title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
ReactJS ES6 - GeeksforGeeks
|
08 Oct, 2021
ES6, also known as ECMA script 2015 is a scripting language which is based on specification and standardization by ECMA International Company in ECMA-262 and ISO/IEC 1623. It is the sixth edition of the ECMAScript language specification standard. It was created to standardize JavaScript language to bring multiple implementations. It has introduced several new features such as a new loop for iterating over arrays, block-scoped variables, template literals, and many more Changes to make JavaScript programming easier. ECMA Script is most commonly used for client-side scripting, specifically in the World Wide Web. It is in huge demand for writing server-based applications and broader services by making use of node.js.
Definition: ES6 is the ECMA script programming language, the next version after 5 was released in 2015. It is used to create the standards for JavaScript language such that it can bring multiple independent implementations.
How to use ES6? ES6 is usually supported in a lot of places but has the problem of Internet Explorer. So, while you just start writing with ES6 style, you can’t be certain if everyone’s browser will behave the same way.
Nowadays, ES6 is compiled down to ‘regular’ ES5 syntax with the help of utility like Babel. Babel is a compiler that helps in converting your development code which is written in ES6 to the code that will run on your production site, often bundled and minifies with web-pack as well.
Working: You write your ‘.js‘ files in the development environment and can use whatever ES6 syntax that you want. Rather than loading them directly, you set up a web-pack to load js files with Babel. Often, you’ll want to run webpack-dev-server, so this happens automatically when you make changes. Now, instead of loading index.js, you load bundle.js, which has all of your code.
let keyword: ES6 has introduced the new let keyword for declaring variables. Before ES6 was introduced the only way to declaring a variable was to use the keyword var.
Variables declared using the var keyword are functionally scoped whereas variables declared using the let keyword are block-scoped. Also, variables are hoisted at the top within its scope if declared using the keyword var, but there’s no hoisting when variables are declared using the let keyword.
Block scoping means that jumbling all the JavaScript statements into one block. It creates a new scope between a pair of curly brackets i.e. {}. So, if you declare a variable using the let keyword, it won’t exist outside that loop. Let’s see an example:
// ES6 Syntax
for(let i = 0; i < 10; i++) {
// Prints '0,1,2,.....9'
console.log(i);
}
// Prints 'undefined'
console.log(i);
// ES5 Syntax
for(var i = 0; i < 10; i++) {
// Prints '0,1,2,.....9'
console.log(i);
}
// Prints '10'
console.log(i);
Therefore, you can see that the variable i in the ES6 syntax is not accessible outside the for-loop. This has the advantage of using the same variable name multiple times since the scope is limited to the block i.e. {}.
const keyword: The const keyword is used to define constants. Constants are read-only, which means that you cannot reassign any new value to them. They are also block-scoped like let keyword.
// Creating a constant variable
const PI = 3.14;
// Prints '3.14'
console.log(PI);
// Throws an Error
PI = 777;
Example: Code to illustrates how to change object properties or array elements as shown below:
// Sample object with some properties
const Branch = {name: "IT", students: 55};
// Prints 'IT'
console.log(Branch.name);
// Changing the object property value
Branch.name = "CSE";
// Prints 'CSE'
console.log(Branch.name);
// Sample array with some values
const Fruits = ["apple", "mango", "banana"];
// Prints 'apple'
console.log(Fruits[0]);
// Changing array element
Fruits[0] = "grapes";
// Prints 'grapes'
console.log(Fruits[0]);
for-of Loop: The for-of loop is used to iterate over arrays or any other iterable objects very easily. Also, using this type of loop each element of the iterable object inside the loop is executed.
Example: Code to illustrate how to use the for-of loop in ReactJs as shown below:
// Iterating over array
let colors = ["red", "blue", "green",
"yellow", "pink", "purple"];
// Using the for-of loop
for (let color of colors) {
// Prints 'red,blue,green,yellow,pink,purple'
console.log(color);
}
// Iterating over string
let name = "Alpha Charlie";
// Using the for-of loop
for(let character of name) {
// Prints 'A,l,p,h,a, ,C,h,a,r,l,i,e'
console.log(character);
}
Template Literals: Template literals help in providing an easy and clean way to write multiple lines of strings and perform string interpolation. It has also made it easy to embed variables or expressions into a string at any place.
Now, Back-ticks(` `) characters are used to create template literals instead of single and double-quotes. Variables and expressions can be placed inside the string using template literals syntax.
Example: Use of multi-line string in ES6.
// Multi-line string in ES6
let str = `Jack and Jill
went up the hill.`;
// Sample values
let a = 30;
let b = 10;
// String with embedded variables
// and expression
let answer =
`The difference of ${30} and ${10} is ${a-b}.`;
// Prints 'The difference of 30 and 10 is 20.'
console.log(answer);
Example: Use of multi-line string in ES5.
// Multi-line string in ES5
var str = 'Jack and Jill\n\t'
+ 'went up the hill.';
// Sample values
var a = 30;
var b = 10;
// Creating string using variables
// and expression
var answer = 'The difference of ' + a
+ ' and ' + b + ' is ' + (a-b) + '.';
// Prints 'The difference of 30 and 10 is 20.'
console.log(answer);
Arrow Functions: Arrow functions have made it very easy to create functions. It is an expression closure that creates nice and compact functions, especially when working with callbacks, lists, or error handling.
// Arrow functions
arr.map((func) => {
return func + 1;
});
Additionally, you don’t need the parentheses if you pass only one argument. Also, no brackets and return statements if you’re returning only one value:
arr.map(func => func + 1);
Without using arrow functions, the syntax would be like this:
// Without Arrow functions
arr.map(function (func) {
return func + 1;
});
surindertarika1234
React-misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26571,
"s": 26543,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 27295,
"s": 26571,
"text": "ES6, also known as ECMA script 2015 is a scripting language which is based on specification and standardization by ECMA International Company in ECMA-262 and ISO/IEC 1623. It is the sixth edition of the ECMAScript language specification standard. It was created to standardize JavaScript language to bring multiple implementations. It has introduced several new features such as a new loop for iterating over arrays, block-scoped variables, template literals, and many more Changes to make JavaScript programming easier. ECMA Script is most commonly used for client-side scripting, specifically in the World Wide Web. It is in huge demand for writing server-based applications and broader services by making use of node.js."
},
{
"code": null,
"e": 27519,
"s": 27295,
"text": "Definition: ES6 is the ECMA script programming language, the next version after 5 was released in 2015. It is used to create the standards for JavaScript language such that it can bring multiple independent implementations."
},
{
"code": null,
"e": 27741,
"s": 27521,
"text": "How to use ES6? ES6 is usually supported in a lot of places but has the problem of Internet Explorer. So, while you just start writing with ES6 style, you can’t be certain if everyone’s browser will behave the same way."
},
{
"code": null,
"e": 28029,
"s": 27745,
"text": "Nowadays, ES6 is compiled down to ‘regular’ ES5 syntax with the help of utility like Babel. Babel is a compiler that helps in converting your development code which is written in ES6 to the code that will run on your production site, often bundled and minifies with web-pack as well."
},
{
"code": null,
"e": 28410,
"s": 28029,
"text": "Working: You write your ‘.js‘ files in the development environment and can use whatever ES6 syntax that you want. Rather than loading them directly, you set up a web-pack to load js files with Babel. Often, you’ll want to run webpack-dev-server, so this happens automatically when you make changes. Now, instead of loading index.js, you load bundle.js, which has all of your code."
},
{
"code": null,
"e": 28581,
"s": 28412,
"text": "let keyword: ES6 has introduced the new let keyword for declaring variables. Before ES6 was introduced the only way to declaring a variable was to use the keyword var. "
},
{
"code": null,
"e": 28883,
"s": 28585,
"text": "Variables declared using the var keyword are functionally scoped whereas variables declared using the let keyword are block-scoped. Also, variables are hoisted at the top within its scope if declared using the keyword var, but there’s no hoisting when variables are declared using the let keyword."
},
{
"code": null,
"e": 29139,
"s": 28885,
"text": "Block scoping means that jumbling all the JavaScript statements into one block. It creates a new scope between a pair of curly brackets i.e. {}. So, if you declare a variable using the let keyword, it won’t exist outside that loop. Let’s see an example:"
},
{
"code": null,
"e": 29276,
"s": 29141,
"text": "// ES6 Syntax\nfor(let i = 0; i < 10; i++) {\n\n // Prints '0,1,2,.....9'\n console.log(i);\n}\n\n// Prints 'undefined'\nconsole.log(i); "
},
{
"code": null,
"e": 29404,
"s": 29276,
"text": "// ES5 Syntax\nfor(var i = 0; i < 10; i++) {\n\n // Prints '0,1,2,.....9'\n console.log(i); \n}\n\n// Prints '10'\nconsole.log(i); "
},
{
"code": null,
"e": 29624,
"s": 29404,
"text": "Therefore, you can see that the variable i in the ES6 syntax is not accessible outside the for-loop. This has the advantage of using the same variable name multiple times since the scope is limited to the block i.e. {}."
},
{
"code": null,
"e": 29816,
"s": 29624,
"text": "const keyword: The const keyword is used to define constants. Constants are read-only, which means that you cannot reassign any new value to them. They are also block-scoped like let keyword."
},
{
"code": null,
"e": 29936,
"s": 29820,
"text": "// Creating a constant variable\nconst PI = 3.14;\n\n// Prints '3.14'\nconsole.log(PI); \n\n// Throws an Error\nPI = 777; "
},
{
"code": null,
"e": 30031,
"s": 29936,
"text": "Example: Code to illustrates how to change object properties or array elements as shown below:"
},
{
"code": null,
"e": 30261,
"s": 30033,
"text": "// Sample object with some properties\nconst Branch = {name: \"IT\", students: 55};\n\n// Prints 'IT'\nconsole.log(Branch.name); \n\n// Changing the object property value\nBranch.name = \"CSE\";\n\n// Prints 'CSE'\nconsole.log(Branch.name); "
},
{
"code": null,
"e": 30477,
"s": 30261,
"text": "// Sample array with some values\nconst Fruits = [\"apple\", \"mango\", \"banana\"];\n\n// Prints 'apple'\nconsole.log(Fruits[0]); \n\n// Changing array element\nFruits[0] = \"grapes\";\n\n// Prints 'grapes'\nconsole.log(Fruits[0]); "
},
{
"code": null,
"e": 30676,
"s": 30477,
"text": "for-of Loop: The for-of loop is used to iterate over arrays or any other iterable objects very easily. Also, using this type of loop each element of the iterable object inside the loop is executed. "
},
{
"code": null,
"e": 30762,
"s": 30680,
"text": "Example: Code to illustrate how to use the for-of loop in ReactJs as shown below:"
},
{
"code": null,
"e": 30994,
"s": 30764,
"text": "// Iterating over array\nlet colors = [\"red\", \"blue\", \"green\", \n \"yellow\", \"pink\", \"purple\"];\n\n// Using the for-of loop\nfor (let color of colors) {\n\n // Prints 'red,blue,green,yellow,pink,purple'\n console.log(color); \n}"
},
{
"code": null,
"e": 31175,
"s": 30994,
"text": "// Iterating over string\nlet name = \"Alpha Charlie\";\n\n// Using the for-of loop \nfor(let character of name) {\n\n // Prints 'A,l,p,h,a, ,C,h,a,r,l,i,e'\n console.log(character); \n}"
},
{
"code": null,
"e": 31408,
"s": 31175,
"text": "Template Literals: Template literals help in providing an easy and clean way to write multiple lines of strings and perform string interpolation. It has also made it easy to embed variables or expressions into a string at any place."
},
{
"code": null,
"e": 31608,
"s": 31412,
"text": "Now, Back-ticks(` `) characters are used to create template literals instead of single and double-quotes. Variables and expressions can be placed inside the string using template literals syntax."
},
{
"code": null,
"e": 31652,
"s": 31610,
"text": "Example: Use of multi-line string in ES6."
},
{
"code": null,
"e": 31959,
"s": 31654,
"text": "// Multi-line string in ES6\nlet str = `Jack and Jill\n went up the hill.`;\n\n// Sample values\nlet a = 30;\nlet b = 10;\n\n// String with embedded variables\n// and expression\nlet answer = \n `The difference of ${30} and ${10} is ${a-b}.`;\n\n// Prints 'The difference of 30 and 10 is 20.'\nconsole.log(answer); "
},
{
"code": null,
"e": 32001,
"s": 31959,
"text": "Example: Use of multi-line string in ES5."
},
{
"code": null,
"e": 32334,
"s": 32003,
"text": "// Multi-line string in ES5\nvar str = 'Jack and Jill\\n\\t'\n + 'went up the hill.';\n\n// Sample values\nvar a = 30;\nvar b = 10;\n\n// Creating string using variables\n// and expression\nvar answer = 'The difference of ' + a \n + ' and ' + b + ' is ' + (a-b) + '.';\n\n// Prints 'The difference of 30 and 10 is 20.'\nconsole.log(answer); "
},
{
"code": null,
"e": 32546,
"s": 32334,
"text": "Arrow Functions: Arrow functions have made it very easy to create functions. It is an expression closure that creates nice and compact functions, especially when working with callbacks, lists, or error handling."
},
{
"code": null,
"e": 32612,
"s": 32550,
"text": "// Arrow functions\narr.map((func) => {\n return func + 1;\n});"
},
{
"code": null,
"e": 32764,
"s": 32612,
"text": "Additionally, you don’t need the parentheses if you pass only one argument. Also, no brackets and return statements if you’re returning only one value:"
},
{
"code": null,
"e": 32793,
"s": 32766,
"text": "arr.map(func => func + 1);"
},
{
"code": null,
"e": 32855,
"s": 32793,
"text": "Without using arrow functions, the syntax would be like this:"
},
{
"code": null,
"e": 32933,
"s": 32857,
"text": "// Without Arrow functions\narr.map(function (func) {\n return func + 1;\n});"
},
{
"code": null,
"e": 32954,
"s": 32935,
"text": "surindertarika1234"
},
{
"code": null,
"e": 32965,
"s": 32954,
"text": "React-misc"
},
{
"code": null,
"e": 32976,
"s": 32965,
"text": "JavaScript"
},
{
"code": null,
"e": 32993,
"s": 32976,
"text": "Web Technologies"
},
{
"code": null,
"e": 33091,
"s": 32993,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33131,
"s": 33091,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33192,
"s": 33131,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33233,
"s": 33192,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 33255,
"s": 33233,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 33309,
"s": 33255,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 33349,
"s": 33309,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33382,
"s": 33349,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33425,
"s": 33382,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 33475,
"s": 33425,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to create Frame by Frame Animation using CSS and JavaScript ? - GeeksforGeeks
|
28 Jul, 2021
Frame by frame animation is a technique where a set of images are shown, one by one in a particular order, maintaining fixed time interval gaps between two consecutive images, to make an illusion of motion to the eyes. Now, in a more technical way, we can say that frame-by-frame animation is a technique where different frames appear, one after another, maintaining fixed time interval gaps in different frames to make the illusion of movement.
We can use the JavaScript setInterval() method to create a frame-by-frame animation. The setInterval() method is used to repeat a particular function at every given time interval, so it can be used in the frame-by-frame animation on the set of frames so that they appear to have fixed time interval gaps in between them.
Syntax:
setInterval(function, milliseconds);
Parameters:
function: The function that has to be executed.
milliseconds: It indicates the length of the time interval in milliseconds between each frame.
Example:
HTML
<!DOCTYPE html><html> <head> <style> img { height: 250px; width: 250px; } .center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 250px; height: 250px; border: 3px solid #73AD21; padding: 2px; } </style></head> <body> <script> var images = new Array() images = ["https://media.geeksforgeeks.org/wp-content/uploads/20210721215006/frame1.PNG","https://media.geeksforgeeks.org/wp-content/uploads/20210721215014/frame2-200x190.PNG","https://media.geeksforgeeks.org/wp-content/uploads/20210721215021/frame3-200x182.PNG" ]; setInterval("Animate()", 400); var x = 0; function Animate() { document.getElementById("img").src = images[x] x++; if (images.length == x) { x = 0; } } </script> <div class="center"> <img id="img" src="https://media.geeksforgeeks.org/wp-content/uploads/20210721215006/frame1.PNG"> <h3>Frame by Frame Animation</h3> </div></body> </html>
Output:
Animation of frames
CSS-Properties
CSS-Questions
JavaScript-Methods
JavaScript-Questions
Picked
CSS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 26647,
"s": 26619,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 27093,
"s": 26647,
"text": "Frame by frame animation is a technique where a set of images are shown, one by one in a particular order, maintaining fixed time interval gaps between two consecutive images, to make an illusion of motion to the eyes. Now, in a more technical way, we can say that frame-by-frame animation is a technique where different frames appear, one after another, maintaining fixed time interval gaps in different frames to make the illusion of movement."
},
{
"code": null,
"e": 27414,
"s": 27093,
"text": "We can use the JavaScript setInterval() method to create a frame-by-frame animation. The setInterval() method is used to repeat a particular function at every given time interval, so it can be used in the frame-by-frame animation on the set of frames so that they appear to have fixed time interval gaps in between them."
},
{
"code": null,
"e": 27422,
"s": 27414,
"text": "Syntax:"
},
{
"code": null,
"e": 27459,
"s": 27422,
"text": "setInterval(function, milliseconds);"
},
{
"code": null,
"e": 27471,
"s": 27459,
"text": "Parameters:"
},
{
"code": null,
"e": 27519,
"s": 27471,
"text": "function: The function that has to be executed."
},
{
"code": null,
"e": 27614,
"s": 27519,
"text": "milliseconds: It indicates the length of the time interval in milliseconds between each frame."
},
{
"code": null,
"e": 27623,
"s": 27614,
"text": "Example:"
},
{
"code": null,
"e": 27628,
"s": 27623,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> img { height: 250px; width: 250px; } .center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 250px; height: 250px; border: 3px solid #73AD21; padding: 2px; } </style></head> <body> <script> var images = new Array() images = [\"https://media.geeksforgeeks.org/wp-content/uploads/20210721215006/frame1.PNG\",\"https://media.geeksforgeeks.org/wp-content/uploads/20210721215014/frame2-200x190.PNG\",\"https://media.geeksforgeeks.org/wp-content/uploads/20210721215021/frame3-200x182.PNG\" ]; setInterval(\"Animate()\", 400); var x = 0; function Animate() { document.getElementById(\"img\").src = images[x] x++; if (images.length == x) { x = 0; } } </script> <div class=\"center\"> <img id=\"img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210721215006/frame1.PNG\"> <h3>Frame by Frame Animation</h3> </div></body> </html>",
"e": 28810,
"s": 27628,
"text": null
},
{
"code": null,
"e": 28818,
"s": 28810,
"text": "Output:"
},
{
"code": null,
"e": 28838,
"s": 28818,
"text": "Animation of frames"
},
{
"code": null,
"e": 28853,
"s": 28838,
"text": "CSS-Properties"
},
{
"code": null,
"e": 28867,
"s": 28853,
"text": "CSS-Questions"
},
{
"code": null,
"e": 28886,
"s": 28867,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 28907,
"s": 28886,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28914,
"s": 28907,
"text": "Picked"
},
{
"code": null,
"e": 28918,
"s": 28914,
"text": "CSS"
},
{
"code": null,
"e": 28929,
"s": 28918,
"text": "JavaScript"
},
{
"code": null,
"e": 28946,
"s": 28929,
"text": "Web Technologies"
},
{
"code": null,
"e": 29044,
"s": 28946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29083,
"s": 29044,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29120,
"s": 29083,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29149,
"s": 29120,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29191,
"s": 29149,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29226,
"s": 29191,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 29266,
"s": 29226,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29311,
"s": 29266,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29372,
"s": 29311,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29444,
"s": 29372,
"text": "Differences between Functional Components and Class Components in React"
}
] |
TypeScript | Array forEach() Method - GeeksforGeeks
|
18 Jun, 2020
The Array.forEach() is an inbuilt TypeScript function which is used to calls a function for each element in the array. Syntax:
array.forEach(callback[, thisObject])
Parameter: This method accepts two parameter as mentioned above and described below:
callback : This parameter is the Function to test for each element.
thisObject : This parameter is the Object to use as this when executing callback.
Return Value: This method returns created array. Below example illustrate the Array forEach() Method in TypeScript.
Example 1:
JavaScript
<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // printing eah element arr.forEach(function (value) { console.log(value); });</script>
Output:
11
89
23
7
98
Example 2:
JavaScript
<script> // Driver code var arr = [ 1, 2, 3, 4, 5 ]; // printing square of element arr.forEach(function (value) { console.log(value * value); });</script>
Output:
1
4
9
16
25
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25679,
"s": 25651,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 25807,
"s": 25679,
"text": "The Array.forEach() is an inbuilt TypeScript function which is used to calls a function for each element in the array. Syntax: "
},
{
"code": null,
"e": 25845,
"s": 25807,
"text": "array.forEach(callback[, thisObject])"
},
{
"code": null,
"e": 25931,
"s": 25845,
"text": "Parameter: This method accepts two parameter as mentioned above and described below: "
},
{
"code": null,
"e": 25999,
"s": 25931,
"text": "callback : This parameter is the Function to test for each element."
},
{
"code": null,
"e": 26081,
"s": 25999,
"text": "thisObject : This parameter is the Object to use as this when executing callback."
},
{
"code": null,
"e": 26197,
"s": 26081,
"text": "Return Value: This method returns created array. Below example illustrate the Array forEach() Method in TypeScript."
},
{
"code": null,
"e": 26209,
"s": 26197,
"text": "Example 1: "
},
{
"code": null,
"e": 26220,
"s": 26209,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // printing eah element arr.forEach(function (value) { console.log(value); });</script>",
"e": 26395,
"s": 26220,
"text": null
},
{
"code": null,
"e": 26404,
"s": 26395,
"text": "Output: "
},
{
"code": null,
"e": 26419,
"s": 26404,
"text": "11\n89\n23\n7\n98\n"
},
{
"code": null,
"e": 26431,
"s": 26419,
"text": "Example 2: "
},
{
"code": null,
"e": 26442,
"s": 26431,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [ 1, 2, 3, 4, 5 ]; // printing square of element arr.forEach(function (value) { console.log(value * value); });</script>",
"e": 26628,
"s": 26442,
"text": null
},
{
"code": null,
"e": 26637,
"s": 26628,
"text": "Output: "
},
{
"code": null,
"e": 26650,
"s": 26637,
"text": "1\n4\n9\n16\n25\n"
},
{
"code": null,
"e": 26661,
"s": 26650,
"text": "TypeScript"
},
{
"code": null,
"e": 26672,
"s": 26661,
"text": "JavaScript"
},
{
"code": null,
"e": 26689,
"s": 26672,
"text": "Web Technologies"
},
{
"code": null,
"e": 26787,
"s": 26689,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26827,
"s": 26787,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26872,
"s": 26827,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26933,
"s": 26872,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27005,
"s": 26933,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27057,
"s": 27005,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27097,
"s": 27057,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27130,
"s": 27097,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27175,
"s": 27130,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27218,
"s": 27175,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
RapidScan – The Multi-Tool Web Vulnerability Scanner in Kali Linux - GeeksforGeeks
|
30 Jun, 2021
RapidScan is a free and open-source tool available on GitHub which is based upon Open Source Intelligence (OSINT), the easiest and useful tool for reconnaissance. The RapidScan interface is very similar to Metasploit 1 and Metasploit 2, which provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain), which can be a website or an IP address. The interactive console provides a number of helpful features, such as command completion and contextual help. RapidScan is a web reconnaissance tool written in python. It has so many modules, such as database interaction, built-in convenience functions, interactive help, and command completion. RapidScan provides a powerful environment in which open-source web-based reconnaissance can be conducted and you can gather all the information about the target.
RapidScan’s interactive console provides a number of helpful features.
RapidScan is used for information gathering and vulnerability assessment of web applications.
RapidScan uses the Shodan search engine to scan IoT devices.
RapidScan can easily find loopholes in the code of web applications and websites.
RapidScan has the following modules: Geo lookup, banner grabbing, DNS lookup, port scanning. These modules make this tool so powerful.
Step 1: Use the following command to install the tool.
git clone https://github.com/skavngr/rapidscan.git
cd rapidscan
Step 2: Now give permission to the tool using the following command and run the tool using the following command.
chmod +x rapidscan.py
./rapidscan.py
The tool has been downloaded successfully.
Example 1: Use the RapidScan tool to scan a website.
./rapidscan.py <domain>
We have scanned our geeksforgeeks.org domain.
Example 2: Use the RapidScan tool to scan another website.
./rapidscan.py <domain>
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26527,
"s": 25651,
"text": "RapidScan is a free and open-source tool available on GitHub which is based upon Open Source Intelligence (OSINT), the easiest and useful tool for reconnaissance. The RapidScan interface is very similar to Metasploit 1 and Metasploit 2, which provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain), which can be a website or an IP address. The interactive console provides a number of helpful features, such as command completion and contextual help. RapidScan is a web reconnaissance tool written in python. It has so many modules, such as database interaction, built-in convenience functions, interactive help, and command completion. RapidScan provides a powerful environment in which open-source web-based reconnaissance can be conducted and you can gather all the information about the target."
},
{
"code": null,
"e": 26598,
"s": 26527,
"text": "RapidScan’s interactive console provides a number of helpful features."
},
{
"code": null,
"e": 26692,
"s": 26598,
"text": "RapidScan is used for information gathering and vulnerability assessment of web applications."
},
{
"code": null,
"e": 26753,
"s": 26692,
"text": "RapidScan uses the Shodan search engine to scan IoT devices."
},
{
"code": null,
"e": 26835,
"s": 26753,
"text": "RapidScan can easily find loopholes in the code of web applications and websites."
},
{
"code": null,
"e": 26970,
"s": 26835,
"text": "RapidScan has the following modules: Geo lookup, banner grabbing, DNS lookup, port scanning. These modules make this tool so powerful."
},
{
"code": null,
"e": 27025,
"s": 26970,
"text": "Step 1: Use the following command to install the tool."
},
{
"code": null,
"e": 27089,
"s": 27025,
"text": "git clone https://github.com/skavngr/rapidscan.git\ncd rapidscan"
},
{
"code": null,
"e": 27203,
"s": 27089,
"text": "Step 2: Now give permission to the tool using the following command and run the tool using the following command."
},
{
"code": null,
"e": 27241,
"s": 27203,
"text": "chmod +x rapidscan.py\n\n./rapidscan.py"
},
{
"code": null,
"e": 27285,
"s": 27241,
"text": " The tool has been downloaded successfully."
},
{
"code": null,
"e": 27338,
"s": 27285,
"text": "Example 1: Use the RapidScan tool to scan a website."
},
{
"code": null,
"e": 27362,
"s": 27338,
"text": "./rapidscan.py <domain>"
},
{
"code": null,
"e": 27408,
"s": 27362,
"text": "We have scanned our geeksforgeeks.org domain."
},
{
"code": null,
"e": 27467,
"s": 27408,
"text": "Example 2: Use the RapidScan tool to scan another website."
},
{
"code": null,
"e": 27491,
"s": 27467,
"text": "./rapidscan.py <domain>"
},
{
"code": null,
"e": 27502,
"s": 27491,
"text": "Kali-Linux"
},
{
"code": null,
"e": 27514,
"s": 27502,
"text": "Linux-Tools"
},
{
"code": null,
"e": 27525,
"s": 27514,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27623,
"s": 27525,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27658,
"s": 27623,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27692,
"s": 27658,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27718,
"s": 27692,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27747,
"s": 27718,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27784,
"s": 27747,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27821,
"s": 27784,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27863,
"s": 27821,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27889,
"s": 27863,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27925,
"s": 27889,
"text": "uniq Command in LINUX with examples"
}
] |
Scope Resolution in Python | LEGB Rule - GeeksforGeeks
|
27 Nov, 2018
Namespaces : A namespace is a container where names are mapped to objects, they are used to avoid confusions in cases where same names exist in different namespaces. They are created by modules, functions, classes etc.
Scope : A scope defines the hierarchical order in which the namespaces have to be searched in order to obtain the mappings of name-to-object(variables). It is a context in which variables exist and from which they are referenced. It defines the accessibility and the lifetime of a variable. Let us take a simple example as shown below:
pi = 'outer pi variable' def print_pi(): pi = 'inner pi variable' print(pi) print_pi()print(pi)
Output:
inner pi variable
outer pi variable
Above program give different outputs because the same variable name pi resides in different namespaces, one inside the function print_pi and the other in the upper level. When print_pi() gets executed, ‘inner pi variable‘ is printed as that is pi value inside the function namespace. The value ‘outer pi variable‘ is printed when pi is referenced in the outer namespace. From the above example, we can guess that there definitely is a rule which is followed, in order in decide from which namespace a variable has to be picked. Scope resolution via LEGB rule :In Python, the LEGB rule is used to decide the order in which the namespaces are to be searched for scope resolution.The scopes are listed below in terms of hierarchy(highest to lowest/narrowest to broadest):
Local(L): Defined inside function/class
Enclosed(E): Defined inside enclosing functions(Nested function concept)
Global(G): Defined at the uppermost level
Built-in(B): Reserved names in Python builtin modules
Local Scope :Local scope refers to variables defined in current function.Always, a function will first look up for a variable name in its local scope. Only if it does not find it there, the outer scopes are checked.
# Local Scope pi = 'global pi variable'def inner(): pi = 'inner pi variable' print(pi) inner()
Output:
inner pi variable
On running the above program, the execution of the inner function prints the value of its local(highest priority in LEGB rule) variable pi because it is defined and available in the local scope.
Local and Global Scopes :If a variable is not defined in local scope, then, it is checked for in the higher scope, in this case, the global scope.
# Global Scope pi = 'global pi variable'def inner(): pi = 'inner pi variable' print(pi) inner()print(pi)
Output:
inner pi variable
global pi variable
Therefore, as expected the program prints out the value in the local scope on execution of inner(). It is because it is defined inside the function and that is the first place where the variable is looked up. The pi value in global scope is printed on execution of print(pi) on line 9. Local, Enclosed and Global Scopes :For the enclosed scope, we need to define an outer function enclosing the inner function, comment out the local pi variable of inner function and refer to pi using the nonlocal keyword.
# Enclosed Scope pi = 'global pi variable' def outer(): pi = 'outer pi variable' def inner(): # pi = 'inner pi variable' nonlocal pi print(pi) inner() outer()print(pi)
Output:
outer pi variable
global pi variable
When outer() is executed, inner() and consequently the print functions are executed, which print the value the enclosed pi variable. The statement in line 10 looks for variable in local scope of inner, but does not find it there. Since pi is referred with the nonlocal keyword, it means that pi needs to be accessed from the outer function(i.e the outer scope). To summarize, the pi variable is not found in local scope, so the higher scopes are looked up. It is found in both enclosed and global scopes. But as per the LEGB hierarchy, the enclosed scope variable is considered even though we have one defined in the global scope. Local,Enclosed,Global and Built-in Scopes :The final check can be done by importing pi from math module and commenting the global, enclosed and local pi variables as shown below:
# Built-in Scopefrom math import pi # pi = 'global pi variable' def outer(): # pi = 'outer pi variable' def inner(): # pi = 'inner pi variable' print(pi) inner() outer()
Output:
3.141592653589793
Since, pi is not defined in either local, enclosed or global scope, the built-in scope is looked up i.e the pi value imported from math module. Since the program is able to find the value of pi in the outermost scope, the following output is obtained,
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n27 Nov, 2018"
},
{
"code": null,
"e": 25780,
"s": 25561,
"text": "Namespaces : A namespace is a container where names are mapped to objects, they are used to avoid confusions in cases where same names exist in different namespaces. They are created by modules, functions, classes etc."
},
{
"code": null,
"e": 26116,
"s": 25780,
"text": "Scope : A scope defines the hierarchical order in which the namespaces have to be searched in order to obtain the mappings of name-to-object(variables). It is a context in which variables exist and from which they are referenced. It defines the accessibility and the lifetime of a variable. Let us take a simple example as shown below:"
},
{
"code": "pi = 'outer pi variable' def print_pi(): pi = 'inner pi variable' print(pi) print_pi()print(pi)",
"e": 26220,
"s": 26116,
"text": null
},
{
"code": null,
"e": 26228,
"s": 26220,
"text": "Output:"
},
{
"code": null,
"e": 26265,
"s": 26228,
"text": "inner pi variable\nouter pi variable\n"
},
{
"code": null,
"e": 27034,
"s": 26265,
"text": "Above program give different outputs because the same variable name pi resides in different namespaces, one inside the function print_pi and the other in the upper level. When print_pi() gets executed, ‘inner pi variable‘ is printed as that is pi value inside the function namespace. The value ‘outer pi variable‘ is printed when pi is referenced in the outer namespace. From the above example, we can guess that there definitely is a rule which is followed, in order in decide from which namespace a variable has to be picked. Scope resolution via LEGB rule :In Python, the LEGB rule is used to decide the order in which the namespaces are to be searched for scope resolution.The scopes are listed below in terms of hierarchy(highest to lowest/narrowest to broadest):"
},
{
"code": null,
"e": 27074,
"s": 27034,
"text": "Local(L): Defined inside function/class"
},
{
"code": null,
"e": 27147,
"s": 27074,
"text": "Enclosed(E): Defined inside enclosing functions(Nested function concept)"
},
{
"code": null,
"e": 27189,
"s": 27147,
"text": "Global(G): Defined at the uppermost level"
},
{
"code": null,
"e": 27243,
"s": 27189,
"text": "Built-in(B): Reserved names in Python builtin modules"
},
{
"code": null,
"e": 27459,
"s": 27243,
"text": "Local Scope :Local scope refers to variables defined in current function.Always, a function will first look up for a variable name in its local scope. Only if it does not find it there, the outer scopes are checked."
},
{
"code": "# Local Scope pi = 'global pi variable'def inner(): pi = 'inner pi variable' print(pi) inner()",
"e": 27562,
"s": 27459,
"text": null
},
{
"code": null,
"e": 27570,
"s": 27562,
"text": "Output:"
},
{
"code": null,
"e": 27589,
"s": 27570,
"text": "inner pi variable\n"
},
{
"code": null,
"e": 27785,
"s": 27589,
"text": " On running the above program, the execution of the inner function prints the value of its local(highest priority in LEGB rule) variable pi because it is defined and available in the local scope."
},
{
"code": null,
"e": 27932,
"s": 27785,
"text": "Local and Global Scopes :If a variable is not defined in local scope, then, it is checked for in the higher scope, in this case, the global scope."
},
{
"code": "# Global Scope pi = 'global pi variable'def inner(): pi = 'inner pi variable' print(pi) inner()print(pi)",
"e": 28045,
"s": 27932,
"text": null
},
{
"code": null,
"e": 28053,
"s": 28045,
"text": "Output:"
},
{
"code": null,
"e": 28091,
"s": 28053,
"text": "inner pi variable\nglobal pi variable\n"
},
{
"code": null,
"e": 28598,
"s": 28091,
"text": "Therefore, as expected the program prints out the value in the local scope on execution of inner(). It is because it is defined inside the function and that is the first place where the variable is looked up. The pi value in global scope is printed on execution of print(pi) on line 9. Local, Enclosed and Global Scopes :For the enclosed scope, we need to define an outer function enclosing the inner function, comment out the local pi variable of inner function and refer to pi using the nonlocal keyword."
},
{
"code": "# Enclosed Scope pi = 'global pi variable' def outer(): pi = 'outer pi variable' def inner(): # pi = 'inner pi variable' nonlocal pi print(pi) inner() outer()print(pi)",
"e": 28799,
"s": 28598,
"text": null
},
{
"code": null,
"e": 28807,
"s": 28799,
"text": "Output:"
},
{
"code": null,
"e": 28845,
"s": 28807,
"text": "outer pi variable\nglobal pi variable\n"
},
{
"code": null,
"e": 29655,
"s": 28845,
"text": "When outer() is executed, inner() and consequently the print functions are executed, which print the value the enclosed pi variable. The statement in line 10 looks for variable in local scope of inner, but does not find it there. Since pi is referred with the nonlocal keyword, it means that pi needs to be accessed from the outer function(i.e the outer scope). To summarize, the pi variable is not found in local scope, so the higher scopes are looked up. It is found in both enclosed and global scopes. But as per the LEGB hierarchy, the enclosed scope variable is considered even though we have one defined in the global scope. Local,Enclosed,Global and Built-in Scopes :The final check can be done by importing pi from math module and commenting the global, enclosed and local pi variables as shown below:"
},
{
"code": "# Built-in Scopefrom math import pi # pi = 'global pi variable' def outer(): # pi = 'outer pi variable' def inner(): # pi = 'inner pi variable' print(pi) inner() outer()",
"e": 29851,
"s": 29655,
"text": null
},
{
"code": null,
"e": 29859,
"s": 29851,
"text": "Output:"
},
{
"code": null,
"e": 29878,
"s": 29859,
"text": "3.141592653589793\n"
},
{
"code": null,
"e": 30130,
"s": 29878,
"text": "Since, pi is not defined in either local, enclosed or global scope, the built-in scope is looked up i.e the pi value imported from math module. Since the program is able to find the value of pi in the outermost scope, the following output is obtained,"
},
{
"code": null,
"e": 30144,
"s": 30130,
"text": "python-basics"
},
{
"code": null,
"e": 30151,
"s": 30144,
"text": "Python"
},
{
"code": null,
"e": 30249,
"s": 30151,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30281,
"s": 30249,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30323,
"s": 30281,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30365,
"s": 30323,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30392,
"s": 30365,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30448,
"s": 30392,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30470,
"s": 30448,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30509,
"s": 30470,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30540,
"s": 30509,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30569,
"s": 30540,
"text": "Create a directory in Python"
}
] |
Java Program to Join Contents of More than One Table & Display in JDBC - GeeksforGeeks
|
11 Aug, 2021
Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. First, need to decide, which database we are using and accordingly, we need to add the jars. For other databases like Progress, Cassandra, etc also we have jars and need to include them in the build path. There are different kinds of joins available in MySQL and depends upon the requirement, we can frame queries.
Join is a join that provides the facility to connect two tables are merged with each other according to a field that is common and creates a new virtual table.
NATURAL JOIN: It is a type of join that retrieves data within specified tables to a specific field that is matched.
NATURAL LEFT JOIN: In this operation, both tables are merged with each other according to common fields but the priority is given to the first table in the database.
NATURAL RIGHT JOIN: It also the same as Natural left join but it retrieves the data from the second table in the database.
MySQL tables that are used in code:
First table
CREATE TABLE `studentsdetails` (
`id` int(6) unsigned NOT NULL,
`Name` varchar(50) NOT NULL,
`caste` varchar(10) NOT NULL,
`NeetMarks` int(11) NOT NULL,
`gender` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Second table
CREATE TABLE `studentspersonaldetails` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(30) NOT NULL,
`Address` varchar(30) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`reg_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
In both tables, “Name” is the common column. 1st table specifies Gender, NeetMarks, Caste, etc whereas 2nd table specifies the address, email, etc. Now only necessity is to create an SQL query to join the table which is as follows:
SELECT * FROM " + "studentsdetails" + " NATURAL JOIN " + "studentspersonaldetails"
Now as this query is executed it retrieves data within specified tables to a specific field is matched, it will match records in both tables depends upon “Name” column, implementing the Natural join concept in play. Now the program depends upon the data present in both tables and for matching values of “Name” column in both tables to get the desired output.
Implementation: Now executing the above query command with the help of the below program as per Natural Join.
Java
// Java Program to Join Contents// of More than One Table & Display in JDBC // Step 1: Importing DB files // Provides the API for accessing and processing// data stored in a data sourceimport java.sql.*; // Class for Joining of multiple tablespublic class GFG { // Main driver method public static void main(String[] args) { // Display message System.out.println( "Joining 2 MySQL tables using Natural Join"); // DB 'Connection' object of Connection class Connection con = null; // Try block to check exceptions try { // Step 2: Load and register drivers // Loading driver // Jars(relevant) or mysql-connector-java-8.0.22 // in build path of project Class.forName("com.mysql.cj.jdbc.Driver"); // Registering driver // test is database name here // serverTimezone=UTC, if not provided we will // have java.sql.SQLException // Credentials here are root/"" // i.e. username is root // password is "" // Step 3: Establishing a connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", ""); // Try block to check java exceptions try { // Step 4: Write a statement // Join Statement st = con.createStatement(); // Combining two tables in query using // NATURAL JOIN studentsdetails columns : // Name,caste,NeetMarks,gender // studentspersonaldetails columns : // Name,Address,email // In both tables, connecting columns are // Name Name is taken Here res will have the // data from // both studentsdetails and // studentspersonaldetails whenever "Name" // in both tables are matched join ResultSet res = st.executeQuery( "SELECT *FROM " + "studentsdetails" + " NATURAL JOIN " + "studentspersonaldetails"); // Step 5: Execute the query System.out.println(" StuName" + " Gender" + " Caste " + "Neet Marks" + " Email"); // Step 6: Process the statements // Iterate the resultset and retrieve the // required fields while (res.next()) { String name = res.getString("Name"); String gender = res.getString("gender"); String caste = res.getString("caste"); String neetMarks = res.getString("NeetMarks"); String email = res.getString("email"); // Beautification of output System.out.format( "%10s%10s%10s%10s%20s\n", name, gender, caste, neetMarks, email); } // Step 7: Close the connection con.close(); } // Catch bloack to handle DB exceptions catch (SQLException s) { // If there is error in SQL query, this // exception occurs System.out.println( "SQL statement is not executed!"); } // Catch bloack to handle generic java // exceptions } catch (Exception e) { // General exception apart from SQLException are // caught here e.printStackTrace(); } }}
Output :
Similarly, we can use the rest of the other joins too in the SQL query. Join and Natural join alone makes columns matching in both tables and display data from both tables. As per the requirements, for
Natural left join: Priority goes to the first table.Natural right join: Priority goes to the second table.
Natural left join: Priority goes to the first table.
Natural right join: Priority goes to the second table.
For different servers, there are different jar files used.
For SQL
Step 1: Load the driver class
jar to be used: sqljdbc4.jar
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Step 2: Create a connection for which the connection string “HOSP_SQL1.company.com” is a user-defined one. Similarly, we can use username, password, the database can be used as shown
Connection conn = DriverManager.getConnection(“jdbc:sqlserver://HOSP_SQL1.company.com;user=name;password=abcdefg;database=Test”);
For Oracle
Step 1: Load the driver class
jar to be used: ojdbc14.jar
Class.forName("oracle.jdbc.driver.OracleDriver");
Step 2: Create a connection object followed by username and password
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
simranarora5sos
surindertarika1234
JDBC
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.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 25747,
"s": 25719,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 26222,
"s": 25747,
"text": "Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. First, need to decide, which database we are using and accordingly, we need to add the jars. For other databases like Progress, Cassandra, etc also we have jars and need to include them in the build path. There are different kinds of joins available in MySQL and depends upon the requirement, we can frame queries."
},
{
"code": null,
"e": 26382,
"s": 26222,
"text": "Join is a join that provides the facility to connect two tables are merged with each other according to a field that is common and creates a new virtual table."
},
{
"code": null,
"e": 26498,
"s": 26382,
"text": "NATURAL JOIN: It is a type of join that retrieves data within specified tables to a specific field that is matched."
},
{
"code": null,
"e": 26664,
"s": 26498,
"text": "NATURAL LEFT JOIN: In this operation, both tables are merged with each other according to common fields but the priority is given to the first table in the database."
},
{
"code": null,
"e": 26787,
"s": 26664,
"text": "NATURAL RIGHT JOIN: It also the same as Natural left join but it retrieves the data from the second table in the database."
},
{
"code": null,
"e": 26823,
"s": 26787,
"text": "MySQL tables that are used in code:"
},
{
"code": null,
"e": 26835,
"s": 26823,
"text": "First table"
},
{
"code": null,
"e": 27088,
"s": 26835,
"text": "CREATE TABLE `studentsdetails` (\n `id` int(6) unsigned NOT NULL,\n `Name` varchar(50) NOT NULL,\n `caste` varchar(10) NOT NULL,\n `NeetMarks` int(11) NOT NULL,\n `gender` varchar(10) DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;"
},
{
"code": null,
"e": 27101,
"s": 27088,
"text": "Second table"
},
{
"code": null,
"e": 27455,
"s": 27101,
"text": "CREATE TABLE `studentspersonaldetails` (\n `id` int(6) unsigned NOT NULL AUTO_INCREMENT,\n `Name` varchar(30) NOT NULL,\n `Address` varchar(30) NOT NULL,\n `email` varchar(50) DEFAULT NULL,\n `reg_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;"
},
{
"code": null,
"e": 27687,
"s": 27455,
"text": "In both tables, “Name” is the common column. 1st table specifies Gender, NeetMarks, Caste, etc whereas 2nd table specifies the address, email, etc. Now only necessity is to create an SQL query to join the table which is as follows:"
},
{
"code": null,
"e": 27770,
"s": 27687,
"text": "SELECT * FROM \" + \"studentsdetails\" + \" NATURAL JOIN \" + \"studentspersonaldetails\""
},
{
"code": null,
"e": 28130,
"s": 27770,
"text": "Now as this query is executed it retrieves data within specified tables to a specific field is matched, it will match records in both tables depends upon “Name” column, implementing the Natural join concept in play. Now the program depends upon the data present in both tables and for matching values of “Name” column in both tables to get the desired output."
},
{
"code": null,
"e": 28240,
"s": 28130,
"text": "Implementation: Now executing the above query command with the help of the below program as per Natural Join."
},
{
"code": null,
"e": 28245,
"s": 28240,
"text": "Java"
},
{
"code": "// Java Program to Join Contents// of More than One Table & Display in JDBC // Step 1: Importing DB files // Provides the API for accessing and processing// data stored in a data sourceimport java.sql.*; // Class for Joining of multiple tablespublic class GFG { // Main driver method public static void main(String[] args) { // Display message System.out.println( \"Joining 2 MySQL tables using Natural Join\"); // DB 'Connection' object of Connection class Connection con = null; // Try block to check exceptions try { // Step 2: Load and register drivers // Loading driver // Jars(relevant) or mysql-connector-java-8.0.22 // in build path of project Class.forName(\"com.mysql.cj.jdbc.Driver\"); // Registering driver // test is database name here // serverTimezone=UTC, if not provided we will // have java.sql.SQLException // Credentials here are root/\"\" // i.e. username is root // password is \"\" // Step 3: Establishing a connection con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/test?serverTimezone=UTC\", \"root\", \"\"); // Try block to check java exceptions try { // Step 4: Write a statement // Join Statement st = con.createStatement(); // Combining two tables in query using // NATURAL JOIN studentsdetails columns : // Name,caste,NeetMarks,gender // studentspersonaldetails columns : // Name,Address,email // In both tables, connecting columns are // Name Name is taken Here res will have the // data from // both studentsdetails and // studentspersonaldetails whenever \"Name\" // in both tables are matched join ResultSet res = st.executeQuery( \"SELECT *FROM \" + \"studentsdetails\" + \" NATURAL JOIN \" + \"studentspersonaldetails\"); // Step 5: Execute the query System.out.println(\" StuName\" + \" Gender\" + \" Caste \" + \"Neet Marks\" + \" Email\"); // Step 6: Process the statements // Iterate the resultset and retrieve the // required fields while (res.next()) { String name = res.getString(\"Name\"); String gender = res.getString(\"gender\"); String caste = res.getString(\"caste\"); String neetMarks = res.getString(\"NeetMarks\"); String email = res.getString(\"email\"); // Beautification of output System.out.format( \"%10s%10s%10s%10s%20s\\n\", name, gender, caste, neetMarks, email); } // Step 7: Close the connection con.close(); } // Catch bloack to handle DB exceptions catch (SQLException s) { // If there is error in SQL query, this // exception occurs System.out.println( \"SQL statement is not executed!\"); } // Catch bloack to handle generic java // exceptions } catch (Exception e) { // General exception apart from SQLException are // caught here e.printStackTrace(); } }}",
"e": 32099,
"s": 28245,
"text": null
},
{
"code": null,
"e": 32111,
"s": 32102,
"text": "Output :"
},
{
"code": null,
"e": 32317,
"s": 32115,
"text": "Similarly, we can use the rest of the other joins too in the SQL query. Join and Natural join alone makes columns matching in both tables and display data from both tables. As per the requirements, for"
},
{
"code": null,
"e": 32425,
"s": 32317,
"text": "Natural left join: Priority goes to the first table.Natural right join: Priority goes to the second table. "
},
{
"code": null,
"e": 32478,
"s": 32425,
"text": "Natural left join: Priority goes to the first table."
},
{
"code": null,
"e": 32534,
"s": 32478,
"text": "Natural right join: Priority goes to the second table. "
},
{
"code": null,
"e": 32595,
"s": 32534,
"text": "For different servers, there are different jar files used. "
},
{
"code": null,
"e": 32603,
"s": 32595,
"text": "For SQL"
},
{
"code": null,
"e": 32633,
"s": 32603,
"text": "Step 1: Load the driver class"
},
{
"code": null,
"e": 32662,
"s": 32633,
"text": "jar to be used: sqljdbc4.jar"
},
{
"code": null,
"e": 32725,
"s": 32662,
"text": "Class.forName(\"com.microsoft.sqlserver.jdbc.SQLServerDriver\");"
},
{
"code": null,
"e": 32910,
"s": 32727,
"text": "Step 2: Create a connection for which the connection string “HOSP_SQL1.company.com” is a user-defined one. Similarly, we can use username, password, the database can be used as shown"
},
{
"code": null,
"e": 33040,
"s": 32910,
"text": "Connection conn = DriverManager.getConnection(“jdbc:sqlserver://HOSP_SQL1.company.com;user=name;password=abcdefg;database=Test”);"
},
{
"code": null,
"e": 33051,
"s": 33040,
"text": "For Oracle"
},
{
"code": null,
"e": 33081,
"s": 33051,
"text": "Step 1: Load the driver class"
},
{
"code": null,
"e": 33109,
"s": 33081,
"text": "jar to be used: ojdbc14.jar"
},
{
"code": null,
"e": 33159,
"s": 33109,
"text": "Class.forName(\"oracle.jdbc.driver.OracleDriver\");"
},
{
"code": null,
"e": 33228,
"s": 33159,
"text": "Step 2: Create a connection object followed by username and password"
},
{
"code": null,
"e": 33330,
"s": 33228,
"text": "Connection con=DriverManager.getConnection( \"jdbc:oracle:thin:@localhost:1521:xe\",\"system\",\"oracle\");"
},
{
"code": null,
"e": 33346,
"s": 33330,
"text": "simranarora5sos"
},
{
"code": null,
"e": 33365,
"s": 33346,
"text": "surindertarika1234"
},
{
"code": null,
"e": 33370,
"s": 33365,
"text": "JDBC"
},
{
"code": null,
"e": 33377,
"s": 33370,
"text": "Picked"
},
{
"code": null,
"e": 33401,
"s": 33377,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 33406,
"s": 33401,
"text": "Java"
},
{
"code": null,
"e": 33420,
"s": 33406,
"text": "Java Programs"
},
{
"code": null,
"e": 33439,
"s": 33420,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33444,
"s": 33439,
"text": "Java"
},
{
"code": null,
"e": 33542,
"s": 33444,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33593,
"s": 33542,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 33623,
"s": 33593,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 33638,
"s": 33623,
"text": "Stream In Java"
},
{
"code": null,
"e": 33657,
"s": 33638,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 33688,
"s": 33657,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 33716,
"s": 33688,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 33760,
"s": 33716,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 33786,
"s": 33760,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 33820,
"s": 33786,
"text": "Convert Double to Integer in Java"
}
] |
Python - English (Latin) to Hindi (Devanagiri) text convertor GUI using Tkinter - GeeksforGeeks
|
10 Jun, 2021
Prerequisites : Introduction to tkinter | Text transliteration from English to Indian languages – Using indic-transliterationPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create GUI applications. Now, it’s up to the imagination or necessity of a developer, what he/she wants to develop using this toolkit.
To create a tkinter :
Importing the module – tkinter
Create the main window (container)
Add any number of widgets to the main window.
Apply the event Trigger on the widgets.
Let’s create a GUI based English(Latin) to Hindi(Devanagari) text-convertor application that can convert text input given by user into Devanagari text.
Below is the implementation :
Python3
# import sanscript class from the indic_transliteration modulefrom indic_transliteration import sanscript # import transliterate method from sanscript# class of the indic_transliteration modulefrom indic_transliteration.sanscript import transliterate # import all functions from the tkinter from tkinter import * # Function to clear both the text areasdef clearAll() : # whole content of text area is deleted text1_field.delete(1.0, END) text2_field.delete(1.0, END) # Function to convert into Devanagari textdef convert() : # get a whole input content from text box # ignoring \n from the text box content input_text = text1_field.get("1.0", "end")[:-1] # converted into the given devanagari # transliterated text output_text = transliterate(input_text, sanscript.ITRANS, sanscript.DEVANAGARI) text2_field.insert('end -1 chars', output_text) # Driver codeif __name__ == "__main__" : # Create a GUI window root = Tk() # Set the background colour of GUI window root.configure(background = 'light green') # Set the configuration of GUI window (WidthxHeight) root.geometry("400x350") # set the name of tkinter GUI window root.title("Converter") # Create Welcome to Latin to Devanagiri text converter headlabel = Label(root, text = 'Welcome to Latin to Devanagiri text converter', fg = 'black', bg = "red") # Create a " Latin Text " label label1 = Label(root, text = " Latin Text ", fg = 'black', bg = 'dark green') # Create a " Devanagiri Text " label label2 = Label(root, text = " Devnagiri Text", fg = 'black', bg = 'dark green') # grid method is used for placing # the widgets at respective positions # in table like structure . headlabel.grid(row = 0, column = 1) # padx keyword argument used to set padding along x-axis . # pady keyword argument used to set padding along y-axis . label1.grid(row = 1, column = 0, padx = 10, pady = 10) label2.grid(row = 3, column = 0, padx = 10, pady = 10) # Create a text area box # for filling or typing the information. text1_field = Text(root, height = 5, width = 25, font = "lucida 13") text2_field = Text(root, height = 5, width = 25, font = "lucida 13") # padx keyword argument used to set padding along x-axis . # pady keyword argument used to set padding along y-axis . text1_field.grid(row = 1, column = 1, padx = 10, pady = 10) text2_field.grid(row = 3, column = 1, padx = 10, pady = 10) # Create a Convert Button and attached # with convert function button1 = Button(root, text = "Convert into Devnagiri text", bg = "red", fg = "black", command = convert) button1.grid(row = 2, column = 1) # Create a Clear Button and attached # with clearAll function button2 = Button(root, text = "Clear", bg = "red", fg = "black", command = clearAll) button2.grid(row = 4, column = 1) # Start the GUI root.mainloop()
Output :
simmytarika5
surinderdawra388
Python Tkinter-exercises
Python Tkinter-projects
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Defaultdict in Python
Enumerate() in Python
sum() function in Python
Python String | replace()
Read a file line by line in Python
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
|
[
{
"code": null,
"e": 26347,
"s": 26319,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 26893,
"s": 26347,
"text": "Prerequisites : Introduction to tkinter | Text transliteration from English to Indian languages – Using indic-transliterationPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create GUI applications. Now, it’s up to the imagination or necessity of a developer, what he/she wants to develop using this toolkit."
},
{
"code": null,
"e": 26915,
"s": 26893,
"text": "To create a tkinter :"
},
{
"code": null,
"e": 26946,
"s": 26915,
"text": "Importing the module – tkinter"
},
{
"code": null,
"e": 26981,
"s": 26946,
"text": "Create the main window (container)"
},
{
"code": null,
"e": 27027,
"s": 26981,
"text": "Add any number of widgets to the main window."
},
{
"code": null,
"e": 27067,
"s": 27027,
"text": "Apply the event Trigger on the widgets."
},
{
"code": null,
"e": 27219,
"s": 27067,
"text": "Let’s create a GUI based English(Latin) to Hindi(Devanagari) text-convertor application that can convert text input given by user into Devanagari text."
},
{
"code": null,
"e": 27251,
"s": 27219,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 27259,
"s": 27251,
"text": "Python3"
},
{
"code": "# import sanscript class from the indic_transliteration modulefrom indic_transliteration import sanscript # import transliterate method from sanscript# class of the indic_transliteration modulefrom indic_transliteration.sanscript import transliterate # import all functions from the tkinter from tkinter import * # Function to clear both the text areasdef clearAll() : # whole content of text area is deleted text1_field.delete(1.0, END) text2_field.delete(1.0, END) # Function to convert into Devanagari textdef convert() : # get a whole input content from text box # ignoring \\n from the text box content input_text = text1_field.get(\"1.0\", \"end\")[:-1] # converted into the given devanagari # transliterated text output_text = transliterate(input_text, sanscript.ITRANS, sanscript.DEVANAGARI) text2_field.insert('end -1 chars', output_text) # Driver codeif __name__ == \"__main__\" : # Create a GUI window root = Tk() # Set the background colour of GUI window root.configure(background = 'light green') # Set the configuration of GUI window (WidthxHeight) root.geometry(\"400x350\") # set the name of tkinter GUI window root.title(\"Converter\") # Create Welcome to Latin to Devanagiri text converter headlabel = Label(root, text = 'Welcome to Latin to Devanagiri text converter', fg = 'black', bg = \"red\") # Create a \" Latin Text \" label label1 = Label(root, text = \" Latin Text \", fg = 'black', bg = 'dark green') # Create a \" Devanagiri Text \" label label2 = Label(root, text = \" Devnagiri Text\", fg = 'black', bg = 'dark green') # grid method is used for placing # the widgets at respective positions # in table like structure . headlabel.grid(row = 0, column = 1) # padx keyword argument used to set padding along x-axis . # pady keyword argument used to set padding along y-axis . label1.grid(row = 1, column = 0, padx = 10, pady = 10) label2.grid(row = 3, column = 0, padx = 10, pady = 10) # Create a text area box # for filling or typing the information. text1_field = Text(root, height = 5, width = 25, font = \"lucida 13\") text2_field = Text(root, height = 5, width = 25, font = \"lucida 13\") # padx keyword argument used to set padding along x-axis . # pady keyword argument used to set padding along y-axis . text1_field.grid(row = 1, column = 1, padx = 10, pady = 10) text2_field.grid(row = 3, column = 1, padx = 10, pady = 10) # Create a Convert Button and attached # with convert function button1 = Button(root, text = \"Convert into Devnagiri text\", bg = \"red\", fg = \"black\", command = convert) button1.grid(row = 2, column = 1) # Create a Clear Button and attached # with clearAll function button2 = Button(root, text = \"Clear\", bg = \"red\", fg = \"black\", command = clearAll) button2.grid(row = 4, column = 1) # Start the GUI root.mainloop() ",
"e": 30407,
"s": 27259,
"text": null
},
{
"code": null,
"e": 30418,
"s": 30407,
"text": "Output : "
},
{
"code": null,
"e": 30435,
"s": 30422,
"text": "simmytarika5"
},
{
"code": null,
"e": 30452,
"s": 30435,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30477,
"s": 30452,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 30501,
"s": 30477,
"text": "Python Tkinter-projects"
},
{
"code": null,
"e": 30512,
"s": 30501,
"text": "Python-gui"
},
{
"code": null,
"e": 30527,
"s": 30512,
"text": "Python-tkinter"
},
{
"code": null,
"e": 30534,
"s": 30527,
"text": "Python"
},
{
"code": null,
"e": 30632,
"s": 30534,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30650,
"s": 30632,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30672,
"s": 30650,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30694,
"s": 30672,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30719,
"s": 30694,
"text": "sum() function in Python"
},
{
"code": null,
"e": 30745,
"s": 30719,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30780,
"s": 30745,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30812,
"s": 30780,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30828,
"s": 30812,
"text": "Deque in Python"
},
{
"code": null,
"e": 30870,
"s": 30828,
"text": "Different ways to create Pandas Dataframe"
}
] |
Handling OSError exception in Python - GeeksforGeeks
|
19 Aug, 2020
Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as “file not found” or “disk full”.
Below is an example of OSError:
Python
# Importing os moduleimport os # os.ttyname() method in Python is used to get the terminal # device associated with the specified file descriptor.# and raises an exception if the specified file descriptor # is not associated with any terminal device.print(os.ttyname(1))
Output :
OSError: [Errno 25] Inappropriate ioctl for device
We can handle an ODError exception using try...except statements.
Python
# importing os module import os # create a pipe using os.pipe() method # it will return a pair of # file descriptors (r, w) usable for # reading and writing, respectively. r, w = os.pipe() # (using exception handling technique) # try to get the terminal device associated # with the file descriptor r or w try : print(os.ttyname(r)) except OSError as error : print(error) print("File descriptor is not associated with any terminal device")
[Errno 25] Inappropriate ioctl for device
File descriptor is not associated with any terminal device
Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 25591,
"s": 25563,
"text": "\n19 Aug, 2020"
},
{
"code": null,
"e": 25885,
"s": 25591,
"text": "Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as “file not found” or “disk full”."
},
{
"code": null,
"e": 25917,
"s": 25885,
"text": "Below is an example of OSError:"
},
{
"code": null,
"e": 25924,
"s": 25917,
"text": "Python"
},
{
"code": "# Importing os moduleimport os # os.ttyname() method in Python is used to get the terminal # device associated with the specified file descriptor.# and raises an exception if the specified file descriptor # is not associated with any terminal device.print(os.ttyname(1))",
"e": 26196,
"s": 25924,
"text": null
},
{
"code": null,
"e": 26205,
"s": 26196,
"text": "Output :"
},
{
"code": null,
"e": 26257,
"s": 26205,
"text": "OSError: [Errno 25] Inappropriate ioctl for device\n"
},
{
"code": null,
"e": 26323,
"s": 26257,
"text": "We can handle an ODError exception using try...except statements."
},
{
"code": null,
"e": 26330,
"s": 26323,
"text": "Python"
},
{
"code": "# importing os module import os # create a pipe using os.pipe() method # it will return a pair of # file descriptors (r, w) usable for # reading and writing, respectively. r, w = os.pipe() # (using exception handling technique) # try to get the terminal device associated # with the file descriptor r or w try : print(os.ttyname(r)) except OSError as error : print(error) print(\"File descriptor is not associated with any terminal device\") ",
"e": 26800,
"s": 26330,
"text": null
},
{
"code": null,
"e": 26901,
"s": 26800,
"text": "[Errno 25] Inappropriate ioctl for device\nFile descriptor is not associated with any terminal device"
},
{
"code": null,
"e": 26919,
"s": 26901,
"text": "Python-exceptions"
},
{
"code": null,
"e": 26926,
"s": 26919,
"text": "Python"
},
{
"code": null,
"e": 27024,
"s": 26926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27042,
"s": 27024,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27074,
"s": 27042,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27096,
"s": 27074,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27138,
"s": 27096,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27168,
"s": 27138,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27194,
"s": 27168,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27223,
"s": 27194,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27260,
"s": 27223,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27302,
"s": 27260,
"text": "Check if element exists in list in Python"
}
] |
Count of words that are present in all the given sentences - GeeksforGeeks
|
27 Dec, 2021
Given n sentences. The task is to count the number of words that appear in all of these sentences. Note that every word consists of only lowercase English alphabets.Examples:
Input: arr[] = { “there is a cow”, “cow is our mother”, “cow gives us milk and milk is sweet”, “there is a boy who loves cow”} Output: 2 Only the words “is” and “cow” appear in all of the sentences.Input: arr[] = { “abc aac abcd ccc”, “ac aa abc cca”, “abca aaac abcd ccc”} Output: 0
Naive Approach: The naive approach is to take every word of the first sentence and compare it with the rest of the lines if it is also present in all lines then increment the count.Efficient Approach: For all the words of the first sentence, we can check if it is also present in all the other sentences in constant time by using a map. Store all the words of the first sentence in a map and check how many of these stored words are present in all the other sentences.
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of common words// in all the sentencesint commonWords(vector<string> S){ int m, n, i, j; // To store separate words string str; // It will be used to check if a word is present // in a particular string unordered_map<string, bool> has; // To store all the words of first string vector<pair<string, bool> > ans; pair<string, bool> tmp; // m will store number of strings in given vector m = S.size(); i = 0; // Extract all words of first string and store it in ans while (i < S[0].size()) { str = ""; while (i < S[0].size() && S[0][i] != ' ') { str += S[0][i]; i++; } // Increase i to get at starting index // of the next word i++; // If str is not empty store it in map if (str != "") { tmp = make_pair(str, true); ans.push_back(tmp); } } // Start from 2nd line check if any word of // the first string did not match with // some word in the current line for (j = 1; j < m; j++) { has.clear(); i = 0; while (i < S[j].size()) { str = ""; while (i < S[j].size() && S[j][i] != ' ') { str += S[j][i]; i++; } i++; if (str != "") { has[str] = true; } } // Check all words of this vector // if it is not present in current line // make it false for (int k = 0; k < ans.size(); k++) { if (ans[k].second != false && has[ans[k].first] == false) { ans[k].second = false; } // This line is used to consider only distinct words else if (ans[k].second != false && has[ans[k].first] == true) { has[ans[k].first] = false; } } } // This function will print // the count of common words int cnt = 0; // If current word appears in all the sentences for (int k = 0; k < ans.size(); k++) { if (ans[k].second == true) cnt++; } return cnt;} // Driver codeint main(){ vector<string> S; S.push_back("there is a cow"); S.push_back("cow is our mother"); S.push_back("cow gives us milk and milk is sweet"); S.push_back("there is a boy who loves cow"); cout << commonWords(S); return 0;}
// Java implementation of the approachimport java.util.HashMap; class GFG{ // Function to return the count of // common words in all the sentences static int commonWords(String[] s) { int m, i, j; // To store separate words String str; // It will be used to check if a word // is present in a particular string HashMap<String, Boolean> has = new HashMap<>(); // To store all the words of first string String[] ans1 = new String[100]; boolean[] ans2 = new boolean[100]; int track = 0; // m will store number of strings // in given vector m = s.length; i = 0; // Extract all words of first string // and store it in ans while (i < s[0].length()) { str = ""; while (i < s[0].length() && s[0].charAt(i) != ' ') { str += s[0].charAt(i); i++; } // Increase i to get at starting index // of the next word i++; // If str is not empty store it in map if (str.compareTo("") != 0) { ans1[track] = str; ans2[track] = true; track++; } } // Start from 2nd line check if any word of // the first string did not match with // some word in the current line for (j = 1; j < m; j++) { has.clear(); i = 0; while (i < s[j].length()) { str = ""; while (i < s[j].length() && s[j].charAt(i) != ' ') { str += s[j].charAt(i); i++; } i++; if (str.compareTo("") != 0) has.put(str, true); } // Check all words of this vector // if it is not present in current line // make it false for (int k = 0; k < track; k++) { // System.out.println(has.get(ans1[k])); if (ans2[k] != false && !has.containsKey(ans1[k])) ans2[k] = false; // This line is used to consider // only distinct words else if (ans2[k] != false && has.containsKey(ans1[k]) && has.get(ans1[k]) == true) has.put(ans1[k], false); } } // This function will print // the count of common words int cnt = 0; // If current word appears // in all the sentences for (int k = 0; k < track; k++) if (ans2[k] == true) cnt++; return cnt; } // Driver Code public static void main(String[] args) { String[] s = { "there is a cow", "cow is our mother", "cow gives us milk and milk is sweet", "there is a boy who loves cow" }; System.out.println(commonWords(s)); }} // This code is contributed by// sanjeev2552
# Python3 implementation of the approachfrom collections import defaultdict # Function to return the count of# common words in all the sentencesdef commonWords(S): # It will be used to check if a word # is present in a particular string has = defaultdict(lambda:False) # To store all the words of first string ans = [] # m will store number of strings # in given vector m = len(S) i = 0 # Extract all words of first string # and store it in ans while i < len(S[0]): string = "" while i < len(S[0]) and S[0][i] != ' ': string += S[0][i] i += 1 # Increase i to get at starting # index of the next word i += 1 # If str is not empty store it in map if string != "": ans.append([string, True]) # Start from 2nd line check if any word # of the first string did not match with # some word in the current line for j in range(1, m): has.clear() i = 0 while i < len(S[j]): string = "" while i < len(S[j]) and S[j][i] != ' ': string += S[j][i] i += 1 i += 1 if string != "": has[string] = True # Check all words of this vector # if it is not present in current # line make it false for k in range(0, len(ans)): if (ans[k][1] != False and has[ans[k][0]] == False): ans[k][1] = False # This line is used to consider # only distinct words elif (ans[k][1] != False and has[ans[k][0]] == True): has[ans[k][0]] = False # This function will print # the count of common words cnt = 0 # If current word appears in all # the sentences for k in range(0, len(ans)): if ans[k][1] == True: cnt += 1 return cnt # Driver codeif __name__ == "__main__": S = [] S.append("there is a cow") S.append("cow is our mother") S.append("cow gives us milk and milk is sweet") S.append("there is a boy who loves cow") print(commonWords(S)) # This code is contributed by Rituraj Jain
// C# implementation of the// above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count of// common words in all the sentencesstatic int commonWords(String[] s){ int m, i, j; // To store separate words String str; // It will be used to check // if a word is present in a // particular string Dictionary<String, Boolean> has = new Dictionary<String, Boolean>(); // To store all the words of // first string String[] ans1 = new String[100]; bool[] ans2 = new bool[100]; int track = 0; // m will store number of // strings in given vector m = s.Length; i = 0; // Extract all words of // first string and store // it in ans while (i < s[0].Length) { str = ""; while (i < s[0].Length && s[0][i] != ' ') { str += s[0][i]; i++; } // Increase i to get at // starting index of the // next word i++; // If str is not empty store // it in map if (str.CompareTo("") != 0) { ans1[track] = str; ans2[track] = true; track++; } } // Start from 2nd line check if // any word of the first string // did not match with some word // in the current line for (j = 1; j < m; j++) { has.Clear(); i = 0; while (i < s[j].Length) { str = ""; while (i < s[j].Length && s[j][i] != ' ') { str += s[j][i]; i++; } i++; if (str.CompareTo("") != 0) has[str] = true; } // Check all words of this // vector if it is not present // in current line make it false for (int k = 0; k < track; k++) { // Console.WriteLine(has[ans1[k])); if (ans2[k] != false && !has.ContainsKey(ans1[k])) ans2[k] = false; // This line is used to consider // only distinct words else if (ans2[k] != false && has.ContainsKey(ans1[k]) && has[ans1[k]] == true) has[ans1[k]] = false; } } // This function will print // the count of common words int cnt = 0; // If current word appears // in all the sentences for (int k = 0; k < track; k++) if (ans2[k] == true) cnt++; return cnt;} // Driver Codepublic static void Main(String[] args){ String[] s = {"there is a cow", "cow is our mother", "cow gives us milk" + "and milk is sweet", "there is a boy who" + "loves cow" }; Console.WriteLine(commonWords(s));}} // This code is contributed by Rajput-Ji
<script>// javascript implementation of the approach // Function to return the count of // common words in all the sentences function commonWords( s) { var m, i, j; // To store separate words var str; // It will be used to check if a word // is present in a particular string var has = new Map(); // To store all the words of first string var ans1 = []; var ans2 = []; var track = 0; // m will store number of strings // in given vector m = s.length; i = 0; // Extract all words of first string // and store it in ans while (i < s[0].length) { str = ""; while (i < s[0].length && s[0].charAt(i) != ' ') { str += s[0].charAt(i); i++; } // Increase i to get at starting index // of the next word i++; // If str is not empty store it in map if (str !== "") { ans1[track] = str; ans2[track] = true; track++; } } // Start from 2nd line check if any word of // the first string did not match with // some word in the current line for (j = 1; j < m; j++) { has.clear(); i = 0; while (i < s[j].length) { str = ""; while (i < s[j].length && s[j].charAt(i) != ' ') { str += s[j].charAt(i); i++; } i++; if (str !== "") has.set(str, true); } // Check all words of this vector // if it is not present in current line // make it false for (k = 0; k < track; k++) { // document.write(has.get(ans1[k])); if (ans2[k] != false && !has.has(ans1[k])) ans2[k] = false; // This line is used to consider // only distinct words else if (ans2[k] != false && has.has(ans1[k]) && has.get(ans1[k]) == true) has.set(ans1[k], false); } } // This function will print // the count of common words var cnt = 0; // If current word appears // in all the sentences for (k = 0; k < track; k++) if (ans2[k] == true) cnt++; return cnt; } // Driver Code var s = [ "there is a cow", "cow is our mother", "cow gives us milk and milk is sweet", "there is a boy who loves cow" ]; document.write(commonWords(s)); // This code is contributed by gauravrajput1</script>
2
rituraj_jain
sanjeev2552
Rajput-Ji
saurabh1990aror
GauravRajput1
cpp-unordered_map
Advanced Data Structure
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ordered Set and GNU C++ PBDS
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Suffix Array | Set 1 (Introduction)
Interval Tree
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
|
[
{
"code": null,
"e": 25731,
"s": 25703,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 25907,
"s": 25731,
"text": "Given n sentences. The task is to count the number of words that appear in all of these sentences. Note that every word consists of only lowercase English alphabets.Examples: "
},
{
"code": null,
"e": 26192,
"s": 25907,
"text": "Input: arr[] = { “there is a cow”, “cow is our mother”, “cow gives us milk and milk is sweet”, “there is a boy who loves cow”} Output: 2 Only the words “is” and “cow” appear in all of the sentences.Input: arr[] = { “abc aac abcd ccc”, “ac aa abc cca”, “abca aaac abcd ccc”} Output: 0 "
},
{
"code": null,
"e": 26662,
"s": 26192,
"text": "Naive Approach: The naive approach is to take every word of the first sentence and compare it with the rest of the lines if it is also present in all lines then increment the count.Efficient Approach: For all the words of the first sentence, we can check if it is also present in all the other sentences in constant time by using a map. Store all the words of the first sentence in a map and check how many of these stored words are present in all the other sentences. "
},
{
"code": null,
"e": 26666,
"s": 26662,
"text": "C++"
},
{
"code": null,
"e": 26671,
"s": 26666,
"text": "Java"
},
{
"code": null,
"e": 26679,
"s": 26671,
"text": "Python3"
},
{
"code": null,
"e": 26682,
"s": 26679,
"text": "C#"
},
{
"code": null,
"e": 26693,
"s": 26682,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of common words// in all the sentencesint commonWords(vector<string> S){ int m, n, i, j; // To store separate words string str; // It will be used to check if a word is present // in a particular string unordered_map<string, bool> has; // To store all the words of first string vector<pair<string, bool> > ans; pair<string, bool> tmp; // m will store number of strings in given vector m = S.size(); i = 0; // Extract all words of first string and store it in ans while (i < S[0].size()) { str = \"\"; while (i < S[0].size() && S[0][i] != ' ') { str += S[0][i]; i++; } // Increase i to get at starting index // of the next word i++; // If str is not empty store it in map if (str != \"\") { tmp = make_pair(str, true); ans.push_back(tmp); } } // Start from 2nd line check if any word of // the first string did not match with // some word in the current line for (j = 1; j < m; j++) { has.clear(); i = 0; while (i < S[j].size()) { str = \"\"; while (i < S[j].size() && S[j][i] != ' ') { str += S[j][i]; i++; } i++; if (str != \"\") { has[str] = true; } } // Check all words of this vector // if it is not present in current line // make it false for (int k = 0; k < ans.size(); k++) { if (ans[k].second != false && has[ans[k].first] == false) { ans[k].second = false; } // This line is used to consider only distinct words else if (ans[k].second != false && has[ans[k].first] == true) { has[ans[k].first] = false; } } } // This function will print // the count of common words int cnt = 0; // If current word appears in all the sentences for (int k = 0; k < ans.size(); k++) { if (ans[k].second == true) cnt++; } return cnt;} // Driver codeint main(){ vector<string> S; S.push_back(\"there is a cow\"); S.push_back(\"cow is our mother\"); S.push_back(\"cow gives us milk and milk is sweet\"); S.push_back(\"there is a boy who loves cow\"); cout << commonWords(S); return 0;}",
"e": 29204,
"s": 26693,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.HashMap; class GFG{ // Function to return the count of // common words in all the sentences static int commonWords(String[] s) { int m, i, j; // To store separate words String str; // It will be used to check if a word // is present in a particular string HashMap<String, Boolean> has = new HashMap<>(); // To store all the words of first string String[] ans1 = new String[100]; boolean[] ans2 = new boolean[100]; int track = 0; // m will store number of strings // in given vector m = s.length; i = 0; // Extract all words of first string // and store it in ans while (i < s[0].length()) { str = \"\"; while (i < s[0].length() && s[0].charAt(i) != ' ') { str += s[0].charAt(i); i++; } // Increase i to get at starting index // of the next word i++; // If str is not empty store it in map if (str.compareTo(\"\") != 0) { ans1[track] = str; ans2[track] = true; track++; } } // Start from 2nd line check if any word of // the first string did not match with // some word in the current line for (j = 1; j < m; j++) { has.clear(); i = 0; while (i < s[j].length()) { str = \"\"; while (i < s[j].length() && s[j].charAt(i) != ' ') { str += s[j].charAt(i); i++; } i++; if (str.compareTo(\"\") != 0) has.put(str, true); } // Check all words of this vector // if it is not present in current line // make it false for (int k = 0; k < track; k++) { // System.out.println(has.get(ans1[k])); if (ans2[k] != false && !has.containsKey(ans1[k])) ans2[k] = false; // This line is used to consider // only distinct words else if (ans2[k] != false && has.containsKey(ans1[k]) && has.get(ans1[k]) == true) has.put(ans1[k], false); } } // This function will print // the count of common words int cnt = 0; // If current word appears // in all the sentences for (int k = 0; k < track; k++) if (ans2[k] == true) cnt++; return cnt; } // Driver Code public static void main(String[] args) { String[] s = { \"there is a cow\", \"cow is our mother\", \"cow gives us milk and milk is sweet\", \"there is a boy who loves cow\" }; System.out.println(commonWords(s)); }} // This code is contributed by// sanjeev2552",
"e": 32374,
"s": 29204,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom collections import defaultdict # Function to return the count of# common words in all the sentencesdef commonWords(S): # It will be used to check if a word # is present in a particular string has = defaultdict(lambda:False) # To store all the words of first string ans = [] # m will store number of strings # in given vector m = len(S) i = 0 # Extract all words of first string # and store it in ans while i < len(S[0]): string = \"\" while i < len(S[0]) and S[0][i] != ' ': string += S[0][i] i += 1 # Increase i to get at starting # index of the next word i += 1 # If str is not empty store it in map if string != \"\": ans.append([string, True]) # Start from 2nd line check if any word # of the first string did not match with # some word in the current line for j in range(1, m): has.clear() i = 0 while i < len(S[j]): string = \"\" while i < len(S[j]) and S[j][i] != ' ': string += S[j][i] i += 1 i += 1 if string != \"\": has[string] = True # Check all words of this vector # if it is not present in current # line make it false for k in range(0, len(ans)): if (ans[k][1] != False and has[ans[k][0]] == False): ans[k][1] = False # This line is used to consider # only distinct words elif (ans[k][1] != False and has[ans[k][0]] == True): has[ans[k][0]] = False # This function will print # the count of common words cnt = 0 # If current word appears in all # the sentences for k in range(0, len(ans)): if ans[k][1] == True: cnt += 1 return cnt # Driver codeif __name__ == \"__main__\": S = [] S.append(\"there is a cow\") S.append(\"cow is our mother\") S.append(\"cow gives us milk and milk is sweet\") S.append(\"there is a boy who loves cow\") print(commonWords(S)) # This code is contributed by Rituraj Jain",
"e": 34599,
"s": 32374,
"text": null
},
{
"code": "// C# implementation of the// above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count of// common words in all the sentencesstatic int commonWords(String[] s){ int m, i, j; // To store separate words String str; // It will be used to check // if a word is present in a // particular string Dictionary<String, Boolean> has = new Dictionary<String, Boolean>(); // To store all the words of // first string String[] ans1 = new String[100]; bool[] ans2 = new bool[100]; int track = 0; // m will store number of // strings in given vector m = s.Length; i = 0; // Extract all words of // first string and store // it in ans while (i < s[0].Length) { str = \"\"; while (i < s[0].Length && s[0][i] != ' ') { str += s[0][i]; i++; } // Increase i to get at // starting index of the // next word i++; // If str is not empty store // it in map if (str.CompareTo(\"\") != 0) { ans1[track] = str; ans2[track] = true; track++; } } // Start from 2nd line check if // any word of the first string // did not match with some word // in the current line for (j = 1; j < m; j++) { has.Clear(); i = 0; while (i < s[j].Length) { str = \"\"; while (i < s[j].Length && s[j][i] != ' ') { str += s[j][i]; i++; } i++; if (str.CompareTo(\"\") != 0) has[str] = true; } // Check all words of this // vector if it is not present // in current line make it false for (int k = 0; k < track; k++) { // Console.WriteLine(has[ans1[k])); if (ans2[k] != false && !has.ContainsKey(ans1[k])) ans2[k] = false; // This line is used to consider // only distinct words else if (ans2[k] != false && has.ContainsKey(ans1[k]) && has[ans1[k]] == true) has[ans1[k]] = false; } } // This function will print // the count of common words int cnt = 0; // If current word appears // in all the sentences for (int k = 0; k < track; k++) if (ans2[k] == true) cnt++; return cnt;} // Driver Codepublic static void Main(String[] args){ String[] s = {\"there is a cow\", \"cow is our mother\", \"cow gives us milk\" + \"and milk is sweet\", \"there is a boy who\" + \"loves cow\" }; Console.WriteLine(commonWords(s));}} // This code is contributed by Rajput-Ji",
"e": 37162,
"s": 34599,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // Function to return the count of // common words in all the sentences function commonWords( s) { var m, i, j; // To store separate words var str; // It will be used to check if a word // is present in a particular string var has = new Map(); // To store all the words of first string var ans1 = []; var ans2 = []; var track = 0; // m will store number of strings // in given vector m = s.length; i = 0; // Extract all words of first string // and store it in ans while (i < s[0].length) { str = \"\"; while (i < s[0].length && s[0].charAt(i) != ' ') { str += s[0].charAt(i); i++; } // Increase i to get at starting index // of the next word i++; // If str is not empty store it in map if (str !== \"\") { ans1[track] = str; ans2[track] = true; track++; } } // Start from 2nd line check if any word of // the first string did not match with // some word in the current line for (j = 1; j < m; j++) { has.clear(); i = 0; while (i < s[j].length) { str = \"\"; while (i < s[j].length && s[j].charAt(i) != ' ') { str += s[j].charAt(i); i++; } i++; if (str !== \"\") has.set(str, true); } // Check all words of this vector // if it is not present in current line // make it false for (k = 0; k < track; k++) { // document.write(has.get(ans1[k])); if (ans2[k] != false && !has.has(ans1[k])) ans2[k] = false; // This line is used to consider // only distinct words else if (ans2[k] != false && has.has(ans1[k]) && has.get(ans1[k]) == true) has.set(ans1[k], false); } } // This function will print // the count of common words var cnt = 0; // If current word appears // in all the sentences for (k = 0; k < track; k++) if (ans2[k] == true) cnt++; return cnt; } // Driver Code var s = [ \"there is a cow\", \"cow is our mother\", \"cow gives us milk and milk is sweet\", \"there is a boy who loves cow\" ]; document.write(commonWords(s)); // This code is contributed by gauravrajput1</script>",
"e": 39899,
"s": 37162,
"text": null
},
{
"code": null,
"e": 39901,
"s": 39899,
"text": "2"
},
{
"code": null,
"e": 39916,
"s": 39903,
"text": "rituraj_jain"
},
{
"code": null,
"e": 39928,
"s": 39916,
"text": "sanjeev2552"
},
{
"code": null,
"e": 39938,
"s": 39928,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39954,
"s": 39938,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 39968,
"s": 39954,
"text": "GauravRajput1"
},
{
"code": null,
"e": 39986,
"s": 39968,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 40010,
"s": 39986,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 40015,
"s": 40010,
"text": "Hash"
},
{
"code": null,
"e": 40023,
"s": 40015,
"text": "Strings"
},
{
"code": null,
"e": 40028,
"s": 40023,
"text": "Hash"
},
{
"code": null,
"e": 40036,
"s": 40028,
"text": "Strings"
},
{
"code": null,
"e": 40134,
"s": 40036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40163,
"s": 40134,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 40205,
"s": 40163,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 40251,
"s": 40205,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 40287,
"s": 40251,
"text": "Suffix Array | Set 1 (Introduction)"
},
{
"code": null,
"e": 40301,
"s": 40287,
"text": "Interval Tree"
},
{
"code": null,
"e": 40386,
"s": 40301,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 40422,
"s": 40386,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 40449,
"s": 40422,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 40480,
"s": 40449,
"text": "Hashing | Set 1 (Introduction)"
}
] |
How to Build Android Applications with Gradle? - GeeksforGeeks
|
27 Sep, 2021
There are several contemporary build automation technologies available nowadays that may be utilized to create a quicker build when creating a project. Gradle is one of these modern-day automation technologies. Gradle is now used by Android to automate and control the build process while also defining flexible custom build settings. As a result, it is required to design or build an Android application utilizing such sophisticated build tools as Gradle.
So, in this article, we’ll learn how to use Gradle to boost our builds. In addition, we will study the fundamental syntax in the build.gradle file created by Android Studio. We will learn about gradlew tasks, build variations, and many other uses later in this blog.
Before we continue, let’s take a brief look at Gradle. Gradle, a sophisticated build toolkit, is used by Android Studio to automate and control the build process while allowing you to design flexible custom build settings. So, with Gradle, you can build, test, and deploy your application, and the files responsible for this sort of automation are the “Build.gradle” files. Gradle build scripts, for example, may do simple tasks such as copying pictures from one location/directory to another before the real build process begins. Gradle is required for Android projects in order to compile source code and resources.
When you create an Android Project in Android Studio, the build.gradle file is automatically produced, and when you hit the run button in Android Studio, the associated Gradle task is called, and the application is started or launched. When you run your source code in Android Studio, it will be transformed into DEX (Dalvik Executable) files. These DEX files contain the bytecode needed to execute the program on Android. APK Packager is used to bundle multiple DEX files with the application’s resources. The APK Packager then signs your APK using either the debug or release Keystore, and before creating your final APK, it optimizes your program to remove unnecessary code.
When you create a new project in Android Studio, it generates several files for you. Let us first define the scope and purpose of these files. A typical Android project’s project view is as follows:
The Gradle configuration file: The file settings.gradle may be found in the root directory. It is made up of all of the modules included in the app.The top-level build file is the build.gradle file, which is stored in the root directory. If you wish to use the same configuration for all modules in your project, declare them in this file.The module-level build file is as follows: The module-level build.gradle file, which can be found in each project/module/ directory, allows us to define build parameters for the module in which it is placed.Gradle configuration file: You may define parameters for the Gradle toolkit in the Gradle properties file.
The Gradle configuration file: The file settings.gradle may be found in the root directory. It is made up of all of the modules included in the app.
The top-level build file is the build.gradle file, which is stored in the root directory. If you wish to use the same configuration for all modules in your project, declare them in this file.
The module-level build file is as follows: The module-level build.gradle file, which can be found in each project/module/ directory, allows us to define build parameters for the module in which it is placed.
Gradle configuration file: You may define parameters for the Gradle toolkit in the Gradle properties file.
We have already covered the fundamentals of Gradle, and now we will look at some of the Gradle commands that may be used to conduct the build process without using Android Studio, i.e. via the command line. You can open gradle and then use the following commands which will help you.
1. Gradle Wrapper: Gradle is still in development, and a new version might arrive at any time. Gradle Wrapper is used to provide a seamless flow while running Gradle instructions. On Mac OS or Linux, the Gradle Wrapper is a shell script named gradlew, while on Windows, it is a batch file called gradlew.bat. So, if you run this script and the specified version of Gradle is not present, it will download the selected version of Gradle for you. If you use Android Studio to build an Android project, this Gradle Wrapper will be generated automatically. If you want to make your own Gradle Wrapper, then download Gradle from here and then execute the following command in your project directory:
$ gradle wrapper --gradle-version x.x
2. gradlew: The Gradle wrapper is gradlew. If you used Android Studio to build the Android project, navigate to the root directory of your project on the command line
This will provide a list of things you can perform using Gradle:
> Task :help
Welcome to Gradle 5.1.1.
To run a build, run gradlew <task> ...
To see a list of available tasks, run gradlew tasks
To see a list of command-line options, run gradlew --help
To see more detail about a task, run gradlew help --task <task>
For troubleshooting, visit https://help.gradle.org
3. gradlew responsibilities: This is used to display a list of available jobs. In the command line, type the following command:
> Task :tasks
-----------------------------------------------------------
Tasks runnable from root project
-----------------------------------------------------------
Android tasks
-------------
androidDependencies - Displays the Android dependencies of the project.
signingReport - Displays the signing info for the base and test modules
sourceSets - Prints out all the source sets defined in this project.
Build tasks
-----------
assemble - Assemble main outputs for all the variants.
assembleAndroidTest - Assembles all the Test applications.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
bundle - Assemble bundles for all the variants.
clean - Deletes the build directory.
cleanBuildCache - Deletes the build cache directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources
Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.
4. gradlew lint: The gradlew lint command is used to discover errors across the project, i.e. it will look for different errors, typos, and vulnerabilities. When you are at the root of your project, you can use all these commands
> Task :app:lint
Ran lint on variant debug: 30 issues found
Ran lint on variant release: 102 issues found
Wrote HTML report to file:
Wrote XML report to file:
5. gradlew build: To build your project, execute the following command in your root directory:
$ ./gradlew build
6. gradlew clean build: You may use this command to clear and obustificate your code the build will be rewritten from the ground up.
$ ./gradlew clean build
7. gradlew examination: Use the following command to perform the application test:
$ ./gradlew test
Gradle, in addition to being useful on command lines, has a plethora of other capabilities. Some of these are as follows:
Manage dependencies version: In a multi-module project, a number of dependencies are utilized, and the most common issue that emerges, as a result, is a conflict in the version of the dependencies, i.e. only if you have the dependency of the server then only they will run. The versions of these dependencies are tough to maintain, however, Gradle provides an ext block where we can declare our common property values and utilize them in dependencies.
apply plugin: 'com.android.application'
android {
defaultConfig{...}
buildTypes{...}
ProductFlavours{...}
}
ext {
supportLibraryVersion = '28.1.0'
}
dependencies {
// android supported libraries
implementation "com.android.support:appcompat-v7:$supportLibraryVersion"
implementation "com.android.support:design:$supportLibraryVersion"
implementation "com.android.support:cardview-v7:$supportLibraryVersion"
// google play service
implementation "com.google.android.gms:play-services:$playServiceVersion"
implementation "com.google.android.gms:play-services-fitness:$playServiceVersion"
// your other project files
}
By default, there are two types of builds in Android: debug and release. These building types are used to generate distinct application variants. We imply by “flavor” that the same program might have distinct features for various users. For example, the premium edition of the software should have different features than the free one. You may use the productFlavors closure in your app level build.gradle file to specify multiple flavors. As an example, consider the following:
productFlavors {
paid {
applicationId = "your app id goes here"
versionName = "1.1-paid"
}
free {
applicationId = "your app id"
versionName = "1.0-free"
}
}
As we’ve seen, the./gradlew tasks command may be used to retrieve a list of available tasks. However, we may also construct our own tasks. For example, we might write a task that instructs Gradle to generate an APK file with the build date in its name. To do so, add the following code to your module-level build.gradle file:
Java
task postTopic() { android.seeAllVariants.all { here -> here.outputs.all { output -> def gfg = new Date().format("dd-yyyy") def geeksforgeeks = here.name + "_" + date + ".apk" output.finalName = last } }}
We have one job here called postTopic(), and you are creating a new filename by appending the variable and the build date to it.
We learned how to utilize Gradle in our Android project in this article. We learned several Gradle commands. The whole set of commands is available on the Gradle website.
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
How to Get Current Location in Android?
Android Listview in Java with Example
Flexbox-Layout in Android
How to Save Data to the Firebase Realtime Database in Android?
Fragment Lifecycle in Android
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 26839,
"s": 26381,
"text": "There are several contemporary build automation technologies available nowadays that may be utilized to create a quicker build when creating a project. Gradle is one of these modern-day automation technologies. Gradle is now used by Android to automate and control the build process while also defining flexible custom build settings. As a result, it is required to design or build an Android application utilizing such sophisticated build tools as Gradle. "
},
{
"code": null,
"e": 27106,
"s": 26839,
"text": "So, in this article, we’ll learn how to use Gradle to boost our builds. In addition, we will study the fundamental syntax in the build.gradle file created by Android Studio. We will learn about gradlew tasks, build variations, and many other uses later in this blog."
},
{
"code": null,
"e": 27724,
"s": 27106,
"text": "Before we continue, let’s take a brief look at Gradle. Gradle, a sophisticated build toolkit, is used by Android Studio to automate and control the build process while allowing you to design flexible custom build settings. So, with Gradle, you can build, test, and deploy your application, and the files responsible for this sort of automation are the “Build.gradle” files. Gradle build scripts, for example, may do simple tasks such as copying pictures from one location/directory to another before the real build process begins. Gradle is required for Android projects in order to compile source code and resources."
},
{
"code": null,
"e": 28402,
"s": 27724,
"text": "When you create an Android Project in Android Studio, the build.gradle file is automatically produced, and when you hit the run button in Android Studio, the associated Gradle task is called, and the application is started or launched. When you run your source code in Android Studio, it will be transformed into DEX (Dalvik Executable) files. These DEX files contain the bytecode needed to execute the program on Android. APK Packager is used to bundle multiple DEX files with the application’s resources. The APK Packager then signs your APK using either the debug or release Keystore, and before creating your final APK, it optimizes your program to remove unnecessary code."
},
{
"code": null,
"e": 28601,
"s": 28402,
"text": "When you create a new project in Android Studio, it generates several files for you. Let us first define the scope and purpose of these files. A typical Android project’s project view is as follows:"
},
{
"code": null,
"e": 29254,
"s": 28601,
"text": "The Gradle configuration file: The file settings.gradle may be found in the root directory. It is made up of all of the modules included in the app.The top-level build file is the build.gradle file, which is stored in the root directory. If you wish to use the same configuration for all modules in your project, declare them in this file.The module-level build file is as follows: The module-level build.gradle file, which can be found in each project/module/ directory, allows us to define build parameters for the module in which it is placed.Gradle configuration file: You may define parameters for the Gradle toolkit in the Gradle properties file."
},
{
"code": null,
"e": 29403,
"s": 29254,
"text": "The Gradle configuration file: The file settings.gradle may be found in the root directory. It is made up of all of the modules included in the app."
},
{
"code": null,
"e": 29595,
"s": 29403,
"text": "The top-level build file is the build.gradle file, which is stored in the root directory. If you wish to use the same configuration for all modules in your project, declare them in this file."
},
{
"code": null,
"e": 29803,
"s": 29595,
"text": "The module-level build file is as follows: The module-level build.gradle file, which can be found in each project/module/ directory, allows us to define build parameters for the module in which it is placed."
},
{
"code": null,
"e": 29910,
"s": 29803,
"text": "Gradle configuration file: You may define parameters for the Gradle toolkit in the Gradle properties file."
},
{
"code": null,
"e": 30194,
"s": 29910,
"text": "We have already covered the fundamentals of Gradle, and now we will look at some of the Gradle commands that may be used to conduct the build process without using Android Studio, i.e. via the command line. You can open gradle and then use the following commands which will help you."
},
{
"code": null,
"e": 30889,
"s": 30194,
"text": "1. Gradle Wrapper: Gradle is still in development, and a new version might arrive at any time. Gradle Wrapper is used to provide a seamless flow while running Gradle instructions. On Mac OS or Linux, the Gradle Wrapper is a shell script named gradlew, while on Windows, it is a batch file called gradlew.bat. So, if you run this script and the specified version of Gradle is not present, it will download the selected version of Gradle for you. If you use Android Studio to build an Android project, this Gradle Wrapper will be generated automatically. If you want to make your own Gradle Wrapper, then download Gradle from here and then execute the following command in your project directory:"
},
{
"code": null,
"e": 30927,
"s": 30889,
"text": "$ gradle wrapper --gradle-version x.x"
},
{
"code": null,
"e": 31094,
"s": 30927,
"text": "2. gradlew: The Gradle wrapper is gradlew. If you used Android Studio to build the Android project, navigate to the root directory of your project on the command line"
},
{
"code": null,
"e": 31159,
"s": 31094,
"text": "This will provide a list of things you can perform using Gradle:"
},
{
"code": null,
"e": 31461,
"s": 31159,
"text": "> Task :help\nWelcome to Gradle 5.1.1.\nTo run a build, run gradlew <task> ...\nTo see a list of available tasks, run gradlew tasks\nTo see a list of command-line options, run gradlew --help\nTo see more detail about a task, run gradlew help --task <task>\nFor troubleshooting, visit https://help.gradle.org"
},
{
"code": null,
"e": 31589,
"s": 31461,
"text": "3. gradlew responsibilities: This is used to display a list of available jobs. In the command line, type the following command:"
},
{
"code": null,
"e": 32731,
"s": 31589,
"text": "> Task :tasks\n-----------------------------------------------------------\nTasks runnable from root project\n-----------------------------------------------------------\nAndroid tasks\n-------------\nandroidDependencies - Displays the Android dependencies of the project.\nsigningReport - Displays the signing info for the base and test modules\nsourceSets - Prints out all the source sets defined in this project.\n\nBuild tasks\n-----------\nassemble - Assemble main outputs for all the variants.\nassembleAndroidTest - Assembles all the Test applications.\nbuild - Assembles and tests this project.\nbuildDependents - Assembles and tests this project and all projects that depend on it.\nbuildNeeded - Assembles and tests this project and all projects it depends on.\nbundle - Assemble bundles for all the variants.\nclean - Deletes the build directory.\ncleanBuildCache - Deletes the build cache directory.\ncompileDebugAndroidTestSources\ncompileDebugSources\ncompileDebugUnitTestSources\ncompileReleaseSources\ncompileReleaseUnitTestSources\n\nBuild Setup tasks\n-----------------\ninit - Initializes a new Gradle build.\nwrapper - Generates Gradle wrapper files."
},
{
"code": null,
"e": 32961,
"s": 32731,
"text": "4. gradlew lint: The gradlew lint command is used to discover errors across the project, i.e. it will look for different errors, typos, and vulnerabilities. When you are at the root of your project, you can use all these commands"
},
{
"code": null,
"e": 33120,
"s": 32961,
"text": "> Task :app:lint\nRan lint on variant debug: 30 issues found\nRan lint on variant release: 102 issues found\nWrote HTML report to file:\nWrote XML report to file:"
},
{
"code": null,
"e": 33215,
"s": 33120,
"text": "5. gradlew build: To build your project, execute the following command in your root directory:"
},
{
"code": null,
"e": 33233,
"s": 33215,
"text": "$ ./gradlew build"
},
{
"code": null,
"e": 33366,
"s": 33233,
"text": "6. gradlew clean build: You may use this command to clear and obustificate your code the build will be rewritten from the ground up."
},
{
"code": null,
"e": 33391,
"s": 33366,
"text": "$ ./gradlew clean build "
},
{
"code": null,
"e": 33474,
"s": 33391,
"text": "7. gradlew examination: Use the following command to perform the application test:"
},
{
"code": null,
"e": 33491,
"s": 33474,
"text": "$ ./gradlew test"
},
{
"code": null,
"e": 33613,
"s": 33491,
"text": "Gradle, in addition to being useful on command lines, has a plethora of other capabilities. Some of these are as follows:"
},
{
"code": null,
"e": 34065,
"s": 33613,
"text": "Manage dependencies version: In a multi-module project, a number of dependencies are utilized, and the most common issue that emerges, as a result, is a conflict in the version of the dependencies, i.e. only if you have the dependency of the server then only they will run. The versions of these dependencies are tough to maintain, however, Gradle provides an ext block where we can declare our common property values and utilize them in dependencies."
},
{
"code": null,
"e": 34747,
"s": 34065,
"text": "apply plugin: 'com.android.application'\n \nandroid {\n defaultConfig{...}\n buildTypes{...}\n ProductFlavours{...}\n}\n\next {\n supportLibraryVersion = '28.1.0'\n\n}\n\ndependencies {\n // android supported libraries\n implementation \"com.android.support:appcompat-v7:$supportLibraryVersion\"\n implementation \"com.android.support:design:$supportLibraryVersion\"\n implementation \"com.android.support:cardview-v7:$supportLibraryVersion\"\n\n // google play service\n implementation \"com.google.android.gms:play-services:$playServiceVersion\"\n implementation \"com.google.android.gms:play-services-fitness:$playServiceVersion\"\n\n // your other project files\n }"
},
{
"code": null,
"e": 35226,
"s": 34747,
"text": "By default, there are two types of builds in Android: debug and release. These building types are used to generate distinct application variants. We imply by “flavor” that the same program might have distinct features for various users. For example, the premium edition of the software should have different features than the free one. You may use the productFlavors closure in your app level build.gradle file to specify multiple flavors. As an example, consider the following:"
},
{
"code": null,
"e": 35341,
"s": 35226,
"text": "productFlavors {\n paid {\n applicationId = \"your app id goes here\"\n versionName = \"1.1-paid\"\n }"
},
{
"code": null,
"e": 35427,
"s": 35341,
"text": "free {\n applicationId = \"your app id\"\n versionName = \"1.0-free\"\n }\n}"
},
{
"code": null,
"e": 35753,
"s": 35427,
"text": "As we’ve seen, the./gradlew tasks command may be used to retrieve a list of available tasks. However, we may also construct our own tasks. For example, we might write a task that instructs Gradle to generate an APK file with the build date in its name. To do so, add the following code to your module-level build.gradle file:"
},
{
"code": null,
"e": 35758,
"s": 35753,
"text": "Java"
},
{
"code": "task postTopic() { android.seeAllVariants.all { here -> here.outputs.all { output -> def gfg = new Date().format(\"dd-yyyy\") def geeksforgeeks = here.name + \"_\" + date + \".apk\" output.finalName = last } }}",
"e": 36016,
"s": 35758,
"text": null
},
{
"code": null,
"e": 36145,
"s": 36016,
"text": "We have one job here called postTopic(), and you are creating a new filename by appending the variable and the build date to it."
},
{
"code": null,
"e": 36316,
"s": 36145,
"text": "We learned how to utilize Gradle in our Android project in this article. We learned several Gradle commands. The whole set of commands is available on the Gradle website."
},
{
"code": null,
"e": 36323,
"s": 36316,
"text": "Picked"
},
{
"code": null,
"e": 36331,
"s": 36323,
"text": "Android"
},
{
"code": null,
"e": 36339,
"s": 36331,
"text": "Android"
},
{
"code": null,
"e": 36437,
"s": 36339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36475,
"s": 36437,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 36514,
"s": 36475,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36564,
"s": 36514,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 36606,
"s": 36564,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 36657,
"s": 36606,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 36697,
"s": 36657,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 36735,
"s": 36697,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 36761,
"s": 36735,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 36824,
"s": 36761,
"text": "How to Save Data to the Firebase Realtime Database in Android?"
}
] |
Tree Traversals - GeeksforGeeks
|
01 Jun, 2021
a
/ \
/ \
b c
/ \ / \
/ \ / \
d e f g
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 Replace Values in a List in Python?
How to Select Data Between Two Dates and Times in SQL Server?
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
How to Compare Two Columns in Pandas?
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 29121,
"s": 28855,
"text": " a\n / \\\n / \\\n b c\n / \\ / \\\n / \\ / \\\n d e f g"
},
{
"code": null,
"e": 29219,
"s": 29121,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29272,
"s": 29219,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29334,
"s": 29272,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29414,
"s": 29334,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 29455,
"s": 29414,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29535,
"s": 29455,
"text": "How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?"
},
{
"code": null,
"e": 29578,
"s": 29535,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29640,
"s": 29578,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 29676,
"s": 29640,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 29720,
"s": 29676,
"text": "How to Calculate Moving Averages in Python?"
}
] |
Minimum and Maximum number of pairs in m teams of n people - GeeksforGeeks
|
31 Mar, 2021
There are people which are to be grouped into exactly teams such that there is at least one person in each team. All members of a team are friends with each other. Find the minimum and maximum no. of pairs of friends that can be formed by grouping these people into exactly teams.Examples:
Input : 5 2 Output : 4 6 For maximum no. of pairs, 1st team contains only 1 member and 2nd team contains 4 people which are friends which each other, so no. of pairs in 1st team + no. of pairs in 2nd team = 0 + 6 = total pairs = 6 For minimum no. of pairs, 1st team contains 2 members and 2nd team contains 3 people which are friends which each other, so no. of pairs in 1st team + no. of pairs in 2nd team = 1 + 3 = total pairs = 4Input : 2 1 Output : 1 1
Explanation: First of all, we have to put 1 member in each team to satisfy the constraint. So we are left with people. 1. For maximum no. of pairs It can be seen that maximum no. pairs can result only by putting all of the remaining members of the same team. It can be explained as follows: Consider 2 teams one containing x people and other containing 1 person, now we have to add 1 more person to both the teams, adding him/her to the team of x people increases the no. of pairs by x while adding him to the other team only increases the no. of pairs by 1. Hence, for maximum no. of pairs, we have to put all the remaining people in the same team. Now the teams distribution for maximum no. of pairs would be something like this: Hence,
Ex: If a team consists of 3 persons, the 3rd person has 1 and 2 as friends, the 2nd person has 1 as a friend. Therefore, 2+1 = ((3-1)*(3))/2 friends2. For minimum no. of pairs Now from the same explanation, it can be seen that minimum no. of pairs are obtained when all the persons are distributed equally in the teams. Hence remaining n-m people should be distributed in m teams so that each team contains (n-m)/m more people. Now there are people still remaining which are to be filled 1 in each team (can be seen contrary to the above condition of maximum). Now the team distribution for minimum no. of pairs would be something like this: Each team has members and teams have one member extra. So total no. of pairs = Total no.s of pairs in m teams each of size + No. of pairs formed by adding 1 person in teams which have size
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find minimum and maximum no. of pairs#include <bits/stdc++.h>using namespace std; void MinimumMaximumPairs(int n, int m){ int max_pairs = ((n - m + 1) * (n - m)) / 2; int min_pairs = m * (((n - m) / m + 1) * ((n - m) / m)) / 2 + ceil((n - m) / double(m)) * ((n - m) % m); cout << "Minimum no. of pairs = " << min_pairs << "\n"; cout << "Maximum no. of pairs = " << max_pairs << "\n";} // Driver codeint main(){ int n = 5, m = 2; MinimumMaximumPairs(n, m); return 0;}
//Java program to find minimum// and maximum no. of pairs import java.io.*; class GFG { static void MinimumMaximumPairs(int n, int m){ int max_pairs = ((n - m + 1) * (n - m)) / 2; int min_pairs = m * (((n - m) / m + 1) * ((n - m) / m)) / 2 + (int)Math.ceil((double)((n - m) / (double)(m))) * ((n - m) % m); System.out.println("Minimum no. of pairs = " + min_pairs); System.out.println("Maximum no. of pairs = " + max_pairs);} // Driver code public static void main (String[] args) { int n = 5, m = 2; MinimumMaximumPairs(n, m);}}// This code is contributed by Sachin.
# Python3 program to find minimum# and maximum no. of pairs from math import ceil def MinimumMaximumPairs(n, m) : max_pairs = ((n - m + 1) * (n - m)) // 2; min_pairs = (m * (((n - m) // m + 1) * ((n - m) // m)) // 2 + ceil((n - m) / (m)) * ((n - m) % m)) print("Minimum no. of pairs = ", min_pairs) print("Maximum no. of pairs = " , max_pairs) # Driver codeif __name__ == "__main__" : n ,m= 5, 2 MinimumMaximumPairs(n, m) # This code is contributed by Ryuga
// C# program to find minimum// and maximum no. of pairsusing System;class GFG{static void MinimumMaximumPairs(int n, int m){ int max_pairs = ((n - m + 1) * (n - m)) / 2; int min_pairs = m * (((n - m) / m + 1) * ((n - m) / m)) / 2 + (int)Math.Ceiling((double)((n - m) / (double)(m))) * ((n - m) % m); Console.WriteLine("Minimum no. of pairs = " + min_pairs); Console.WriteLine("Maximum no. of pairs = " + max_pairs);} // Driver codepublic static void Main(){ int n = 5, m = 2; MinimumMaximumPairs(n, m);}} // This code is contributed by Akanksha Rai
<?php// PHP program to find minimum// and maximum no. of pairsfunction MinimumMaximumPairs($n, $m){ $max_pairs = (($n - $m + 1) * ($n - $m)) / 2; $min_pairs = $m * (int)((((int)($n - $m) / $m + 1) * ((int)($n - $m) / $m)) / 2) + (int)ceil(($n - $m) / $m) * (($n - $m) % $m); echo("Minimum no. of pairs = " . "$min_pairs" . "\n"); echo("Maximum no. of pairs = " . "$max_pairs");} // Driver code$n = 5; $m = 2;MinimumMaximumPairs($n, $m); // This code is contributed// by Mukul Singh?>
<script>// javascript program to find minimum// and maximum no. of pairs function MinimumMaximumPairs(n, m) { var max_pairs = parseInt(((n - m + 1) * (n - m)) / 2); var min_pairs = m * parseInt((((n - m) / m + 1) * ((n - m) / m)) / 2) + parseInt( Math.ceil(((n - m) / (m)))) * ((n - m) % m); document.write("Minimum no. of pairs = " + min_pairs+"<br/>"); document.write("Maximum no. of pairs = " + max_pairs); } // Driver code var n = 5, m = 2; MinimumMaximumPairs(n, m); // This code is contributed by gauravrajput1</script>
Output
Minimum no. of pairs = 4
Maximum no. of pairs = 6
Time Complexity:
sirjan13
ankthon
Code_Mech
Akanksha_Rai
Sach_Code
GauravRajput1
Combinatorial
Mathematical
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Combinational Sum
Count ways to reach the nth stair using step 1, 2 or 3
Print all possible strings of length k that can be formed from a set of n characters
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Coin Change | DP-7
Merge two sorted arrays
|
[
{
"code": null,
"e": 26673,
"s": 26645,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 26965,
"s": 26673,
"text": "There are people which are to be grouped into exactly teams such that there is at least one person in each team. All members of a team are friends with each other. Find the minimum and maximum no. of pairs of friends that can be formed by grouping these people into exactly teams.Examples: "
},
{
"code": null,
"e": 27422,
"s": 26965,
"text": "Input : 5 2 Output : 4 6 For maximum no. of pairs, 1st team contains only 1 member and 2nd team contains 4 people which are friends which each other, so no. of pairs in 1st team + no. of pairs in 2nd team = 0 + 6 = total pairs = 6 For minimum no. of pairs, 1st team contains 2 members and 2nd team contains 3 people which are friends which each other, so no. of pairs in 1st team + no. of pairs in 2nd team = 1 + 3 = total pairs = 4Input : 2 1 Output : 1 1"
},
{
"code": null,
"e": 28164,
"s": 27424,
"text": "Explanation: First of all, we have to put 1 member in each team to satisfy the constraint. So we are left with people. 1. For maximum no. of pairs It can be seen that maximum no. pairs can result only by putting all of the remaining members of the same team. It can be explained as follows: Consider 2 teams one containing x people and other containing 1 person, now we have to add 1 more person to both the teams, adding him/her to the team of x people increases the no. of pairs by x while adding him to the other team only increases the no. of pairs by 1. Hence, for maximum no. of pairs, we have to put all the remaining people in the same team. Now the teams distribution for maximum no. of pairs would be something like this: Hence, "
},
{
"code": null,
"e": 29001,
"s": 28169,
"text": "Ex: If a team consists of 3 persons, the 3rd person has 1 and 2 as friends, the 2nd person has 1 as a friend. Therefore, 2+1 = ((3-1)*(3))/2 friends2. For minimum no. of pairs Now from the same explanation, it can be seen that minimum no. of pairs are obtained when all the persons are distributed equally in the teams. Hence remaining n-m people should be distributed in m teams so that each team contains (n-m)/m more people. Now there are people still remaining which are to be filled 1 in each team (can be seen contrary to the above condition of maximum). Now the team distribution for minimum no. of pairs would be something like this: Each team has members and teams have one member extra. So total no. of pairs = Total no.s of pairs in m teams each of size + No. of pairs formed by adding 1 person in teams which have size "
},
{
"code": null,
"e": 29012,
"s": 29008,
"text": "C++"
},
{
"code": null,
"e": 29017,
"s": 29012,
"text": "Java"
},
{
"code": null,
"e": 29025,
"s": 29017,
"text": "Python3"
},
{
"code": null,
"e": 29028,
"s": 29025,
"text": "C#"
},
{
"code": null,
"e": 29032,
"s": 29028,
"text": "PHP"
},
{
"code": null,
"e": 29043,
"s": 29032,
"text": "Javascript"
},
{
"code": "// CPP program to find minimum and maximum no. of pairs#include <bits/stdc++.h>using namespace std; void MinimumMaximumPairs(int n, int m){ int max_pairs = ((n - m + 1) * (n - m)) / 2; int min_pairs = m * (((n - m) / m + 1) * ((n - m) / m)) / 2 + ceil((n - m) / double(m)) * ((n - m) % m); cout << \"Minimum no. of pairs = \" << min_pairs << \"\\n\"; cout << \"Maximum no. of pairs = \" << max_pairs << \"\\n\";} // Driver codeint main(){ int n = 5, m = 2; MinimumMaximumPairs(n, m); return 0;}",
"e": 29570,
"s": 29043,
"text": null
},
{
"code": "//Java program to find minimum// and maximum no. of pairs import java.io.*; class GFG { static void MinimumMaximumPairs(int n, int m){ int max_pairs = ((n - m + 1) * (n - m)) / 2; int min_pairs = m * (((n - m) / m + 1) * ((n - m) / m)) / 2 + (int)Math.ceil((double)((n - m) / (double)(m))) * ((n - m) % m); System.out.println(\"Minimum no. of pairs = \" + min_pairs); System.out.println(\"Maximum no. of pairs = \" + max_pairs);} // Driver code public static void main (String[] args) { int n = 5, m = 2; MinimumMaximumPairs(n, m);}}// This code is contributed by Sachin.",
"e": 30236,
"s": 29570,
"text": null
},
{
"code": "# Python3 program to find minimum# and maximum no. of pairs from math import ceil def MinimumMaximumPairs(n, m) : max_pairs = ((n - m + 1) * (n - m)) // 2; min_pairs = (m * (((n - m) // m + 1) * ((n - m) // m)) // 2 + ceil((n - m) / (m)) * ((n - m) % m)) print(\"Minimum no. of pairs = \", min_pairs) print(\"Maximum no. of pairs = \" , max_pairs) # Driver codeif __name__ == \"__main__\" : n ,m= 5, 2 MinimumMaximumPairs(n, m) # This code is contributed by Ryuga",
"e": 30775,
"s": 30236,
"text": null
},
{
"code": "// C# program to find minimum// and maximum no. of pairsusing System;class GFG{static void MinimumMaximumPairs(int n, int m){ int max_pairs = ((n - m + 1) * (n - m)) / 2; int min_pairs = m * (((n - m) / m + 1) * ((n - m) / m)) / 2 + (int)Math.Ceiling((double)((n - m) / (double)(m))) * ((n - m) % m); Console.WriteLine(\"Minimum no. of pairs = \" + min_pairs); Console.WriteLine(\"Maximum no. of pairs = \" + max_pairs);} // Driver codepublic static void Main(){ int n = 5, m = 2; MinimumMaximumPairs(n, m);}} // This code is contributed by Akanksha Rai",
"e": 31411,
"s": 30775,
"text": null
},
{
"code": "<?php// PHP program to find minimum// and maximum no. of pairsfunction MinimumMaximumPairs($n, $m){ $max_pairs = (($n - $m + 1) * ($n - $m)) / 2; $min_pairs = $m * (int)((((int)($n - $m) / $m + 1) * ((int)($n - $m) / $m)) / 2) + (int)ceil(($n - $m) / $m) * (($n - $m) % $m); echo(\"Minimum no. of pairs = \" . \"$min_pairs\" . \"\\n\"); echo(\"Maximum no. of pairs = \" . \"$max_pairs\");} // Driver code$n = 5; $m = 2;MinimumMaximumPairs($n, $m); // This code is contributed// by Mukul Singh?>",
"e": 32023,
"s": 31411,
"text": null
},
{
"code": "<script>// javascript program to find minimum// and maximum no. of pairs function MinimumMaximumPairs(n, m) { var max_pairs = parseInt(((n - m + 1) * (n - m)) / 2); var min_pairs = m * parseInt((((n - m) / m + 1) * ((n - m) / m)) / 2) + parseInt( Math.ceil(((n - m) / (m)))) * ((n - m) % m); document.write(\"Minimum no. of pairs = \" + min_pairs+\"<br/>\"); document.write(\"Maximum no. of pairs = \" + max_pairs); } // Driver code var n = 5, m = 2; MinimumMaximumPairs(n, m); // This code is contributed by gauravrajput1</script>",
"e": 32616,
"s": 32023,
"text": null
},
{
"code": null,
"e": 32625,
"s": 32616,
"text": "Output "
},
{
"code": null,
"e": 32677,
"s": 32625,
"text": "Minimum no. of pairs = 4\nMaximum no. of pairs = 6"
},
{
"code": null,
"e": 32696,
"s": 32677,
"text": "Time Complexity: "
},
{
"code": null,
"e": 32705,
"s": 32696,
"text": "sirjan13"
},
{
"code": null,
"e": 32713,
"s": 32705,
"text": "ankthon"
},
{
"code": null,
"e": 32723,
"s": 32713,
"text": "Code_Mech"
},
{
"code": null,
"e": 32736,
"s": 32723,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32746,
"s": 32736,
"text": "Sach_Code"
},
{
"code": null,
"e": 32760,
"s": 32746,
"text": "GauravRajput1"
},
{
"code": null,
"e": 32774,
"s": 32760,
"text": "Combinatorial"
},
{
"code": null,
"e": 32787,
"s": 32774,
"text": "Mathematical"
},
{
"code": null,
"e": 32800,
"s": 32787,
"text": "Mathematical"
},
{
"code": null,
"e": 32814,
"s": 32800,
"text": "Combinatorial"
},
{
"code": null,
"e": 32912,
"s": 32814,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32930,
"s": 32912,
"text": "Combinational Sum"
},
{
"code": null,
"e": 32985,
"s": 32930,
"text": "Count ways to reach the nth stair using step 1, 2 or 3"
},
{
"code": null,
"e": 33070,
"s": 32985,
"text": "Print all possible strings of length k that can be formed from a set of n characters"
},
{
"code": null,
"e": 33107,
"s": 33070,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 33164,
"s": 33107,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 33194,
"s": 33164,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33237,
"s": 33194,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 33252,
"s": 33237,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33271,
"s": 33252,
"text": "Coin Change | DP-7"
}
] |
java.rmi.Naming Class in Java - GeeksforGeeks
|
25 Aug, 2021
Java.rmi.Naming class contains a method to bind, unbind or rebind names with a remote object present at the remote registry. This class is also used to get the reference of the object present at remote registries or the list of name associated with this registry.
Syntax: Class declaration
public final class Naming extends Object
Let us do discuss some major methods of this class which are as follows:
The most commonly used methods are described below as follows:
bind()list()lookup()rebind()unbind()
bind()
list()
lookup()
rebind()
unbind()
Method 1: bind()
Syntax:
static void bind(String name, remote object)
// Bind this name with this remote object
Parameters: Name of the remote registry
Exceptions:
AlreadyBoundException occurs when the name was already boundedMalformedURLException occurs when the format of the name is not an URLRemoteException occurs when the contact to remote registry failsAccessException occurs when access to this operation is not permitted
AlreadyBoundException occurs when the name was already bounded
MalformedURLException occurs when the format of the name is not an URL
RemoteException occurs when the contact to remote registry fails
AccessException occurs when access to this operation is not permitted
Method 2: list() Used to get the list of the names associated with the registry
Syntax:
static string[] list(String name)
Parameters: The name of the remote registry
Return Type: An array of name bounded with this registry
Exceptions:
MalformedURLException occurs when the format of the name is not an URLRemoteException occurs when hen the contact to remote registry fails
MalformedURLException occurs when the format of the name is not an URL
RemoteException occurs when hen the contact to remote registry fails
Method 3: lookup() looks for the reference of the remote object to which this name is associated
Syntax:
static remote lookup(String name)
Parameters: The name of the remote registry
Return Type: The reference for a remote object
Exceptions:
NotBoundException occurs when the name does not bound with the current operationRemoteException occurs when the contact to remote registry failsAccessException occurs when access to this operation is not permittedMalformedURLException occurs when the format of the name is not an URL
NotBoundException occurs when the name does not bound with the current operation
RemoteException occurs when the contact to remote registry fails
AccessException occurs when access to this operation is not permitted
MalformedURLException occurs when the format of the name is not an URL
Method 4: rebind() method rebinds this name with the associated remote object
Syntax:
static void rebind(String name, remote object)
Parameters: It takes two parameters namely name and object.
The name of the remote registry
The remote object to associate with the name
Exceptions:
MalformedURLException occurs when the format of the name is not an URLRemoteException occurs when the contact to remote registry failsAccessException occurs when access to this operation is not permitted
MalformedURLException occurs when the format of the name is not an URL
RemoteException occurs when the contact to remote registry fails
AccessException occurs when access to this operation is not permitted
Method 5: unbind() unbinds this name with the associated remote object
Syntax:
static void unbind(String name)
Parameters: The name of the remote registry
Exceptions:
NotBoundException occurs when the name does not bound with the current operationMalformedURLException occurs when the format of the name is not an URLRemoteException occurs when the contact to remote registry failsAccessException occurs when access to this operation is not permitted
NotBoundException occurs when the name does not bound with the current operation
MalformedURLException occurs when the format of the name is not an URL
RemoteException occurs when the contact to remote registry fails
AccessException occurs when access to this operation is not permitted
Example 1:
Java
// Java Program to create a registry// Server's Side // Importing java.rmi package to enable object of one JVM// to invoke methods on object in another JVMimport java.rmi.*;import java.rmi.AlreadyBoundException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.Remote;import java.rmi.RemoteException;import java.rmi.registry.LocateRegistry;import java.rmi.registry.Registry;import java.rmi.server.*; // Interface// creating remote interfaceinterface demo extends Remote { public String msg(String msg) throws RemoteException;} // Class 1// Helper Classclass demoRemote extends UnicastRemoteObject implements demo { demoRemote() throws RemoteException { super(); } // @Override public String msg(String msg) throws RemoteException { // Display message only System.out.println("GeeksForGeeks"); return null; }} // Class 2// Main classpublic class GFG_Server { // Main driver method public static void main(String args[]) throws RemoteException, NotBoundException, AlreadyBoundException { // Try block to check for exceptions try { // Creating a new registry by creating // an object of Registry class Registry registry = LocateRegistry.createRegistry(3000); demo obj = new demoRemote(); // binding obj to remote registry Naming.bind("rmi://localhost:3000" + "/geeksforgeeks", (Remote)obj); // Display message when program // is executed succussfully System.out.println( "registry created successfully"); } // Catch block to handle the exceptions catch (Exception e) { // Getting the name of the exception using // the toString() method over exception object System.err.println(e.toString()); } }}
Output:
registry created successfully
Implementation: Java program to look for the object(Clients’ side)
Example 2:
Java
// Java Program to look for the object// Client Side // Importing java.rmi package to enable object of one JVM// to invoke methods on object in another JVMimport java.rmi.*; // Main classpublic class GFG_Client { // Main driver method public static void main(String args[]) { // try block to check for exceptions try { // Looking for object in remote registry demo client = (demo)Naming.lookup( "rmi://localhost:3000/obj"); // Print and display the client message System.out.println(client.msg()); } // Catch block to handle the exception catch (Exception e) { } }}
Output:
GeeksForGeeks
anikakapoor
Java-Packages
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Different ways of Reading a text file in Java
Internal Working of HashMap in Java
Introduction to Java
Comparator Interface in Java with Examples
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 25489,
"s": 25225,
"text": "Java.rmi.Naming class contains a method to bind, unbind or rebind names with a remote object present at the remote registry. This class is also used to get the reference of the object present at remote registries or the list of name associated with this registry."
},
{
"code": null,
"e": 25515,
"s": 25489,
"text": "Syntax: Class declaration"
},
{
"code": null,
"e": 25556,
"s": 25515,
"text": "public final class Naming extends Object"
},
{
"code": null,
"e": 25629,
"s": 25556,
"text": "Let us do discuss some major methods of this class which are as follows:"
},
{
"code": null,
"e": 25692,
"s": 25629,
"text": "The most commonly used methods are described below as follows:"
},
{
"code": null,
"e": 25729,
"s": 25692,
"text": "bind()list()lookup()rebind()unbind()"
},
{
"code": null,
"e": 25736,
"s": 25729,
"text": "bind()"
},
{
"code": null,
"e": 25743,
"s": 25736,
"text": "list()"
},
{
"code": null,
"e": 25752,
"s": 25743,
"text": "lookup()"
},
{
"code": null,
"e": 25761,
"s": 25752,
"text": "rebind()"
},
{
"code": null,
"e": 25770,
"s": 25761,
"text": "unbind()"
},
{
"code": null,
"e": 25788,
"s": 25770,
"text": "Method 1: bind() "
},
{
"code": null,
"e": 25796,
"s": 25788,
"text": "Syntax:"
},
{
"code": null,
"e": 25884,
"s": 25796,
"text": "static void bind(String name, remote object) \n// Bind this name with this remote object"
},
{
"code": null,
"e": 25924,
"s": 25884,
"text": "Parameters: Name of the remote registry"
},
{
"code": null,
"e": 25936,
"s": 25924,
"text": "Exceptions:"
},
{
"code": null,
"e": 26202,
"s": 25936,
"text": "AlreadyBoundException occurs when the name was already boundedMalformedURLException occurs when the format of the name is not an URLRemoteException occurs when the contact to remote registry failsAccessException occurs when access to this operation is not permitted"
},
{
"code": null,
"e": 26265,
"s": 26202,
"text": "AlreadyBoundException occurs when the name was already bounded"
},
{
"code": null,
"e": 26336,
"s": 26265,
"text": "MalformedURLException occurs when the format of the name is not an URL"
},
{
"code": null,
"e": 26401,
"s": 26336,
"text": "RemoteException occurs when the contact to remote registry fails"
},
{
"code": null,
"e": 26471,
"s": 26401,
"text": "AccessException occurs when access to this operation is not permitted"
},
{
"code": null,
"e": 26551,
"s": 26471,
"text": "Method 2: list() Used to get the list of the names associated with the registry"
},
{
"code": null,
"e": 26559,
"s": 26551,
"text": "Syntax:"
},
{
"code": null,
"e": 26593,
"s": 26559,
"text": "static string[] list(String name)"
},
{
"code": null,
"e": 26637,
"s": 26593,
"text": "Parameters: The name of the remote registry"
},
{
"code": null,
"e": 26694,
"s": 26637,
"text": "Return Type: An array of name bounded with this registry"
},
{
"code": null,
"e": 26706,
"s": 26694,
"text": "Exceptions:"
},
{
"code": null,
"e": 26845,
"s": 26706,
"text": "MalformedURLException occurs when the format of the name is not an URLRemoteException occurs when hen the contact to remote registry fails"
},
{
"code": null,
"e": 26916,
"s": 26845,
"text": "MalformedURLException occurs when the format of the name is not an URL"
},
{
"code": null,
"e": 26985,
"s": 26916,
"text": "RemoteException occurs when hen the contact to remote registry fails"
},
{
"code": null,
"e": 27082,
"s": 26985,
"text": "Method 3: lookup() looks for the reference of the remote object to which this name is associated"
},
{
"code": null,
"e": 27090,
"s": 27082,
"text": "Syntax:"
},
{
"code": null,
"e": 27124,
"s": 27090,
"text": "static remote lookup(String name)"
},
{
"code": null,
"e": 27168,
"s": 27124,
"text": "Parameters: The name of the remote registry"
},
{
"code": null,
"e": 27215,
"s": 27168,
"text": "Return Type: The reference for a remote object"
},
{
"code": null,
"e": 27227,
"s": 27215,
"text": "Exceptions:"
},
{
"code": null,
"e": 27511,
"s": 27227,
"text": "NotBoundException occurs when the name does not bound with the current operationRemoteException occurs when the contact to remote registry failsAccessException occurs when access to this operation is not permittedMalformedURLException occurs when the format of the name is not an URL"
},
{
"code": null,
"e": 27592,
"s": 27511,
"text": "NotBoundException occurs when the name does not bound with the current operation"
},
{
"code": null,
"e": 27657,
"s": 27592,
"text": "RemoteException occurs when the contact to remote registry fails"
},
{
"code": null,
"e": 27727,
"s": 27657,
"text": "AccessException occurs when access to this operation is not permitted"
},
{
"code": null,
"e": 27798,
"s": 27727,
"text": "MalformedURLException occurs when the format of the name is not an URL"
},
{
"code": null,
"e": 27876,
"s": 27798,
"text": "Method 4: rebind() method rebinds this name with the associated remote object"
},
{
"code": null,
"e": 27884,
"s": 27876,
"text": "Syntax:"
},
{
"code": null,
"e": 27931,
"s": 27884,
"text": "static void rebind(String name, remote object)"
},
{
"code": null,
"e": 27991,
"s": 27931,
"text": "Parameters: It takes two parameters namely name and object."
},
{
"code": null,
"e": 28023,
"s": 27991,
"text": "The name of the remote registry"
},
{
"code": null,
"e": 28068,
"s": 28023,
"text": "The remote object to associate with the name"
},
{
"code": null,
"e": 28080,
"s": 28068,
"text": "Exceptions:"
},
{
"code": null,
"e": 28284,
"s": 28080,
"text": "MalformedURLException occurs when the format of the name is not an URLRemoteException occurs when the contact to remote registry failsAccessException occurs when access to this operation is not permitted"
},
{
"code": null,
"e": 28355,
"s": 28284,
"text": "MalformedURLException occurs when the format of the name is not an URL"
},
{
"code": null,
"e": 28420,
"s": 28355,
"text": "RemoteException occurs when the contact to remote registry fails"
},
{
"code": null,
"e": 28490,
"s": 28420,
"text": "AccessException occurs when access to this operation is not permitted"
},
{
"code": null,
"e": 28561,
"s": 28490,
"text": "Method 5: unbind() unbinds this name with the associated remote object"
},
{
"code": null,
"e": 28569,
"s": 28561,
"text": "Syntax:"
},
{
"code": null,
"e": 28602,
"s": 28569,
"text": "static void unbind(String name) "
},
{
"code": null,
"e": 28646,
"s": 28602,
"text": "Parameters: The name of the remote registry"
},
{
"code": null,
"e": 28658,
"s": 28646,
"text": "Exceptions:"
},
{
"code": null,
"e": 28942,
"s": 28658,
"text": "NotBoundException occurs when the name does not bound with the current operationMalformedURLException occurs when the format of the name is not an URLRemoteException occurs when the contact to remote registry failsAccessException occurs when access to this operation is not permitted"
},
{
"code": null,
"e": 29023,
"s": 28942,
"text": "NotBoundException occurs when the name does not bound with the current operation"
},
{
"code": null,
"e": 29094,
"s": 29023,
"text": "MalformedURLException occurs when the format of the name is not an URL"
},
{
"code": null,
"e": 29159,
"s": 29094,
"text": "RemoteException occurs when the contact to remote registry fails"
},
{
"code": null,
"e": 29229,
"s": 29159,
"text": "AccessException occurs when access to this operation is not permitted"
},
{
"code": null,
"e": 29240,
"s": 29229,
"text": "Example 1:"
},
{
"code": null,
"e": 29245,
"s": 29240,
"text": "Java"
},
{
"code": "// Java Program to create a registry// Server's Side // Importing java.rmi package to enable object of one JVM// to invoke methods on object in another JVMimport java.rmi.*;import java.rmi.AlreadyBoundException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.Remote;import java.rmi.RemoteException;import java.rmi.registry.LocateRegistry;import java.rmi.registry.Registry;import java.rmi.server.*; // Interface// creating remote interfaceinterface demo extends Remote { public String msg(String msg) throws RemoteException;} // Class 1// Helper Classclass demoRemote extends UnicastRemoteObject implements demo { demoRemote() throws RemoteException { super(); } // @Override public String msg(String msg) throws RemoteException { // Display message only System.out.println(\"GeeksForGeeks\"); return null; }} // Class 2// Main classpublic class GFG_Server { // Main driver method public static void main(String args[]) throws RemoteException, NotBoundException, AlreadyBoundException { // Try block to check for exceptions try { // Creating a new registry by creating // an object of Registry class Registry registry = LocateRegistry.createRegistry(3000); demo obj = new demoRemote(); // binding obj to remote registry Naming.bind(\"rmi://localhost:3000\" + \"/geeksforgeeks\", (Remote)obj); // Display message when program // is executed succussfully System.out.println( \"registry created successfully\"); } // Catch block to handle the exceptions catch (Exception e) { // Getting the name of the exception using // the toString() method over exception object System.err.println(e.toString()); } }}",
"e": 31201,
"s": 29245,
"text": null
},
{
"code": null,
"e": 31210,
"s": 31201,
"text": "Output: "
},
{
"code": null,
"e": 31240,
"s": 31210,
"text": "registry created successfully"
},
{
"code": null,
"e": 31307,
"s": 31240,
"text": "Implementation: Java program to look for the object(Clients’ side)"
},
{
"code": null,
"e": 31319,
"s": 31307,
"text": "Example 2: "
},
{
"code": null,
"e": 31324,
"s": 31319,
"text": "Java"
},
{
"code": "// Java Program to look for the object// Client Side // Importing java.rmi package to enable object of one JVM// to invoke methods on object in another JVMimport java.rmi.*; // Main classpublic class GFG_Client { // Main driver method public static void main(String args[]) { // try block to check for exceptions try { // Looking for object in remote registry demo client = (demo)Naming.lookup( \"rmi://localhost:3000/obj\"); // Print and display the client message System.out.println(client.msg()); } // Catch block to handle the exception catch (Exception e) { } }}",
"e": 32007,
"s": 31324,
"text": null
},
{
"code": null,
"e": 32016,
"s": 32007,
"text": "Output: "
},
{
"code": null,
"e": 32030,
"s": 32016,
"text": "GeeksForGeeks"
},
{
"code": null,
"e": 32044,
"s": 32032,
"text": "anikakapoor"
},
{
"code": null,
"e": 32058,
"s": 32044,
"text": "Java-Packages"
},
{
"code": null,
"e": 32065,
"s": 32058,
"text": "Picked"
},
{
"code": null,
"e": 32070,
"s": 32065,
"text": "Java"
},
{
"code": null,
"e": 32075,
"s": 32070,
"text": "Java"
},
{
"code": null,
"e": 32173,
"s": 32075,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32188,
"s": 32173,
"text": "Stream In Java"
},
{
"code": null,
"e": 32209,
"s": 32188,
"text": "Constructors in Java"
},
{
"code": null,
"e": 32228,
"s": 32209,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 32258,
"s": 32228,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 32275,
"s": 32258,
"text": "Generics in Java"
},
{
"code": null,
"e": 32321,
"s": 32275,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 32357,
"s": 32321,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 32378,
"s": 32357,
"text": "Introduction to Java"
},
{
"code": null,
"e": 32421,
"s": 32378,
"text": "Comparator Interface in Java with Examples"
}
] |
Perfect Square String - GeeksforGeeks
|
25 Mar, 2021
Given a String str and the task is to check sum of ASCII value of all characters is a perfect square or not.
Examples :
Input : ddddddddddddddddddddddddd
Output : Yes
Input : GeeksForGeeks
Output : No
Algorithm
Calculate the string length
Calculate sum of ASCII value of all characters
Take the square root of the number sum and store it into variable squareRoot
Take floor value of the squareRoot and subtract from squareRoot
If the difference of floor value of squareRoot and squareRoot is 0 then print “Yes” otherwise “No”
Below is the implementation of the above approach :
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find if string is a// perfect square or not.#include <bits/stdc++.h>using namespace std; bool isPerfectSquareString(string str){ int sum = 0; // calculating the length of // the string int len = str.length(); // calculating the ASCII value // of the string for (int i = 0; i < len; i++) sum += (int)str[i]; // Find floating point value of // square root of x. long double squareRoot = sqrt(sum); // If square root is an integer return ((squareRoot - floor(squareRoot)) == 0);} // Driver codeint main(){ string str = "d"; if (isPerfectSquareString(str)) cout << "Yes"; else cout << "No";}
// Java program to find if string// is a perfect square or not.import java.io.*; class GFG { static boolean isPerfectSquareString(String str) { int sum = 0; // calculating the length // of the string int len = str.length(); // calculating the ASCII // value of the string for (int i = 0; i < len; i++) sum += (int)str.charAt(i); // Find floating point value // of square root of x. long squareRoot = (long)Math.sqrt(sum); // If square root is an integer return ((squareRoot - Math.floor(squareRoot)) == 0); } // Driver code public static void main (String[] args) { String str = "d"; if (isPerfectSquareString(str)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Ajit.
# Python3 program to find# if string is a perfect# square or not.import math;def isPerfectSquareString(str): sum = 0; # calculating the length # of the string l = len(str); # calculating the ASCII # value of the string for i in range(l): sum = sum + ord(str[i]); # Find floating point value # of square root of x. squareRoot = math.sqrt(sum); # If square root is an integer return ((squareRoot - math.floor(squareRoot)) == 0); # Driver codestr = "d"; if (isPerfectSquareString(str)): print("Yes");else: print("No"); # This code is contributed by mits
// C# program to find if string// is a perfect square or not.using System; class GFG{ static bool isPerfectSquareString(string str) { int sum = 0; // calculating the length // of the string int len = str.Length; // calculating the ASCII // value of the string for (int i = 0; i < len; i++) sum += (int)str[i]; // Find floating point value // of square root of x. double squareRoot = Math.Sqrt(sum); double F = Math.Floor(squareRoot); // If square root is an integer return ((squareRoot - F) == 0); } // Driver Code public static void Main() { string str = "d"; if (isPerfectSquareString(str)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Sam007
<?php// PHP program to find if string// is a perfect square or not. function isPerfectSquareString($str){ $sum = 0; // calculating the length // of the string $len = strlen($str); // calculating the ASCII // value of the string for ($i = 0; $i < $len; $i++) $sum += (int)$str[$i]; // Find floating point value // of square root of x. $squareRoot = sqrt($sum); // If square root is an integer return (($squareRoot - floor($squareRoot)) == 0);} // Driver code$str = "d"; if (isPerfectSquareString($str)) echo "Yes";elseecho "No"; // This code is contributed by m_kit?>
<script> // JavaScript program to find if string is a// perfect square or not. function isPerfectSquareString(str){ var sum = 0; // Calculating the length of // the string var len = str.length; // Calculating the ASCII value // of the string for(var i = 0; i < len; i++) sum += str.charCodeAt(i); // Find floating point value of // square root of x. var squareRoot = Math.sqrt(sum); // If square root is an integer return squareRoot - Math.floor(squareRoot) == 0;} // Driver codevar str = "d"; if (isPerfectSquareString(str)) document.write("Yes");else document.write("No"); // This code is contributed by rdtank </script>
Yes
YouTubeGeeksforGeeks507K subscribersPerfect Square String | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:00•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_Fv1yMF3bfo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
jit_t
Sam007
Mithun Kumar
rdtank
maths-perfect-square
Mathematical
School Programming
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
|
[
{
"code": null,
"e": 26501,
"s": 26473,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 26610,
"s": 26501,
"text": "Given a String str and the task is to check sum of ASCII value of all characters is a perfect square or not."
},
{
"code": null,
"e": 26622,
"s": 26610,
"text": "Examples : "
},
{
"code": null,
"e": 26704,
"s": 26622,
"text": "Input : ddddddddddddddddddddddddd\nOutput : Yes\n\nInput : GeeksForGeeks\nOutput : No"
},
{
"code": null,
"e": 26716,
"s": 26704,
"text": "Algorithm "
},
{
"code": null,
"e": 26744,
"s": 26716,
"text": "Calculate the string length"
},
{
"code": null,
"e": 26791,
"s": 26744,
"text": "Calculate sum of ASCII value of all characters"
},
{
"code": null,
"e": 26868,
"s": 26791,
"text": "Take the square root of the number sum and store it into variable squareRoot"
},
{
"code": null,
"e": 26932,
"s": 26868,
"text": "Take floor value of the squareRoot and subtract from squareRoot"
},
{
"code": null,
"e": 27031,
"s": 26932,
"text": "If the difference of floor value of squareRoot and squareRoot is 0 then print “Yes” otherwise “No”"
},
{
"code": null,
"e": 27084,
"s": 27031,
"text": "Below is the implementation of the above approach : "
},
{
"code": null,
"e": 27088,
"s": 27084,
"text": "C++"
},
{
"code": null,
"e": 27093,
"s": 27088,
"text": "Java"
},
{
"code": null,
"e": 27101,
"s": 27093,
"text": "Python3"
},
{
"code": null,
"e": 27104,
"s": 27101,
"text": "C#"
},
{
"code": null,
"e": 27108,
"s": 27104,
"text": "PHP"
},
{
"code": null,
"e": 27119,
"s": 27108,
"text": "Javascript"
},
{
"code": "// C++ program to find if string is a// perfect square or not.#include <bits/stdc++.h>using namespace std; bool isPerfectSquareString(string str){ int sum = 0; // calculating the length of // the string int len = str.length(); // calculating the ASCII value // of the string for (int i = 0; i < len; i++) sum += (int)str[i]; // Find floating point value of // square root of x. long double squareRoot = sqrt(sum); // If square root is an integer return ((squareRoot - floor(squareRoot)) == 0);} // Driver codeint main(){ string str = \"d\"; if (isPerfectSquareString(str)) cout << \"Yes\"; else cout << \"No\";}",
"e": 27828,
"s": 27119,
"text": null
},
{
"code": "// Java program to find if string// is a perfect square or not.import java.io.*; class GFG { static boolean isPerfectSquareString(String str) { int sum = 0; // calculating the length // of the string int len = str.length(); // calculating the ASCII // value of the string for (int i = 0; i < len; i++) sum += (int)str.charAt(i); // Find floating point value // of square root of x. long squareRoot = (long)Math.sqrt(sum); // If square root is an integer return ((squareRoot - Math.floor(squareRoot)) == 0); } // Driver code public static void main (String[] args) { String str = \"d\"; if (isPerfectSquareString(str)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Ajit.",
"e": 28763,
"s": 27828,
"text": null
},
{
"code": "# Python3 program to find# if string is a perfect# square or not.import math;def isPerfectSquareString(str): sum = 0; # calculating the length # of the string l = len(str); # calculating the ASCII # value of the string for i in range(l): sum = sum + ord(str[i]); # Find floating point value # of square root of x. squareRoot = math.sqrt(sum); # If square root is an integer return ((squareRoot - math.floor(squareRoot)) == 0); # Driver codestr = \"d\"; if (isPerfectSquareString(str)): print(\"Yes\");else: print(\"No\"); # This code is contributed by mits",
"e": 29395,
"s": 28763,
"text": null
},
{
"code": "// C# program to find if string// is a perfect square or not.using System; class GFG{ static bool isPerfectSquareString(string str) { int sum = 0; // calculating the length // of the string int len = str.Length; // calculating the ASCII // value of the string for (int i = 0; i < len; i++) sum += (int)str[i]; // Find floating point value // of square root of x. double squareRoot = Math.Sqrt(sum); double F = Math.Floor(squareRoot); // If square root is an integer return ((squareRoot - F) == 0); } // Driver Code public static void Main() { string str = \"d\"; if (isPerfectSquareString(str)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Sam007",
"e": 30285,
"s": 29395,
"text": null
},
{
"code": "<?php// PHP program to find if string// is a perfect square or not. function isPerfectSquareString($str){ $sum = 0; // calculating the length // of the string $len = strlen($str); // calculating the ASCII // value of the string for ($i = 0; $i < $len; $i++) $sum += (int)$str[$i]; // Find floating point value // of square root of x. $squareRoot = sqrt($sum); // If square root is an integer return (($squareRoot - floor($squareRoot)) == 0);} // Driver code$str = \"d\"; if (isPerfectSquareString($str)) echo \"Yes\";elseecho \"No\"; // This code is contributed by m_kit?>",
"e": 30929,
"s": 30285,
"text": null
},
{
"code": "<script> // JavaScript program to find if string is a// perfect square or not. function isPerfectSquareString(str){ var sum = 0; // Calculating the length of // the string var len = str.length; // Calculating the ASCII value // of the string for(var i = 0; i < len; i++) sum += str.charCodeAt(i); // Find floating point value of // square root of x. var squareRoot = Math.sqrt(sum); // If square root is an integer return squareRoot - Math.floor(squareRoot) == 0;} // Driver codevar str = \"d\"; if (isPerfectSquareString(str)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by rdtank </script>",
"e": 31609,
"s": 30929,
"text": null
},
{
"code": null,
"e": 31613,
"s": 31609,
"text": "Yes"
},
{
"code": null,
"e": 32435,
"s": 31615,
"text": "YouTubeGeeksforGeeks507K subscribersPerfect Square String | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:00•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=_Fv1yMF3bfo\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 32441,
"s": 32435,
"text": "jit_t"
},
{
"code": null,
"e": 32448,
"s": 32441,
"text": "Sam007"
},
{
"code": null,
"e": 32461,
"s": 32448,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 32468,
"s": 32461,
"text": "rdtank"
},
{
"code": null,
"e": 32489,
"s": 32468,
"text": "maths-perfect-square"
},
{
"code": null,
"e": 32502,
"s": 32489,
"text": "Mathematical"
},
{
"code": null,
"e": 32521,
"s": 32502,
"text": "School Programming"
},
{
"code": null,
"e": 32529,
"s": 32521,
"text": "Strings"
},
{
"code": null,
"e": 32537,
"s": 32529,
"text": "Strings"
},
{
"code": null,
"e": 32550,
"s": 32537,
"text": "Mathematical"
},
{
"code": null,
"e": 32648,
"s": 32550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32672,
"s": 32648,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32715,
"s": 32672,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32729,
"s": 32715,
"text": "Prime Numbers"
},
{
"code": null,
"e": 32771,
"s": 32729,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 32844,
"s": 32771,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 32862,
"s": 32844,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32878,
"s": 32862,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32897,
"s": 32878,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 32922,
"s": 32897,
"text": "Reverse a string in Java"
}
] |
Pagination using Scrapy - Web Scraping with Python - GeeksforGeeks
|
30 Sep, 2021
Pagination using Scrapy. Web scraping is a technique to fetch information from websites .Scrapy is used as a python framework for web scraping. Getting data from a normal website is easier, and can be just achieved by just pulling HTMl of website and fetching data by filtering tags. But what in case when there is pagination in the data you are trying to fetch, For example – Amazon’s products can have multiple pages and to scrap all products successfully, one would need concept of pagination.
Pagination: Pagination, also known as paging, is the process of dividing a document into discrete pages, that means bundle of data on different page. These different pages have their own url. So we need to take these url one by one and scrape these pages. But to keep in mind is when to stop pagination. Generally pages have next button, this next button is able and it get disable when pages are finished. This method is used to get url of pages till the next page button is able and when it get disable no page is left for scraping.
Scraping mobile details from amazon site and applying pagination in the following below project.The scraped details involves name and price of mobiles and pagination to scrape all the result for the following searched url
next_page = response.xpath("//div/div/ul/li[@class='alast']/a/@href").get()if next_page: abs_url = f"https://www.amazon.in{next_page}"yield scrapy.Request( url=abs_url, callback=self.parse)
Note:
abs_url = f"https://www.amazon.in{next_page}"
Here need to take https://www.amazon.in is because next_page is /page2. That is incomplete and the complete url is https://www.amazon.in/page2
Fetch xpath of details need to be scraped –Follow below steps to get xpath –xpath of items:xpath of name:xpath of price:xpath of next page:
xpath of name:
xpath of price:
xpath of next page:
Spider Code: Scraping name and price from amazon site and applying pagination in the below code.import scrapy class MobilesSpider(scrapy.Spider): name = 'mobiles' # create request object initially def start_requests(self): yield scrapy.Request( url ='https://www.amazon.in / s?k = xiome + mobile + phone&crid'\ + '= 2AT2IRC7IKO1K&sprefix = xiome % 2Caps % 2C302&ref = nb_sb_ss_i_1_5', callback = self.parse ) # parse products def parse(self, response): products = response.xpath("//div[@class ='s-include-content-margin s-border-bottom s-latency-cf-section']") for product in products: yield { 'name': product.xpath(".//span[@class ='a-size-medium a-color-base a-text-normal']/text()").get(), 'price': product.xpath(".//span[@class ='a-price-whole']/text()").get() } print() print("Next page") print() next_page = response.xpath("//div / div / ul / li[@class ='a-last']/a/@href").get() if next_page: abs_url = f"https://www.amazon.in{next_page}" yield scrapy.Request( url = abs_url, callback = self.parse ) else: print() print('No Page Left') print()
import scrapy class MobilesSpider(scrapy.Spider): name = 'mobiles' # create request object initially def start_requests(self): yield scrapy.Request( url ='https://www.amazon.in / s?k = xiome + mobile + phone&crid'\ + '= 2AT2IRC7IKO1K&sprefix = xiome % 2Caps % 2C302&ref = nb_sb_ss_i_1_5', callback = self.parse ) # parse products def parse(self, response): products = response.xpath("//div[@class ='s-include-content-margin s-border-bottom s-latency-cf-section']") for product in products: yield { 'name': product.xpath(".//span[@class ='a-size-medium a-color-base a-text-normal']/text()").get(), 'price': product.xpath(".//span[@class ='a-price-whole']/text()").get() } print() print("Next page") print() next_page = response.xpath("//div / div / ul / li[@class ='a-last']/a/@href").get() if next_page: abs_url = f"https://www.amazon.in{next_page}" yield scrapy.Request( url = abs_url, callback = self.parse ) else: print() print('No Page Left') print()
Scraped Results:
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 26199,
"s": 26171,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 26696,
"s": 26199,
"text": "Pagination using Scrapy. Web scraping is a technique to fetch information from websites .Scrapy is used as a python framework for web scraping. Getting data from a normal website is easier, and can be just achieved by just pulling HTMl of website and fetching data by filtering tags. But what in case when there is pagination in the data you are trying to fetch, For example – Amazon’s products can have multiple pages and to scrap all products successfully, one would need concept of pagination."
},
{
"code": null,
"e": 27231,
"s": 26696,
"text": "Pagination: Pagination, also known as paging, is the process of dividing a document into discrete pages, that means bundle of data on different page. These different pages have their own url. So we need to take these url one by one and scrape these pages. But to keep in mind is when to stop pagination. Generally pages have next button, this next button is able and it get disable when pages are finished. This method is used to get url of pages till the next page button is able and when it get disable no page is left for scraping."
},
{
"code": null,
"e": 27453,
"s": 27231,
"text": "Scraping mobile details from amazon site and applying pagination in the following below project.The scraped details involves name and price of mobiles and pagination to scrape all the result for the following searched url"
},
{
"code": "next_page = response.xpath(\"//div/div/ul/li[@class='alast']/a/@href\").get()if next_page: abs_url = f\"https://www.amazon.in{next_page}\"yield scrapy.Request( url=abs_url, callback=self.parse)",
"e": 27652,
"s": 27453,
"text": null
},
{
"code": null,
"e": 27658,
"s": 27652,
"text": "Note:"
},
{
"code": null,
"e": 27705,
"s": 27658,
"text": "abs_url = f\"https://www.amazon.in{next_page}\"\n"
},
{
"code": null,
"e": 27848,
"s": 27705,
"text": "Here need to take https://www.amazon.in is because next_page is /page2. That is incomplete and the complete url is https://www.amazon.in/page2"
},
{
"code": null,
"e": 27988,
"s": 27848,
"text": "Fetch xpath of details need to be scraped –Follow below steps to get xpath –xpath of items:xpath of name:xpath of price:xpath of next page:"
},
{
"code": null,
"e": 28003,
"s": 27988,
"text": "xpath of name:"
},
{
"code": null,
"e": 28019,
"s": 28003,
"text": "xpath of price:"
},
{
"code": null,
"e": 28039,
"s": 28019,
"text": "xpath of next page:"
},
{
"code": null,
"e": 29362,
"s": 28039,
"text": "Spider Code: Scraping name and price from amazon site and applying pagination in the below code.import scrapy class MobilesSpider(scrapy.Spider): name = 'mobiles' # create request object initially def start_requests(self): yield scrapy.Request( url ='https://www.amazon.in / s?k = xiome + mobile + phone&crid'\\ + '= 2AT2IRC7IKO1K&sprefix = xiome % 2Caps % 2C302&ref = nb_sb_ss_i_1_5', callback = self.parse ) # parse products def parse(self, response): products = response.xpath(\"//div[@class ='s-include-content-margin s-border-bottom s-latency-cf-section']\") for product in products: yield { 'name': product.xpath(\".//span[@class ='a-size-medium a-color-base a-text-normal']/text()\").get(), 'price': product.xpath(\".//span[@class ='a-price-whole']/text()\").get() } print() print(\"Next page\") print() next_page = response.xpath(\"//div / div / ul / li[@class ='a-last']/a/@href\").get() if next_page: abs_url = f\"https://www.amazon.in{next_page}\" yield scrapy.Request( url = abs_url, callback = self.parse ) else: print() print('No Page Left') print()"
},
{
"code": "import scrapy class MobilesSpider(scrapy.Spider): name = 'mobiles' # create request object initially def start_requests(self): yield scrapy.Request( url ='https://www.amazon.in / s?k = xiome + mobile + phone&crid'\\ + '= 2AT2IRC7IKO1K&sprefix = xiome % 2Caps % 2C302&ref = nb_sb_ss_i_1_5', callback = self.parse ) # parse products def parse(self, response): products = response.xpath(\"//div[@class ='s-include-content-margin s-border-bottom s-latency-cf-section']\") for product in products: yield { 'name': product.xpath(\".//span[@class ='a-size-medium a-color-base a-text-normal']/text()\").get(), 'price': product.xpath(\".//span[@class ='a-price-whole']/text()\").get() } print() print(\"Next page\") print() next_page = response.xpath(\"//div / div / ul / li[@class ='a-last']/a/@href\").get() if next_page: abs_url = f\"https://www.amazon.in{next_page}\" yield scrapy.Request( url = abs_url, callback = self.parse ) else: print() print('No Page Left') print()",
"e": 30589,
"s": 29362,
"text": null
},
{
"code": null,
"e": 30606,
"s": 30589,
"text": "Scraped Results:"
},
{
"code": null,
"e": 30619,
"s": 30606,
"text": "Web-scraping"
},
{
"code": null,
"e": 30626,
"s": 30619,
"text": "Python"
},
{
"code": null,
"e": 30724,
"s": 30626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30742,
"s": 30724,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30774,
"s": 30742,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30796,
"s": 30774,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30838,
"s": 30796,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30864,
"s": 30838,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30893,
"s": 30864,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30937,
"s": 30893,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 30974,
"s": 30937,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 31016,
"s": 30974,
"text": "Check if element exists in list in Python"
}
] |
How to make Custom Buttons in Plotly? - GeeksforGeeks
|
01 Oct, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
In plotly, actions custom Buttons are used to quickly make actions directly from a record. Custom Buttons can be added to page layouts in CRM, Marketing, and Custom Apps. There are 4 possible methods that can be applied in custom buttons:
restyle: modify data or data attributes
relayout: modify layout attributes
update: modify data and layout attributes
animate: start or pause an animation
Example 1: Using Restyle Method
Python3
import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x = np.random.randint(1, 101, 100)random_y = np.random.randint(1, 101, 100) plot = px.Figure(data=[px.Scatter( x=random_x, y=random_y, mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict( type="buttons", direction="left", buttons=list([ dict( args=["type", "scatter"], label="Scatter Plot", method="restyle" ), dict( args=["type", "bar"], label="Bar Chart", method="restyle" ) ]), ), ]) plot.show()
Output:
Example 2: Using Update method
Python3
import plotly.graph_objects as pximport numpy # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x = np.random.randint(1, 101, 100)random_y = np.random.randint(1, 101, 100) x = ['A', 'B', 'C', 'D'] plot = px.Figure(data=[go.Bar( name='Data 1', x=x, y=[100, 200, 500, 673]), go.Bar( name='Data 2', x=x, y=[56, 123, 982, 213])]) # Add dropdownplot.update_layout( updatemenus=[ dict( type="buttons", direction="left", buttons=list([ dict(label="Both", method="update", args=[{"visible": [True, True]}, {"title": "Both"}]), dict(label="Data 1", method="update", args=[{"visible": [True, False]}, {"title": "Data 1", }]), dict(label="Data 2", method="update", args=[{"visible": [False, True]}, {"title": "Data 2", }]), ]), ) ]) plot.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 24843,
"s": 24815,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25148,
"s": 24843,
"text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. "
},
{
"code": null,
"e": 25387,
"s": 25148,
"text": "In plotly, actions custom Buttons are used to quickly make actions directly from a record. Custom Buttons can be added to page layouts in CRM, Marketing, and Custom Apps. There are 4 possible methods that can be applied in custom buttons:"
},
{
"code": null,
"e": 25427,
"s": 25387,
"text": "restyle: modify data or data attributes"
},
{
"code": null,
"e": 25462,
"s": 25427,
"text": "relayout: modify layout attributes"
},
{
"code": null,
"e": 25504,
"s": 25462,
"text": "update: modify data and layout attributes"
},
{
"code": null,
"e": 25541,
"s": 25504,
"text": "animate: start or pause an animation"
},
{
"code": null,
"e": 25573,
"s": 25541,
"text": "Example 1: Using Restyle Method"
},
{
"code": null,
"e": 25581,
"s": 25573,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x = np.random.randint(1, 101, 100)random_y = np.random.randint(1, 101, 100) plot = px.Figure(data=[px.Scatter( x=random_x, y=random_y, mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict( type=\"buttons\", direction=\"left\", buttons=list([ dict( args=[\"type\", \"scatter\"], label=\"Scatter Plot\", method=\"restyle\" ), dict( args=[\"type\", \"bar\"], label=\"Bar Chart\", method=\"restyle\" ) ]), ), ]) plot.show()",
"e": 26398,
"s": 25581,
"text": null
},
{
"code": null,
"e": 26406,
"s": 26398,
"text": "Output:"
},
{
"code": null,
"e": 26437,
"s": 26406,
"text": "Example 2: Using Update method"
},
{
"code": null,
"e": 26445,
"s": 26437,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as pximport numpy # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x = np.random.randint(1, 101, 100)random_y = np.random.randint(1, 101, 100) x = ['A', 'B', 'C', 'D'] plot = px.Figure(data=[go.Bar( name='Data 1', x=x, y=[100, 200, 500, 673]), go.Bar( name='Data 2', x=x, y=[56, 123, 982, 213])]) # Add dropdownplot.update_layout( updatemenus=[ dict( type=\"buttons\", direction=\"left\", buttons=list([ dict(label=\"Both\", method=\"update\", args=[{\"visible\": [True, True]}, {\"title\": \"Both\"}]), dict(label=\"Data 1\", method=\"update\", args=[{\"visible\": [True, False]}, {\"title\": \"Data 1\", }]), dict(label=\"Data 2\", method=\"update\", args=[{\"visible\": [False, True]}, {\"title\": \"Data 2\", }]), ]), ) ]) plot.show()",
"e": 27613,
"s": 26445,
"text": null
},
{
"code": null,
"e": 27621,
"s": 27613,
"text": "Output:"
},
{
"code": null,
"e": 27635,
"s": 27621,
"text": "Python-Plotly"
},
{
"code": null,
"e": 27642,
"s": 27635,
"text": "Python"
},
{
"code": null,
"e": 27740,
"s": 27642,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27768,
"s": 27740,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27818,
"s": 27768,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27840,
"s": 27818,
"text": "Python map() function"
},
{
"code": null,
"e": 27884,
"s": 27840,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 27902,
"s": 27884,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27925,
"s": 27902,
"text": "Taking input in Python"
},
{
"code": null,
"e": 27960,
"s": 27925,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27992,
"s": 27960,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28014,
"s": 27992,
"text": "Enumerate() in Python"
}
] |
PHP | create_function() Function - GeeksforGeeks
|
25 Jun, 2018
The create_function() is an inbuilt function in PHP which is used to create an anonymous (lambda-style) function in the PHP.
Syntax:
string create_function ( $args, $code )
Parameters: This function accepts two parameters which is describes below:
$args: It is a string type function argument.
$code: It is a string type function code.
Note: Usually, these parameters will be passed as single quote delimited strings. The reason for using single quoted strings is to protect the variable names from parsing, otherwise, double quotes will be needed to escape the variable names, e.g. \$avar.
Return Value: This function returns a unique function name as a string, Otherwise returns FALSE on error.
Below programs illustrate the create_function() function in PHP:
Program 1: Creating an anonymous function with create_function()
<?php//create a function from information // gathered at run time, $newfunc = create_function('$a, $b', 'return "ln($a) + ln($b) = " . log($a * $b);'); echo "New anonymous function: $newfunc\n";echo $newfunc(2, M_E) . "\n";?>
New anonymous function: lambda_1
ln(2) + ln(2.718281828459) = 1.6931471805599
Program 2: Create a general function with create_function()
<?php// General function that can apply a set of // operations to a list of parameters. function Program($value1, $value2, $arr){ foreach ($arr as $val) { echo $val($value1, $value2) . "\n"; }} // create a bunch of math functions$f1 = 'if ($a >= 0) { return "b * a^2 = ". $b * sqrt($a);} else { return false; }'; $f2 = "return \"min(a, b) = \".min(\$a, \$b);"; $farr = array( create_function('$x, $y', 'return "a hypotenuse: ".sqrt($x * $x + $y * $y);'), create_function('$a, $b', $f1), create_function('$a, $b', $f2)); echo "first array of anonymous functions" . "\nParameter is a = 2 and b = 3\n";Program(2, 3, $farr); // now make a bunch of string functions$sarr = array( create_function('$a, $b', 'return "Lower case : " . strtolower($a) ;'), create_function('$a, $b', 'return "Similar Character : " . similar_text($a, $b, $percent);')); echo "\nSecond array of anonymous functions" . "\nParameter is a = GeeksForGeeks and" . "b = GeeksForGeeks\n"; Program("GeeksForGeeks", "GeeksForGeeks", $sarr);?>
first array of anonymous functions
Parameter is a = 2 and b = 3
a hypotenuse: 3.605551275464
b * a^2 = 4.2426406871193
min(a, b) = 2
Second array of anonymous functions
Parameter is a = GeeksForGeeks andb = GeeksForGeeks
Lower case : geeksforgeeks
Similar Character : 13
References: http://php.net/manual/en/function.create-function.php
PHP-function
Misc
PHP
Misc
Misc
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
|
[
{
"code": null,
"e": 26103,
"s": 26075,
"text": "\n25 Jun, 2018"
},
{
"code": null,
"e": 26228,
"s": 26103,
"text": "The create_function() is an inbuilt function in PHP which is used to create an anonymous (lambda-style) function in the PHP."
},
{
"code": null,
"e": 26236,
"s": 26228,
"text": "Syntax:"
},
{
"code": null,
"e": 26276,
"s": 26236,
"text": "string create_function ( $args, $code )"
},
{
"code": null,
"e": 26351,
"s": 26276,
"text": "Parameters: This function accepts two parameters which is describes below:"
},
{
"code": null,
"e": 26397,
"s": 26351,
"text": "$args: It is a string type function argument."
},
{
"code": null,
"e": 26439,
"s": 26397,
"text": "$code: It is a string type function code."
},
{
"code": null,
"e": 26694,
"s": 26439,
"text": "Note: Usually, these parameters will be passed as single quote delimited strings. The reason for using single quoted strings is to protect the variable names from parsing, otherwise, double quotes will be needed to escape the variable names, e.g. \\$avar."
},
{
"code": null,
"e": 26800,
"s": 26694,
"text": "Return Value: This function returns a unique function name as a string, Otherwise returns FALSE on error."
},
{
"code": null,
"e": 26865,
"s": 26800,
"text": "Below programs illustrate the create_function() function in PHP:"
},
{
"code": null,
"e": 26930,
"s": 26865,
"text": "Program 1: Creating an anonymous function with create_function()"
},
{
"code": "<?php//create a function from information // gathered at run time, $newfunc = create_function('$a, $b', 'return \"ln($a) + ln($b) = \" . log($a * $b);'); echo \"New anonymous function: $newfunc\\n\";echo $newfunc(2, M_E) . \"\\n\";?>",
"e": 27164,
"s": 26930,
"text": null
},
{
"code": null,
"e": 27243,
"s": 27164,
"text": "New anonymous function: lambda_1\nln(2) + ln(2.718281828459) = 1.6931471805599\n"
},
{
"code": null,
"e": 27303,
"s": 27243,
"text": "Program 2: Create a general function with create_function()"
},
{
"code": "<?php// General function that can apply a set of // operations to a list of parameters. function Program($value1, $value2, $arr){ foreach ($arr as $val) { echo $val($value1, $value2) . \"\\n\"; }} // create a bunch of math functions$f1 = 'if ($a >= 0) { return \"b * a^2 = \". $b * sqrt($a);} else { return false; }'; $f2 = \"return \\\"min(a, b) = \\\".min(\\$a, \\$b);\"; $farr = array( create_function('$x, $y', 'return \"a hypotenuse: \".sqrt($x * $x + $y * $y);'), create_function('$a, $b', $f1), create_function('$a, $b', $f2)); echo \"first array of anonymous functions\" . \"\\nParameter is a = 2 and b = 3\\n\";Program(2, 3, $farr); // now make a bunch of string functions$sarr = array( create_function('$a, $b', 'return \"Lower case : \" . strtolower($a) ;'), create_function('$a, $b', 'return \"Similar Character : \" . similar_text($a, $b, $percent);')); echo \"\\nSecond array of anonymous functions\" . \"\\nParameter is a = GeeksForGeeks and\" . \"b = GeeksForGeeks\\n\"; Program(\"GeeksForGeeks\", \"GeeksForGeeks\", $sarr);?>",
"e": 28393,
"s": 27303,
"text": null
},
{
"code": null,
"e": 28666,
"s": 28393,
"text": "first array of anonymous functions\nParameter is a = 2 and b = 3\na hypotenuse: 3.605551275464\nb * a^2 = 4.2426406871193\nmin(a, b) = 2\n\nSecond array of anonymous functions\nParameter is a = GeeksForGeeks andb = GeeksForGeeks\nLower case : geeksforgeeks\nSimilar Character : 13\n"
},
{
"code": null,
"e": 28732,
"s": 28666,
"text": "References: http://php.net/manual/en/function.create-function.php"
},
{
"code": null,
"e": 28745,
"s": 28732,
"text": "PHP-function"
},
{
"code": null,
"e": 28750,
"s": 28745,
"text": "Misc"
},
{
"code": null,
"e": 28754,
"s": 28750,
"text": "PHP"
},
{
"code": null,
"e": 28759,
"s": 28754,
"text": "Misc"
},
{
"code": null,
"e": 28764,
"s": 28759,
"text": "Misc"
},
{
"code": null,
"e": 28768,
"s": 28764,
"text": "PHP"
},
{
"code": null,
"e": 28866,
"s": 28768,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28887,
"s": 28866,
"text": "Activation Functions"
},
{
"code": null,
"e": 28925,
"s": 28887,
"text": "Characteristics of Internet of Things"
},
{
"code": null,
"e": 28961,
"s": 28925,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 28996,
"s": 28961,
"text": "Sensors in Internet of Things(IoT)"
},
{
"code": null,
"e": 29035,
"s": 28996,
"text": "Challenges in Internet of things (IoT)"
},
{
"code": null,
"e": 29080,
"s": 29035,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 29130,
"s": 29080,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29170,
"s": 29130,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29194,
"s": 29170,
"text": "PHP in_array() Function"
}
] |
Python | Pandas Index.repeat() - GeeksforGeeks
|
18 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.repeat() function repeat elements of an Index. The function returns a new index where each element of the current index is repeated consecutively a given number of times.
Syntax: Index.repeat(repeats, *args, **kwargs)
Parameters :repeats : The number of repetitions for each element.**kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy.
Returns : Newly created Index with repeated elements.
Example #1: Use Index.repeat()() function to repeat the elements of the index 2 times.
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug', 'Mastiff', None, 'Beagle']) # Print the Indexidx
Output :
Let’s repeat the index elements 2 times.
# to repeat the valuesidx.repeat(2)
Output :As we can see in the output, the function has returned a new index with all the values repeated 2 times. One important thing to notice is that the function has also repeated the NaN value.
Example #2: Use Index.repeat() function to repeat the value of index 3 times.
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([22, 14, 8, 56, None, 21, None, 23]) # Print the Indexidx
Output :
Let’s repeat the index elements 3 times.
# to repeat the valuesidx.repeat(3)
Output :
As we can see in the output, the function has returned a new index with all the values repeated 3 times. One important thing to notice is that the function has also repeated the NaN value.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n18 Dec, 2018"
},
{
"code": null,
"e": 25751,
"s": 25537,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 25935,
"s": 25751,
"text": "Pandas Index.repeat() function repeat elements of an Index. The function returns a new index where each element of the current index is repeated consecutively a given number of times."
},
{
"code": null,
"e": 25982,
"s": 25935,
"text": "Syntax: Index.repeat(repeats, *args, **kwargs)"
},
{
"code": null,
"e": 26145,
"s": 25982,
"text": "Parameters :repeats : The number of repetitions for each element.**kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy."
},
{
"code": null,
"e": 26199,
"s": 26145,
"text": "Returns : Newly created Index with repeated elements."
},
{
"code": null,
"e": 26286,
"s": 26199,
"text": "Example #1: Use Index.repeat()() function to repeat the elements of the index 2 times."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug', 'Mastiff', None, 'Beagle']) # Print the Indexidx",
"e": 26476,
"s": 26286,
"text": null
},
{
"code": null,
"e": 26485,
"s": 26476,
"text": "Output :"
},
{
"code": null,
"e": 26526,
"s": 26485,
"text": "Let’s repeat the index elements 2 times."
},
{
"code": "# to repeat the valuesidx.repeat(2)",
"e": 26562,
"s": 26526,
"text": null
},
{
"code": null,
"e": 26759,
"s": 26562,
"text": "Output :As we can see in the output, the function has returned a new index with all the values repeated 2 times. One important thing to notice is that the function has also repeated the NaN value."
},
{
"code": null,
"e": 26837,
"s": 26759,
"text": "Example #2: Use Index.repeat() function to repeat the value of index 3 times."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([22, 14, 8, 56, None, 21, None, 23]) # Print the Indexidx",
"e": 26976,
"s": 26837,
"text": null
},
{
"code": null,
"e": 26985,
"s": 26976,
"text": "Output :"
},
{
"code": null,
"e": 27026,
"s": 26985,
"text": "Let’s repeat the index elements 3 times."
},
{
"code": "# to repeat the valuesidx.repeat(3)",
"e": 27062,
"s": 27026,
"text": null
},
{
"code": null,
"e": 27071,
"s": 27062,
"text": "Output :"
},
{
"code": null,
"e": 27260,
"s": 27071,
"text": "As we can see in the output, the function has returned a new index with all the values repeated 3 times. One important thing to notice is that the function has also repeated the NaN value."
},
{
"code": null,
"e": 27283,
"s": 27260,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 27297,
"s": 27283,
"text": "Python-pandas"
},
{
"code": null,
"e": 27304,
"s": 27297,
"text": "Python"
},
{
"code": null,
"e": 27402,
"s": 27304,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27434,
"s": 27402,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27476,
"s": 27434,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27518,
"s": 27476,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27545,
"s": 27518,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27601,
"s": 27545,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27640,
"s": 27601,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27662,
"s": 27640,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27693,
"s": 27662,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27722,
"s": 27693,
"text": "Create a directory in Python"
}
] |
Queue Operations - GeeksforGeeks
|
24 Dec, 2021
Given N integers, the task is to insert those elements in the queue. Also, given M integers, the task is to find the frequency of each number in the Queue.
Examples:
Input: N = 8 1 2 3 4 5 2 3 1 (N integers)M = 51 3 2 9 10 (M integers)Output:2 2 2 -1 -1
Explanation:After inserting 1, 2, 3, 4, 5, 2, 3, 1 into the queue, frequency of 1 is 2, 3 is 2, 2 is 2, 9 is -1 and 10 is -1 (since, 9 and 10 is not there in the queue).
Input:N = 5 5 2 2 4 5 (N integers)M = 52 3 4 5 1 (M integers)Output:2 -1 1 2 -1
Approach: The given problem can be solved by using a simple queue. The idea is to insert N integers one by one into the queue and then check the frequency of M integers. Separate functions will be created to perform both operations. Follow the steps below to solve the problem.
Create a queue and push all given integers into the queue.
After pushing all the elements into the queue create another function for counting the frequency of given M elements one by one.
Take a variable cntFrequency to keep track of frequency of current element.
Pop all the elements from queue till its size and each time check if current element in queue is equal to element for which we are checking for frequency.– if both are equal, increment cntFrequency by 1– else, do nothing.
Push the current element back to the queue so that for next case queue will not get disturbed.
Print the frequency of each element found.
Below is the implementation of the above approach:
Java
Python3
C#
// Java Program to implement above approachimport java.io.*;import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Declaring Queue Queue<Integer> q = new LinkedList<>(); int N = 8; int[] a = new int[] { 1, 2, 3, 4, 5, 2, 3, 1 }; int M = 5; int[] b = new int[] { 1, 3, 2, 9, 10 }; // Invoking object of Geeks class Geeks obj = new Geeks(); for (int i = 0; i < N; i++) { // calling insert() // to add elements in queue obj.insert(q, a[i]); } for (int i = 0; i < M; i++) { // calling findFrequency() int f = obj.findFrequency(q, b[i]); if (f != 0) { // variable f // will have final frequency System.out.print(f + " "); } else { System.out.print("-1" + " "); } } }} // Helper class Geeks to implement// insert() and findFrequency()class Geeks { // Function to insert // element into the queue static void insert(Queue<Integer> q, int k) { // adding N integers into the Queue q.add(k); } // Function to find frequency of an element // return the frequency of k static int findFrequency(Queue<Integer> q, int k) { // to count frequency of elements int cntFrequency = 0; // storing size of queue in a variable int size = q.size(); // running loop until size becomes zero while (size-- != 0) { // storing and deleting // first element from queue int x = q.poll(); // comparing if it's equal to integer K // that belongs to M if (x == k) { // increment count cntFrequency++; } // add element back to queue because // we also want N integers q.add(x); } // return the count return cntFrequency; }}
# Python Program to implement above approachimport collections # Helper class Geeks to implement# insert() and findFrequency()class Geeks: # Function to insert # element into the queue def insert(self, q, k): # adding N integers into the Queue q.append(k) # Function to find frequency of an element # return the frequency of k def findFrequency(self, q, k): # to count frequency of elements cntFrequency = 0 # storing size of queue in a variable size = len(q) # running loop until size becomes zero while (size): size = size - 1 # storing and deleting # first element from queue x = q.popleft() # comparing if it's equal to integer K # that belongs to M if (x == k): # increment count cntFrequency += 1 # add element back to queue because # we also want N integers q.append(x) # return the count return cntFrequency # Declaring Queueq = collections.deque()N = 8a = [1, 2, 3, 4, 5, 2, 3, 1]M = 5b = [1, 3, 2, 9, 10] # Invoking object of Geeks classobj = Geeks() for i in range(N): # calling insert() # to add elements in queue obj.insert(q, a[i]) for i in range(M): # calling findFrequency() f = obj.findFrequency(q, b[i]) if (f != 0): # variable f # will have final frequency print(f, end=" ") else: print("-1", end=" ")print(" ") # This code is contributed by gfgking.
// C# Program to implement above approachusing System;using System.Collections.Generic; public class GFG { // Helper class Geeks to implement// insert() and findFrequency()public class Geeks { // Function to insert // element into the queue public void insert(Queue<int> q, int k) { // adding N integers into the Queue q.Enqueue(k); } // Function to find frequency of an element // return the frequency of k public int findFrequency(Queue<int> q, int k) { // to count frequency of elements int cntFrequency = 0; // storing size of queue in a variable int size = q.Count; // running loop until size becomes zero while (size-- != 0) { // storing and deleting // first element from queue int x = q.Peek(); q.Dequeue(); // comparing if it's equal to integer K // that belongs to M if (x == k) { // increment count cntFrequency++; } // add element back to queue because // we also want N integers q.Enqueue(x); } // return the count return cntFrequency; }} // Driver code public static void Main() { // Declaring Queue Queue<int> q = new Queue<int>(); int N = 8; int[] a = new int[] { 1, 2, 3, 4, 5, 2, 3, 1 }; int M = 5; int[] b = new int[] { 1, 3, 2, 9, 10 }; // Invoking object of Geeks class Geeks obj = new Geeks(); for (int i = 0; i < N; i++) { // calling insert() // to add elements in queue obj.insert(q, a[i]); } for (int i = 0; i < M; i++) { // calling findFrequency() int f = obj.findFrequency(q, b[i]); if (f != 0) { // variable f // will have final frequency Console.Write(f + " "); } else { Console.Write("-1" + " "); } } }} // This code is contributed by SURENDRA_GANGWAR.
2 2 2 -1 -1
Time Complexity: O(N*M)Auxiliary Space: O(N)
SURENDRA_GANGWAR
gfgking
surindertarika1234
simmytarika5
clintra
arorakashish0911
Blogathon-2021
Data Structures-Queue
Blogathon
Queue
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue Interface In Java
Queue in Python
Queue | Set 1 (Introduction and Array Implementation)
|
[
{
"code": null,
"e": 26175,
"s": 26147,
"text": "\n24 Dec, 2021"
},
{
"code": null,
"e": 26331,
"s": 26175,
"text": "Given N integers, the task is to insert those elements in the queue. Also, given M integers, the task is to find the frequency of each number in the Queue."
},
{
"code": null,
"e": 26341,
"s": 26331,
"text": "Examples:"
},
{
"code": null,
"e": 26431,
"s": 26341,
"text": "Input: N = 8 1 2 3 4 5 2 3 1 (N integers)M = 51 3 2 9 10 (M integers)Output:2 2 2 -1 -1"
},
{
"code": null,
"e": 26602,
"s": 26431,
"text": "Explanation:After inserting 1, 2, 3, 4, 5, 2, 3, 1 into the queue, frequency of 1 is 2, 3 is 2, 2 is 2, 9 is -1 and 10 is -1 (since, 9 and 10 is not there in the queue)."
},
{
"code": null,
"e": 26686,
"s": 26602,
"text": "Input:N = 5 5 2 2 4 5 (N integers)M = 52 3 4 5 1 (M integers)Output:2 -1 1 2 -1"
},
{
"code": null,
"e": 26964,
"s": 26686,
"text": "Approach: The given problem can be solved by using a simple queue. The idea is to insert N integers one by one into the queue and then check the frequency of M integers. Separate functions will be created to perform both operations. Follow the steps below to solve the problem."
},
{
"code": null,
"e": 27023,
"s": 26964,
"text": "Create a queue and push all given integers into the queue."
},
{
"code": null,
"e": 27152,
"s": 27023,
"text": "After pushing all the elements into the queue create another function for counting the frequency of given M elements one by one."
},
{
"code": null,
"e": 27228,
"s": 27152,
"text": "Take a variable cntFrequency to keep track of frequency of current element."
},
{
"code": null,
"e": 27450,
"s": 27228,
"text": "Pop all the elements from queue till its size and each time check if current element in queue is equal to element for which we are checking for frequency.– if both are equal, increment cntFrequency by 1– else, do nothing."
},
{
"code": null,
"e": 27545,
"s": 27450,
"text": "Push the current element back to the queue so that for next case queue will not get disturbed."
},
{
"code": null,
"e": 27588,
"s": 27545,
"text": "Print the frequency of each element found."
},
{
"code": null,
"e": 27639,
"s": 27588,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27644,
"s": 27639,
"text": "Java"
},
{
"code": null,
"e": 27652,
"s": 27644,
"text": "Python3"
},
{
"code": null,
"e": 27655,
"s": 27652,
"text": "C#"
},
{
"code": "// Java Program to implement above approachimport java.io.*;import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Declaring Queue Queue<Integer> q = new LinkedList<>(); int N = 8; int[] a = new int[] { 1, 2, 3, 4, 5, 2, 3, 1 }; int M = 5; int[] b = new int[] { 1, 3, 2, 9, 10 }; // Invoking object of Geeks class Geeks obj = new Geeks(); for (int i = 0; i < N; i++) { // calling insert() // to add elements in queue obj.insert(q, a[i]); } for (int i = 0; i < M; i++) { // calling findFrequency() int f = obj.findFrequency(q, b[i]); if (f != 0) { // variable f // will have final frequency System.out.print(f + \" \"); } else { System.out.print(\"-1\" + \" \"); } } }} // Helper class Geeks to implement// insert() and findFrequency()class Geeks { // Function to insert // element into the queue static void insert(Queue<Integer> q, int k) { // adding N integers into the Queue q.add(k); } // Function to find frequency of an element // return the frequency of k static int findFrequency(Queue<Integer> q, int k) { // to count frequency of elements int cntFrequency = 0; // storing size of queue in a variable int size = q.size(); // running loop until size becomes zero while (size-- != 0) { // storing and deleting // first element from queue int x = q.poll(); // comparing if it's equal to integer K // that belongs to M if (x == k) { // increment count cntFrequency++; } // add element back to queue because // we also want N integers q.add(x); } // return the count return cntFrequency; }}",
"e": 29724,
"s": 27655,
"text": null
},
{
"code": "# Python Program to implement above approachimport collections # Helper class Geeks to implement# insert() and findFrequency()class Geeks: # Function to insert # element into the queue def insert(self, q, k): # adding N integers into the Queue q.append(k) # Function to find frequency of an element # return the frequency of k def findFrequency(self, q, k): # to count frequency of elements cntFrequency = 0 # storing size of queue in a variable size = len(q) # running loop until size becomes zero while (size): size = size - 1 # storing and deleting # first element from queue x = q.popleft() # comparing if it's equal to integer K # that belongs to M if (x == k): # increment count cntFrequency += 1 # add element back to queue because # we also want N integers q.append(x) # return the count return cntFrequency # Declaring Queueq = collections.deque()N = 8a = [1, 2, 3, 4, 5, 2, 3, 1]M = 5b = [1, 3, 2, 9, 10] # Invoking object of Geeks classobj = Geeks() for i in range(N): # calling insert() # to add elements in queue obj.insert(q, a[i]) for i in range(M): # calling findFrequency() f = obj.findFrequency(q, b[i]) if (f != 0): # variable f # will have final frequency print(f, end=\" \") else: print(\"-1\", end=\" \")print(\" \") # This code is contributed by gfgking.",
"e": 31345,
"s": 29724,
"text": null
},
{
"code": "// C# Program to implement above approachusing System;using System.Collections.Generic; public class GFG { // Helper class Geeks to implement// insert() and findFrequency()public class Geeks { // Function to insert // element into the queue public void insert(Queue<int> q, int k) { // adding N integers into the Queue q.Enqueue(k); } // Function to find frequency of an element // return the frequency of k public int findFrequency(Queue<int> q, int k) { // to count frequency of elements int cntFrequency = 0; // storing size of queue in a variable int size = q.Count; // running loop until size becomes zero while (size-- != 0) { // storing and deleting // first element from queue int x = q.Peek(); q.Dequeue(); // comparing if it's equal to integer K // that belongs to M if (x == k) { // increment count cntFrequency++; } // add element back to queue because // we also want N integers q.Enqueue(x); } // return the count return cntFrequency; }} // Driver code public static void Main() { // Declaring Queue Queue<int> q = new Queue<int>(); int N = 8; int[] a = new int[] { 1, 2, 3, 4, 5, 2, 3, 1 }; int M = 5; int[] b = new int[] { 1, 3, 2, 9, 10 }; // Invoking object of Geeks class Geeks obj = new Geeks(); for (int i = 0; i < N; i++) { // calling insert() // to add elements in queue obj.insert(q, a[i]); } for (int i = 0; i < M; i++) { // calling findFrequency() int f = obj.findFrequency(q, b[i]); if (f != 0) { // variable f // will have final frequency Console.Write(f + \" \"); } else { Console.Write(\"-1\" + \" \"); } } }} // This code is contributed by SURENDRA_GANGWAR.",
"e": 33555,
"s": 31345,
"text": null
},
{
"code": null,
"e": 33568,
"s": 33555,
"text": "2 2 2 -1 -1 "
},
{
"code": null,
"e": 33613,
"s": 33568,
"text": "Time Complexity: O(N*M)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33630,
"s": 33613,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 33638,
"s": 33630,
"text": "gfgking"
},
{
"code": null,
"e": 33657,
"s": 33638,
"text": "surindertarika1234"
},
{
"code": null,
"e": 33670,
"s": 33657,
"text": "simmytarika5"
},
{
"code": null,
"e": 33678,
"s": 33670,
"text": "clintra"
},
{
"code": null,
"e": 33695,
"s": 33678,
"text": "arorakashish0911"
},
{
"code": null,
"e": 33710,
"s": 33695,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 33732,
"s": 33710,
"text": "Data Structures-Queue"
},
{
"code": null,
"e": 33742,
"s": 33732,
"text": "Blogathon"
},
{
"code": null,
"e": 33748,
"s": 33742,
"text": "Queue"
},
{
"code": null,
"e": 33754,
"s": 33748,
"text": "Queue"
},
{
"code": null,
"e": 33852,
"s": 33754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33909,
"s": 33852,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 33950,
"s": 33909,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 33980,
"s": 33950,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 34015,
"s": 33980,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 34059,
"s": 34015,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 34099,
"s": 34059,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 34133,
"s": 34099,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 34157,
"s": 34133,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 34173,
"s": 34157,
"text": "Queue in Python"
}
] |
Python program to print the initials of a name with last name in full?
|
Here we use different python inbuilt function. First we use split().split the words into a list. Then traverse till the second last word and upper() function is used for print first character in capital and then add the last word which is title of a name and here we use title(),title function converts the first alphabet to capital.
Input Pradip Chandra Sarkar
Output P.C Sarkar
fullname(str1)
/* str1 is a string */
Step 1: first we split the string into a list.
Step 2: newspace is initialized by a space(“”)
Step 3: then traverse the list till the second last word.
Step 4: then adds the capital first character using the upper function.
Step 5: then get the last item of the list.
# python program to print initials of a name
def fullname(str1):
# split the string into a list
lst = str1.split()
newspace = ""
# traverse in the list
for i in range(len(lst)-1):
str1 = lst[i]
# adds the capital first character
newspace += (str1[0].upper()+'.')
# l[-1] gives last item of list l.
newspace += lst[-1].title()
return newspace
# Driver code
str1=input("Enter Full Name ::>")
print("Short Form of Name Is ::>",fullname(str1))
Enter Full Name ::>pradip chandra sarkar
Short Form of Name Is ::> P.C.Sarkar
|
[
{
"code": null,
"e": 1396,
"s": 1062,
"text": "Here we use different python inbuilt function. First we use split().split the words into a list. Then traverse till the second last word and upper() function is used for print first character in capital and then add the last word which is title of a name and here we use title(),title function converts the first alphabet to capital."
},
{
"code": null,
"e": 1443,
"s": 1396,
"text": "Input Pradip Chandra Sarkar\nOutput P.C Sarkar\n"
},
{
"code": null,
"e": 1750,
"s": 1443,
"text": "fullname(str1)\n/* str1 is a string */\nStep 1: first we split the string into a list.\nStep 2: newspace is initialized by a space(“”)\nStep 3: then traverse the list till the second last word.\nStep 4: then adds the capital first character using the upper function.\nStep 5: then get the last item of the list.\n"
},
{
"code": null,
"e": 2257,
"s": 1750,
"text": "# python program to print initials of a name \ndef fullname(str1):\n # split the string into a list \n lst = str1.split()\n newspace = \"\"\n # traverse in the list \n for i in range(len(lst)-1):\n str1 = lst[i]\n # adds the capital first character \n newspace += (str1[0].upper()+'.')\n # l[-1] gives last item of list l.\n newspace += lst[-1].title()\n return newspace \n# Driver code \nstr1=input(\"Enter Full Name ::>\")\nprint(\"Short Form of Name Is ::>\",fullname(str1)) "
},
{
"code": null,
"e": 2336,
"s": 2257,
"text": "Enter Full Name ::>pradip chandra sarkar\nShort Form of Name Is ::> P.C.Sarkar\n"
}
] |
Job Title Analysis in python and NLTK | by Adonis Gaitatzis | Towards Data Science
|
A job title indicates a lot about someone’s role and responsibilities. It says if they manage a team, if they control a budget, and their level of specialization.
Knowing this is useful when automating business development or client outreach. For example, a company that sells voice recognition software may want to send messages to:
CTOs and technical directors informing them of the price and benefits of using the voice recognition software.
Potential investors or advisors messages inviting them to see the company’s potential market size.
Founders and engineers instructing them how to use the software.
Training a software to classify job titles is a multi-text text classification problem. For this task, we can use the Python Natural Language Toolkit (NLTK) and Bayesian classification.
First, let’s conceptualize what a job title represents. Each job has a level of responsibility for some department.
Responsibilities include maintenance tasks such as cleaning the floor, management task such as team leadership, or strategy tasks such as deciding on budgets.
Departments include growth-based such as business development and marketing, compliance-based such as finance and legal, or execution-based such as product development and operations.
The responsibility and department are coded into many job titles, like this:
We want to classify each job description into one of these responsibilities and departments.
The first step is to get a list of job titles. There is a list of approximately 800 job titles available on CareerBuilder.
The job titles are paginated so the only way to get them all is to click on each page.
Once the job titles are imported, we can describe the responsibility and department of these jobs.
For this project, we will need the Natural Language Toolkit (NLTK). It contains text processing resources, machine learning tools, and more.
We will be using a Bayesian Multi-Class classifier and the Natural Language Toolkit to classify these job titles.
Import NLTK like this:
import reimport nltkfrom nltk.corpus import stopwordsimport pandas as pdstop_words = set(stopwords.words('english'))
Stop words are common words such as a, and, and the which have little significance to our job titles. NLTK provides a list of English stop words which we will filter out of each job title.
When we get job titles in the wild, for instance from LinkedIn or from Conferences, they sometimes include multiple job titles separated by commas, dashes, colons, or other characters. For simplicity, I’ll show how to extract the first job title:
def get_first_title(title): # keep "co-founder, co-ceo, etc" title = re.sub(r"[Cc]o[\-\ ]","", title) split_titles = re.split(r"\,|\-|\||\&|\:|\/|and", title) return split_titles[0].strip()
The Bayesian classifier will need a list of features — in this case, which words are in which job description. I also added the first and last words to the features because sometimes the first or last word has significance to the job title. For instance, Director of Marketing and Marketing Director are different roles.
def get_title_features(title): features = {} word_tokens = nltk.word_tokenize(title) filtered_words = [w for w in word_tokens if not w in stop_words] for word in filtered_words: features['contains({})'.format(word.lower())] = True if len(filtered_words) > 0: first_key = 'first({})'.format(filtered_words[0].lower()) last_key = 'last({})'.format(filtered_words[-1].lower()) features[first_key] = True features[last_key] = True return features
This will produce a list of words for a job title, including the first and last words, for example with the job title, Director of Global Operations:
{ "contains(director)": True, "contains(global)": True, "contains(operations)": True, "first(director)": True, "last(operations)": True}
Now we need to clean and prep the list of job titles, responsibilities, and departments for the classifier.
Presume we have our raw job title data formatted like this:
raw_job_titles = [ { "title": "Business Development", "responsibility": "Strategy", "department": "Business Development" }, { "title": "Inside Sales Consultant", "responsibility": "Execution", "department": "Sales" }, ...]
Next, we can train the Bayesian classifier on these datasets. We do this by catalog the features in each job title.
# Responsibilitiesresponsibilities_features = [ ( get_title_features(job_title["title"]), job_title["responsibility"] ) for job_title in raw_job_titles if job_title["responsibility"] is not None]# Departmentsdepartments_features = [ ( get_title_features(job_title["title"]), job_title["department"] ) for job_title in raw_job_titles if job_title["department"] is not None]
We can split the features so that we can train the classifier using some of the features and test the classifier with the rest.
# Responsibilitiesr_size = int(len(responsibilities_features) * 0.5)r_train_set = responsibilities_features[r_size:]r_test_set = responsibilities_features[:r_size]responsibilities_classifier = nltk.NaiveBayesClassifier.train( r_train_set)print("Responsibility classification accuracy: {}".format( nltk.classify.accuracy( responsibilities_classifier, r_test_set )))# Departmentsd_size = int(len(departments_features) * 0.5)d_train_set = departments_features[d_size:]d_test_set = departments_features[:d_size]departments_classifier = nltk.NaiveBayesClassifier.train( d_train_set)print("Department classification accuracy: {}".format( nltk.classify.accuracy( departments_classifier, d_test_set )))
The output should resemble this:
Responsibility classification accuracy: 0.80588235294117646Department classification accuracy: 0.80526315789473684
If you are happy with the results, you can classify new job titles.
title = "Director of Communications"responsibility = responsibilities_classifier.classify( get_title_features(title))department = departments_classifier.classify( get_title_features(title))print("Job title: '{}'".format(title))print("Responsibility: '{}'".format(responsibility))print("Department: '{}'".format(department))
Which results in the following output:
Job title: 'Director of Communications'Responsibility: 'Strategist'Department: 'Marketing'
One limitation is that the classifier will assign a department and responsibility to every job title, regardless of how ambiguous the job title is. This leads to the classification of job titles that should remain unclassified or reviewed by a person.
To overcome this, we can reveal the classifier’s confidence in its interpretation so that we can choose whether or not to accept it.
# Responsibilityresponsibility_probability = \ responsibilities_classifier.prob_classify( get_title_features(title) )responsibility_probability = 100 * responsibility_probability.prob( responsibility_probability.max())print("Responsibility confidence: {}%".format( round(responsibility_probability)))# Departmentdepartment_probability = \ departments_classifier.prob_classify( get_title_features(title) )department_probability = 100 * department_probability.prob( department_probability.max())print("Department confidence: {}%".format( round(department_probability)))
The result is something like this:
Responsibility confidence: 86%Department confidence: 79%
Source code can be found on Github. I look forward to hearing any feedback or questions.
|
[
{
"code": null,
"e": 335,
"s": 172,
"text": "A job title indicates a lot about someone’s role and responsibilities. It says if they manage a team, if they control a budget, and their level of specialization."
},
{
"code": null,
"e": 506,
"s": 335,
"text": "Knowing this is useful when automating business development or client outreach. For example, a company that sells voice recognition software may want to send messages to:"
},
{
"code": null,
"e": 617,
"s": 506,
"text": "CTOs and technical directors informing them of the price and benefits of using the voice recognition software."
},
{
"code": null,
"e": 716,
"s": 617,
"text": "Potential investors or advisors messages inviting them to see the company’s potential market size."
},
{
"code": null,
"e": 781,
"s": 716,
"text": "Founders and engineers instructing them how to use the software."
},
{
"code": null,
"e": 967,
"s": 781,
"text": "Training a software to classify job titles is a multi-text text classification problem. For this task, we can use the Python Natural Language Toolkit (NLTK) and Bayesian classification."
},
{
"code": null,
"e": 1083,
"s": 967,
"text": "First, let’s conceptualize what a job title represents. Each job has a level of responsibility for some department."
},
{
"code": null,
"e": 1242,
"s": 1083,
"text": "Responsibilities include maintenance tasks such as cleaning the floor, management task such as team leadership, or strategy tasks such as deciding on budgets."
},
{
"code": null,
"e": 1426,
"s": 1242,
"text": "Departments include growth-based such as business development and marketing, compliance-based such as finance and legal, or execution-based such as product development and operations."
},
{
"code": null,
"e": 1503,
"s": 1426,
"text": "The responsibility and department are coded into many job titles, like this:"
},
{
"code": null,
"e": 1596,
"s": 1503,
"text": "We want to classify each job description into one of these responsibilities and departments."
},
{
"code": null,
"e": 1719,
"s": 1596,
"text": "The first step is to get a list of job titles. There is a list of approximately 800 job titles available on CareerBuilder."
},
{
"code": null,
"e": 1806,
"s": 1719,
"text": "The job titles are paginated so the only way to get them all is to click on each page."
},
{
"code": null,
"e": 1905,
"s": 1806,
"text": "Once the job titles are imported, we can describe the responsibility and department of these jobs."
},
{
"code": null,
"e": 2046,
"s": 1905,
"text": "For this project, we will need the Natural Language Toolkit (NLTK). It contains text processing resources, machine learning tools, and more."
},
{
"code": null,
"e": 2160,
"s": 2046,
"text": "We will be using a Bayesian Multi-Class classifier and the Natural Language Toolkit to classify these job titles."
},
{
"code": null,
"e": 2183,
"s": 2160,
"text": "Import NLTK like this:"
},
{
"code": null,
"e": 2300,
"s": 2183,
"text": "import reimport nltkfrom nltk.corpus import stopwordsimport pandas as pdstop_words = set(stopwords.words('english'))"
},
{
"code": null,
"e": 2489,
"s": 2300,
"text": "Stop words are common words such as a, and, and the which have little significance to our job titles. NLTK provides a list of English stop words which we will filter out of each job title."
},
{
"code": null,
"e": 2736,
"s": 2489,
"text": "When we get job titles in the wild, for instance from LinkedIn or from Conferences, they sometimes include multiple job titles separated by commas, dashes, colons, or other characters. For simplicity, I’ll show how to extract the first job title:"
},
{
"code": null,
"e": 2938,
"s": 2736,
"text": "def get_first_title(title): # keep \"co-founder, co-ceo, etc\" title = re.sub(r\"[Cc]o[\\-\\ ]\",\"\", title) split_titles = re.split(r\"\\,|\\-|\\||\\&|\\:|\\/|and\", title) return split_titles[0].strip()"
},
{
"code": null,
"e": 3259,
"s": 2938,
"text": "The Bayesian classifier will need a list of features — in this case, which words are in which job description. I also added the first and last words to the features because sometimes the first or last word has significance to the job title. For instance, Director of Marketing and Marketing Director are different roles."
},
{
"code": null,
"e": 3756,
"s": 3259,
"text": "def get_title_features(title): features = {} word_tokens = nltk.word_tokenize(title) filtered_words = [w for w in word_tokens if not w in stop_words] for word in filtered_words: features['contains({})'.format(word.lower())] = True if len(filtered_words) > 0: first_key = 'first({})'.format(filtered_words[0].lower()) last_key = 'last({})'.format(filtered_words[-1].lower()) features[first_key] = True features[last_key] = True return features"
},
{
"code": null,
"e": 3906,
"s": 3756,
"text": "This will produce a list of words for a job title, including the first and last words, for example with the job title, Director of Global Operations:"
},
{
"code": null,
"e": 4058,
"s": 3906,
"text": "{ \"contains(director)\": True, \"contains(global)\": True, \"contains(operations)\": True, \"first(director)\": True, \"last(operations)\": True}"
},
{
"code": null,
"e": 4166,
"s": 4058,
"text": "Now we need to clean and prep the list of job titles, responsibilities, and departments for the classifier."
},
{
"code": null,
"e": 4226,
"s": 4166,
"text": "Presume we have our raw job title data formatted like this:"
},
{
"code": null,
"e": 4506,
"s": 4226,
"text": "raw_job_titles = [ { \"title\": \"Business Development\", \"responsibility\": \"Strategy\", \"department\": \"Business Development\" }, { \"title\": \"Inside Sales Consultant\", \"responsibility\": \"Execution\", \"department\": \"Sales\" }, ...]"
},
{
"code": null,
"e": 4622,
"s": 4506,
"text": "Next, we can train the Bayesian classifier on these datasets. We do this by catalog the features in each job title."
},
{
"code": null,
"e": 5051,
"s": 4622,
"text": "# Responsibilitiesresponsibilities_features = [ ( get_title_features(job_title[\"title\"]), job_title[\"responsibility\"] ) for job_title in raw_job_titles if job_title[\"responsibility\"] is not None]# Departmentsdepartments_features = [ ( get_title_features(job_title[\"title\"]), job_title[\"department\"] ) for job_title in raw_job_titles if job_title[\"department\"] is not None]"
},
{
"code": null,
"e": 5179,
"s": 5051,
"text": "We can split the features so that we can train the classifier using some of the features and test the classifier with the rest."
},
{
"code": null,
"e": 5920,
"s": 5179,
"text": "# Responsibilitiesr_size = int(len(responsibilities_features) * 0.5)r_train_set = responsibilities_features[r_size:]r_test_set = responsibilities_features[:r_size]responsibilities_classifier = nltk.NaiveBayesClassifier.train( r_train_set)print(\"Responsibility classification accuracy: {}\".format( nltk.classify.accuracy( responsibilities_classifier, r_test_set )))# Departmentsd_size = int(len(departments_features) * 0.5)d_train_set = departments_features[d_size:]d_test_set = departments_features[:d_size]departments_classifier = nltk.NaiveBayesClassifier.train( d_train_set)print(\"Department classification accuracy: {}\".format( nltk.classify.accuracy( departments_classifier, d_test_set )))"
},
{
"code": null,
"e": 5953,
"s": 5920,
"text": "The output should resemble this:"
},
{
"code": null,
"e": 6068,
"s": 5953,
"text": "Responsibility classification accuracy: 0.80588235294117646Department classification accuracy: 0.80526315789473684"
},
{
"code": null,
"e": 6136,
"s": 6068,
"text": "If you are happy with the results, you can classify new job titles."
},
{
"code": null,
"e": 6466,
"s": 6136,
"text": "title = \"Director of Communications\"responsibility = responsibilities_classifier.classify( get_title_features(title))department = departments_classifier.classify( get_title_features(title))print(\"Job title: '{}'\".format(title))print(\"Responsibility: '{}'\".format(responsibility))print(\"Department: '{}'\".format(department))"
},
{
"code": null,
"e": 6505,
"s": 6466,
"text": "Which results in the following output:"
},
{
"code": null,
"e": 6596,
"s": 6505,
"text": "Job title: 'Director of Communications'Responsibility: 'Strategist'Department: 'Marketing'"
},
{
"code": null,
"e": 6848,
"s": 6596,
"text": "One limitation is that the classifier will assign a department and responsibility to every job title, regardless of how ambiguous the job title is. This leads to the classification of job titles that should remain unclassified or reviewed by a person."
},
{
"code": null,
"e": 6981,
"s": 6848,
"text": "To overcome this, we can reveal the classifier’s confidence in its interpretation so that we can choose whether or not to accept it."
},
{
"code": null,
"e": 7587,
"s": 6981,
"text": "# Responsibilityresponsibility_probability = \\ responsibilities_classifier.prob_classify( get_title_features(title) )responsibility_probability = 100 * responsibility_probability.prob( responsibility_probability.max())print(\"Responsibility confidence: {}%\".format( round(responsibility_probability)))# Departmentdepartment_probability = \\ departments_classifier.prob_classify( get_title_features(title) )department_probability = 100 * department_probability.prob( department_probability.max())print(\"Department confidence: {}%\".format( round(department_probability)))"
},
{
"code": null,
"e": 7622,
"s": 7587,
"text": "The result is something like this:"
},
{
"code": null,
"e": 7679,
"s": 7622,
"text": "Responsibility confidence: 86%Department confidence: 79%"
}
] |
Angular Material 7 - Button
|
The <mat-button>, an Angular Directive, is used to create a button with material styling and animations.
In this chapter, we will showcase the configuration required to draw a button control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonModule,MatIconModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatButtonModule,MatIconModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified CSS file app.component.css.
.tp-button-row button,
.tp-button-row a {
margin-right: 8px;
}
Following is the content of the modified HTML host file app.component.html.
<div class = "example-button-row">
<button mat-button>Basic</button>
<button mat-raised-button>Raised</button>
<button mat-stroked-button>Stroked</button>
<button mat-flat-button>Flat</button>
<button mat-icon-button>
<mat-icon aria-label="Heart">favorite</mat-icon>
</button>
<button mat-fab>Fab</button>
<button mat-mini-fab>Mini</button>
<a mat-button routerLink = ".">Link</a>
</div>
Verify the result.
Here, we've created buttons using various variants of mat-buttons.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2860,
"s": 2755,
"text": "The <mat-button>, an Angular Directive, is used to create a button with material styling and animations."
},
{
"code": null,
"e": 2970,
"s": 2860,
"text": "In this chapter, we will showcase the configuration required to draw a button control using Angular Material."
},
{
"code": null,
"e": 3081,
"s": 2970,
"text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −"
},
{
"code": null,
"e": 3155,
"s": 3081,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3798,
"s": 3155,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatButtonModule,MatIconModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatButtonModule,MatIconModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3867,
"s": 3798,
"text": "Following is the content of the modified CSS file app.component.css."
},
{
"code": null,
"e": 3933,
"s": 3867,
"text": ".tp-button-row button,\n.tp-button-row a {\n margin-right: 8px;\n}"
},
{
"code": null,
"e": 4009,
"s": 3933,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 4430,
"s": 4009,
"text": "<div class = \"example-button-row\">\n <button mat-button>Basic</button>\n <button mat-raised-button>Raised</button>\n <button mat-stroked-button>Stroked</button>\n <button mat-flat-button>Flat</button>\n <button mat-icon-button>\n <mat-icon aria-label=\"Heart\">favorite</mat-icon>\n </button>\n <button mat-fab>Fab</button>\n <button mat-mini-fab>Mini</button>\n <a mat-button routerLink = \".\">Link</a>\n</div>"
},
{
"code": null,
"e": 4449,
"s": 4430,
"text": "Verify the result."
},
{
"code": null,
"e": 4516,
"s": 4449,
"text": "Here, we've created buttons using various variants of mat-buttons."
},
{
"code": null,
"e": 4551,
"s": 4516,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4565,
"s": 4551,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4600,
"s": 4565,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4614,
"s": 4600,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4649,
"s": 4614,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4669,
"s": 4649,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 4704,
"s": 4669,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4721,
"s": 4704,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4754,
"s": 4721,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4766,
"s": 4754,
"text": " Senol Atac"
},
{
"code": null,
"e": 4801,
"s": 4766,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4813,
"s": 4801,
"text": " Senol Atac"
},
{
"code": null,
"e": 4820,
"s": 4813,
"text": " Print"
},
{
"code": null,
"e": 4831,
"s": 4820,
"text": " Add Notes"
}
] |
Python | Percentage occurrence at index - GeeksforGeeks
|
27 Mar, 2019
Sometimes while dealing with statistics, we might come across this particular problem in which we require to find the percentage of occurrence of element at particular index in list of list. Let’s discuss certain ways in which this can be done.
Method #1 : Using loop + list comprehensionWe can perform this particular task using the loop for each list index, and for that we can compute the percentage occurrence of element using the list comprehension logic.
# Python3 code to demonstrate# index percentage calculation of element# using loop + list comprehension # initializing test listtest_list = [[3, 4, 5], [2, 4, 6], [3, 5, 4]] # printing original list print("The original list : " + str(test_list)) # using loop + list comprehension# index percentage calculation of elementres = []for i in range(len(test_list[1])): res.append(len([j[i] for j in test_list if j[i]== 4 ])/len(test_list)) # print resultprint("The percentage of 4 each index is : " + str(res))
The original list : [[3, 4, 5], [2, 4, 6], [3, 5, 4]]
The percentage of 4 each index is : [0.0, 0.6666666666666666, 0.3333333333333333]
Method #2 : Using zip() + count() + list comprehensionThis particular task can also be performed using the combination of above functions. The count and zip function do the task of percentage computation and grouping respectively.
# Python3 code to demonstrate# index percentage calculation of element# using zip() + count() + list comprehension # initializing test listtest_list = [[3, 4, 5], [2, 4, 6], [3, 5, 4]] # printing original list print("The original list : " + str(test_list)) # using zip() + count() + list comprehension# index percentage calculation of elementres = [sub.count(4)/len(sub) for sub in zip(*test_list)] # print resultprint("The percentage of 4 each index is : " + str(res))
The original list : [[3, 4, 5], [2, 4, 6], [3, 5, 4]]
The percentage of 4 each index is : [0.0, 0.6666666666666666, 0.3333333333333333]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24156,
"s": 24128,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 24401,
"s": 24156,
"text": "Sometimes while dealing with statistics, we might come across this particular problem in which we require to find the percentage of occurrence of element at particular index in list of list. Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 24617,
"s": 24401,
"text": "Method #1 : Using loop + list comprehensionWe can perform this particular task using the loop for each list index, and for that we can compute the percentage occurrence of element using the list comprehension logic."
},
{
"code": "# Python3 code to demonstrate# index percentage calculation of element# using loop + list comprehension # initializing test listtest_list = [[3, 4, 5], [2, 4, 6], [3, 5, 4]] # printing original list print(\"The original list : \" + str(test_list)) # using loop + list comprehension# index percentage calculation of elementres = []for i in range(len(test_list[1])): res.append(len([j[i] for j in test_list if j[i]== 4 ])/len(test_list)) # print resultprint(\"The percentage of 4 each index is : \" + str(res))",
"e": 25129,
"s": 24617,
"text": null
},
{
"code": null,
"e": 25266,
"s": 25129,
"text": "The original list : [[3, 4, 5], [2, 4, 6], [3, 5, 4]]\nThe percentage of 4 each index is : [0.0, 0.6666666666666666, 0.3333333333333333]\n"
},
{
"code": null,
"e": 25499,
"s": 25268,
"text": "Method #2 : Using zip() + count() + list comprehensionThis particular task can also be performed using the combination of above functions. The count and zip function do the task of percentage computation and grouping respectively."
},
{
"code": "# Python3 code to demonstrate# index percentage calculation of element# using zip() + count() + list comprehension # initializing test listtest_list = [[3, 4, 5], [2, 4, 6], [3, 5, 4]] # printing original list print(\"The original list : \" + str(test_list)) # using zip() + count() + list comprehension# index percentage calculation of elementres = [sub.count(4)/len(sub) for sub in zip(*test_list)] # print resultprint(\"The percentage of 4 each index is : \" + str(res))",
"e": 25973,
"s": 25499,
"text": null
},
{
"code": null,
"e": 26110,
"s": 25973,
"text": "The original list : [[3, 4, 5], [2, 4, 6], [3, 5, 4]]\nThe percentage of 4 each index is : [0.0, 0.6666666666666666, 0.3333333333333333]\n"
},
{
"code": null,
"e": 26131,
"s": 26110,
"text": "Python list-programs"
},
{
"code": null,
"e": 26138,
"s": 26131,
"text": "Python"
},
{
"code": null,
"e": 26154,
"s": 26138,
"text": "Python Programs"
},
{
"code": null,
"e": 26252,
"s": 26154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26270,
"s": 26252,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26305,
"s": 26270,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26327,
"s": 26305,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26359,
"s": 26327,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26389,
"s": 26359,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26432,
"s": 26389,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26478,
"s": 26432,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26517,
"s": 26478,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26555,
"s": 26517,
"text": "Python | Convert a list to dictionary"
}
] |
Creating a tkinter GUI layout using frames and grid
|
Tkinter is a well-known Python library for creating GUI-based applications. You can create a fully featured application with the help of widgets, functions, and modules that are already present in Tkinter library.
Sometimes, selecting the right GUI of the application becomes a daunting task for many of us. Tkinter comes with a set of inbuilt functions and extensions to create good-looking GUIs.
Generally, the Frame widget in Tkinter manages all the widgets in an application as a container. It inherits all the properties that the main window can contain. To design the layout of the widgets, we can use any of the geometry managers. Geometry Manager helps to create the layout of the widget and place them in a certain order. The Grid geometry manager places all the widgets in the form of X and Y coordinate system. We can provide the row and column property to place the widget anywhere in the application.
In this example, we will create the GUI of a Registration Form.
# Import the Required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
# Add a Frame widget
frame = Frame(win)
# Define a function to get the data and display a message
def on_key_up():
name = fname
frame.pack_forget()
win.configure(bg="green4")
Label(win, text="Hey " + fname.get() + " Welcome to TutorialsPoint",
font=('Segoe UI', 18, 'bold'),
background="white").pack(pady=30)
# Create a Label widget
Label(frame, text="Registration Form",
font=('Helvetica 16 bold'),
background="green3").grid(row=5, column=0, pady=30)
frame.pack()
# Add Field for First Value
Label(frame, text="First Name").grid(row=7, column=0, padx=5)
fname = Entry(frame)
fname.grid(row=10, column=0, padx=10)
# Add Field for Second Value
Label(frame, text="Family name").grid(row=12, column=0, padx=5)
sname = Entry(frame)
sname.grid(row=15, column=0, padx=10)
# Add Field for Email Address
Label(frame, text="Email address").grid(row=17, column=0, padx=5)
email = Entry(frame)
email.grid(row=20, column=0, padx=10)
# Add another field for accepting password value
Label(frame, text="Enter a Password").grid(row=22, column=0, padx=5)
password = Entry(frame, show="*")
password.grid(row=25, column=0, padx=10)
# Create a button
Button(frame, text="Register", command=on_key_up).grid(row=15,
column=1, padx=5)
win.mainloop()
Running the above code will display a registration form template and a button to register the information.
|
[
{
"code": null,
"e": 1276,
"s": 1062,
"text": "Tkinter is a well-known Python library for creating GUI-based applications. You can create a fully featured application with the help of widgets, functions, and modules that are already present in Tkinter library."
},
{
"code": null,
"e": 1460,
"s": 1276,
"text": "Sometimes, selecting the right GUI of the application becomes a daunting task for many of us. Tkinter comes with a set of inbuilt functions and extensions to create good-looking GUIs."
},
{
"code": null,
"e": 1976,
"s": 1460,
"text": "Generally, the Frame widget in Tkinter manages all the widgets in an application as a container. It inherits all the properties that the main window can contain. To design the layout of the widgets, we can use any of the geometry managers. Geometry Manager helps to create the layout of the widget and place them in a certain order. The Grid geometry manager places all the widgets in the form of X and Y coordinate system. We can provide the row and column property to place the widget anywhere in the application."
},
{
"code": null,
"e": 2040,
"s": 1976,
"text": "In this example, we will create the GUI of a Registration Form."
},
{
"code": null,
"e": 3474,
"s": 2040,
"text": "# Import the Required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Add a Frame widget\nframe = Frame(win)\n\n# Define a function to get the data and display a message\ndef on_key_up():\n name = fname\n frame.pack_forget()\n win.configure(bg=\"green4\")\n Label(win, text=\"Hey \" + fname.get() + \" Welcome to TutorialsPoint\",\n font=('Segoe UI', 18, 'bold'),\n background=\"white\").pack(pady=30)\n# Create a Label widget\n Label(frame, text=\"Registration Form\",\n font=('Helvetica 16 bold'),\nbackground=\"green3\").grid(row=5, column=0, pady=30)\nframe.pack()\n\n# Add Field for First Value\nLabel(frame, text=\"First Name\").grid(row=7, column=0, padx=5)\nfname = Entry(frame)\nfname.grid(row=10, column=0, padx=10)\n\n# Add Field for Second Value\nLabel(frame, text=\"Family name\").grid(row=12, column=0, padx=5)\nsname = Entry(frame)\nsname.grid(row=15, column=0, padx=10)\n\n# Add Field for Email Address\nLabel(frame, text=\"Email address\").grid(row=17, column=0, padx=5)\nemail = Entry(frame)\nemail.grid(row=20, column=0, padx=10)\n\n# Add another field for accepting password value\nLabel(frame, text=\"Enter a Password\").grid(row=22, column=0, padx=5)\npassword = Entry(frame, show=\"*\")\npassword.grid(row=25, column=0, padx=10)\n\n# Create a button\nButton(frame, text=\"Register\", command=on_key_up).grid(row=15,\ncolumn=1, padx=5)\n\nwin.mainloop()"
},
{
"code": null,
"e": 3581,
"s": 3474,
"text": "Running the above code will display a registration form template and a button to register the information."
}
] |
Program for Mobius Function | Set 2 - GeeksforGeeks
|
18 Mar, 2022
Given an integer N. The task is to find Mobius function of all numbers from 1 to N.Examples:
Input: N = 5 Output: 1 -1 -1 0 -1 Input: N = 10 Output: 1 -1 -1 0 -1 1 -1 0 0 1
Approach: The idea is to first find the least prime factor of all the numbers from 1 to N using Sieve of Eratosthenes then using these least prime factors the Mobius function can be calculated for all the numbers, depending on a number contains an odd number of distinct primes or even number of distinct primes.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;#define N 100005 int lpf[N]; // Function to calculate least// prime factor of each numbervoid least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (!lpf[i]) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (!lpf[j]) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nvoid Mobius(int n){ // To store the values of Mobius function int mobius[N]; for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } } for (int i = 1; i <= n; i++) cout << mobius[i] << " ";} // Driver codeint main(){ int n = 5; // Function to find least prime factor least_prime_factor(); // Function to find mobius function Mobius(n);}
// Java implementation of the approachimport java.util.*; class GFG{ static int N = 100005; static int []lpf = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (lpf[i] % 2 != 1) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (lpf[j] % 2 != 0) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nstatic void Mobius(int n){ // To store the values of Mobius function int []mobius = new int[N]; for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } } for (int i = 1; i <= n; i++) System.out.print(mobius[i] + " ");} // Driver codepublic static void main(String[] args){ int n = 5; Arrays.fill(lpf, -1); // Function to find least prime factor least_prime_factor(); // Function to find mobius function Mobius(n);}} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approachN = 100005 lpf = [0] * N; # Function to calculate least# prime factor of each numberdef least_prime_factor() : for i in range(2, N) : # If it is a prime number if (not lpf[i]) : for j in range(i, N, i) : # For all multiples which are not # visited yet. if (not lpf[j]) : lpf[j] = i; # Function to find the value of Mobius function# for all the numbers from 1 to ndef Mobius(n) : # To store the values of Mobius function mobius = [0] * N; for i in range(1, N) : # If number is one if (i == 1) : mobius[i] = 1; else : # If number has a squared prime factor if (lpf[i // lpf[i]] == lpf[i]) : mobius[i] = 0; # Multiply -1 with the previous number else : mobius[i] = -1 * mobius[i // lpf[i]]; for i in range(1, n + 1) : print(mobius[i], end = " "); # Driver codeif __name__ == "__main__" : n = 5; # Function to find least prime factor least_prime_factor(); # Function to find mobius function Mobius(n); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{static int N = 100005; static int []lpf = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (lpf[i] % 2 != 1) for (int j = i; j < N; j += i) // For all multiples which // are not visited yet. if (lpf[j] % 2 != 0) lpf[j] = i;} // Function to find the value of// Mobius function for all the numbers// from 1 to nstatic void Mobius(int n){ // To store the values of // Mobius function int []mobius = new int[N]; for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the // previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } } for (int i = 1; i <= n; i++) Console.Write(mobius[i] + " ");} // Driver codestatic public void Main (){ int n = 5; Array.Fill(lpf, -1); // Function to find least prime factor least_prime_factor(); // Function to find mobius function Mobius(n);}} // This code is contributed by ajit.
<script> // Javascript implementation of the approach const N = 100005; let lpf = new Array(N); // Function to calculate least// prime factor of each numberfunction least_prime_factor(){ for (let i = 2; i < N; i++) // If it is a prime number if (!lpf[i]) for (let j = i; j < N; j += i) // For all multiples which are not // visited yet. if (!lpf[j]) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nfunction Mobius(n){ // To store the values of Mobius function let mobius = new Array(N); for (let i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[parseInt(i / lpf[i])] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[parseInt(i / lpf[i])]; } } for (let i = 1; i <= n; i++) document.write(mobius[i] + " ");} // Driver code let n = 5; // Function to find least prime factor least_prime_factor(); // Function to find mobius function Mobius(n); </script>
1 -1 -1 0 -1
Time Complexity: O(N2)
Auxiliary Space: O(N)
ankthon
princiraj1992
jit_t
souravmahato348
subhamkumarm348
number-theory
prime-factor
sieve
Mathematical
number-theory
Mathematical
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
Program for Decimal to Binary Conversion
Algorithm to solve Rubik's Cube
|
[
{
"code": null,
"e": 24604,
"s": 24576,
"text": "\n18 Mar, 2022"
},
{
"code": null,
"e": 24699,
"s": 24604,
"text": "Given an integer N. The task is to find Mobius function of all numbers from 1 to N.Examples: "
},
{
"code": null,
"e": 24781,
"s": 24699,
"text": "Input: N = 5 Output: 1 -1 -1 0 -1 Input: N = 10 Output: 1 -1 -1 0 -1 1 -1 0 0 1 "
},
{
"code": null,
"e": 25148,
"s": 24783,
"text": "Approach: The idea is to first find the least prime factor of all the numbers from 1 to N using Sieve of Eratosthenes then using these least prime factors the Mobius function can be calculated for all the numbers, depending on a number contains an odd number of distinct primes or even number of distinct primes.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25152,
"s": 25148,
"text": "C++"
},
{
"code": null,
"e": 25157,
"s": 25152,
"text": "Java"
},
{
"code": null,
"e": 25165,
"s": 25157,
"text": "Python3"
},
{
"code": null,
"e": 25168,
"s": 25165,
"text": "C#"
},
{
"code": null,
"e": 25179,
"s": 25168,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 100005 int lpf[N]; // Function to calculate least// prime factor of each numbervoid least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (!lpf[i]) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (!lpf[j]) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nvoid Mobius(int n){ // To store the values of Mobius function int mobius[N]; for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } } for (int i = 1; i <= n; i++) cout << mobius[i] << \" \";} // Driver codeint main(){ int n = 5; // Function to find least prime factor least_prime_factor(); // Function to find mobius function Mobius(n);}",
"e": 26421,
"s": 25179,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static int N = 100005; static int []lpf = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (lpf[i] % 2 != 1) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (lpf[j] % 2 != 0) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nstatic void Mobius(int n){ // To store the values of Mobius function int []mobius = new int[N]; for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } } for (int i = 1; i <= n; i++) System.out.print(mobius[i] + \" \");} // Driver codepublic static void main(String[] args){ int n = 5; Arrays.fill(lpf, -1); // Function to find least prime factor least_prime_factor(); // Function to find mobius function Mobius(n);}} // This code is contributed by PrinciRaj1992",
"e": 27840,
"s": 26421,
"text": null
},
{
"code": "# Python3 implementation of the approachN = 100005 lpf = [0] * N; # Function to calculate least# prime factor of each numberdef least_prime_factor() : for i in range(2, N) : # If it is a prime number if (not lpf[i]) : for j in range(i, N, i) : # For all multiples which are not # visited yet. if (not lpf[j]) : lpf[j] = i; # Function to find the value of Mobius function# for all the numbers from 1 to ndef Mobius(n) : # To store the values of Mobius function mobius = [0] * N; for i in range(1, N) : # If number is one if (i == 1) : mobius[i] = 1; else : # If number has a squared prime factor if (lpf[i // lpf[i]] == lpf[i]) : mobius[i] = 0; # Multiply -1 with the previous number else : mobius[i] = -1 * mobius[i // lpf[i]]; for i in range(1, n + 1) : print(mobius[i], end = \" \"); # Driver codeif __name__ == \"__main__\" : n = 5; # Function to find least prime factor least_prime_factor(); # Function to find mobius function Mobius(n); # This code is contributed by AnkitRai01",
"e": 29064,
"s": 27840,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{static int N = 100005; static int []lpf = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (lpf[i] % 2 != 1) for (int j = i; j < N; j += i) // For all multiples which // are not visited yet. if (lpf[j] % 2 != 0) lpf[j] = i;} // Function to find the value of// Mobius function for all the numbers// from 1 to nstatic void Mobius(int n){ // To store the values of // Mobius function int []mobius = new int[N]; for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the // previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } } for (int i = 1; i <= n; i++) Console.Write(mobius[i] + \" \");} // Driver codestatic public void Main (){ int n = 5; Array.Fill(lpf, -1); // Function to find least prime factor least_prime_factor(); // Function to find mobius function Mobius(n);}} // This code is contributed by ajit.",
"e": 30476,
"s": 29064,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach const N = 100005; let lpf = new Array(N); // Function to calculate least// prime factor of each numberfunction least_prime_factor(){ for (let i = 2; i < N; i++) // If it is a prime number if (!lpf[i]) for (let j = i; j < N; j += i) // For all multiples which are not // visited yet. if (!lpf[j]) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nfunction Mobius(n){ // To store the values of Mobius function let mobius = new Array(N); for (let i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[parseInt(i / lpf[i])] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[parseInt(i / lpf[i])]; } } for (let i = 1; i <= n; i++) document.write(mobius[i] + \" \");} // Driver code let n = 5; // Function to find least prime factor least_prime_factor(); // Function to find mobius function Mobius(n); </script>",
"e": 31745,
"s": 30476,
"text": null
},
{
"code": null,
"e": 31758,
"s": 31745,
"text": "1 -1 -1 0 -1"
},
{
"code": null,
"e": 31783,
"s": 31760,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 31805,
"s": 31783,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 31813,
"s": 31805,
"text": "ankthon"
},
{
"code": null,
"e": 31827,
"s": 31813,
"text": "princiraj1992"
},
{
"code": null,
"e": 31833,
"s": 31827,
"text": "jit_t"
},
{
"code": null,
"e": 31849,
"s": 31833,
"text": "souravmahato348"
},
{
"code": null,
"e": 31865,
"s": 31849,
"text": "subhamkumarm348"
},
{
"code": null,
"e": 31879,
"s": 31865,
"text": "number-theory"
},
{
"code": null,
"e": 31892,
"s": 31879,
"text": "prime-factor"
},
{
"code": null,
"e": 31898,
"s": 31892,
"text": "sieve"
},
{
"code": null,
"e": 31911,
"s": 31898,
"text": "Mathematical"
},
{
"code": null,
"e": 31925,
"s": 31911,
"text": "number-theory"
},
{
"code": null,
"e": 31938,
"s": 31925,
"text": "Mathematical"
},
{
"code": null,
"e": 31944,
"s": 31938,
"text": "sieve"
},
{
"code": null,
"e": 32042,
"s": 31944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32051,
"s": 32042,
"text": "Comments"
},
{
"code": null,
"e": 32064,
"s": 32051,
"text": "Old Comments"
},
{
"code": null,
"e": 32106,
"s": 32064,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 32130,
"s": 32106,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32173,
"s": 32130,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32187,
"s": 32173,
"text": "Prime Numbers"
},
{
"code": null,
"e": 32236,
"s": 32187,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32270,
"s": 32236,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 32291,
"s": 32270,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 32333,
"s": 32291,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 32374,
"s": 32333,
"text": "Program for Decimal to Binary Conversion"
}
] |
Maximize sum(arr[i]*i) of an Array | Practice | GeeksforGeeks
|
Given an array A of N integers. Your task is to write a program to find the maximum value of ∑arr[i]*i, where i = 0, 1, 2,...., n – 1.
You are allowed to rearrange the elements of the array.
Note: Since output could be large, hence module 109+7 and then print answer.
Example 1:
Input : Arr[] = {5, 3, 2, 4, 1}
Output : 40
Explanation:
If we arrange the array as 1 2 3 4 5 then
we can see that the minimum index will multiply
with minimum number and maximum index will
multiply with maximum number.
So 1*0+2*1+3*2+4*3+5*4=0+2+6+12+20 = 40 mod(109+7) = 40
Example 2:
Input : Arr[] = {1, 2, 3}
Output : 8
Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function Maximize() that takes an array (arr), sizeOfArray (n), and return the maximum value of an array. The driver code takes care of the printing.
Expected Time Complexity: O(nlog(n)).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 107
1 ≤ Ai ≤ N
+1
harshscode5 days ago
long long int sum=0;
long long int prod=1;
sort(a,a+n);
long long int m=pow(10,9)+7;
for(long long int i=0;i<n;i++)
{
prod=(a[i]*i);
sum+=prod;
}
return sum%m;
0
tanashah1 week ago
+1
mestryruturaj2 weeks ago
Java
class Solution{
long Maximize(int arr[], int n)
{
long res = 0;
long mod = 1000000007;
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
res = (res + (arr[i] % mod * i % mod)) % mod;
}
return res;
}
}
+1
sarthakgupta102 weeks ago
//Execution time=0.65
int Maximize(int a[],int n)
{
// Complete the function
sort(a,a+n);
long long int prod=1;
long long int sum=0;
long long int mod = pow(10,9)+7;
for(long long int i=0;i<n;i++)
{
prod=(a[i]*i);
sum+=prod;
}
//int ans=sum%1000000007;
return sum%mod;
}
0
zerefkhan2 weeks ago
C++ solution
Total Time Taken : 0.65/2.19
int Maximize(int a[],int n)
{
sort(a,a+n); // First sort the array - increasing order
int sum = 0;
for(long long int i = 0; i < n; i++){
sum = (sum+a[i]*i)%1000000007;
}
return sum%1000000007;
}
0
951991g
This comment was deleted.
0
somawatpravin023 weeks ago
def Maximize(self, a, n): # Complete the function sum=0 a.sort() mod=(10**9)+7 for i in range(n): sum+= a[i]*i return sum%mod
0
rahulstm081 month ago
//i got stuck at 600 test cases.why?
sort(a,a+n); int sum=0; for(int i=0;i<n;i++) { sum+=a[i]*i; } return sum;
0
ajay7yadav951 month ago
//why its not pass after 600 test cases.. this will fine in VS
Maximize(arr,n){ //code here let sum = 0; arr.sort((x,y)=>x-y); for(let i=0; i<arr.length;i++){ sum += arr[i]*i; } return sum; }
0
atif836141 month ago
JAVA SOLUTION :
class Solution{
int Maximize(int arr[], int n)
{
long sum=0;
int mod = (int)(Math.pow(10,3)+7);
for(int i=0;i<n;i++){
sum =sum+(long)arr[i]*i;
}
return (int)(sum%mod);
}
}
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": 506,
"s": 238,
"text": "Given an array A of N integers. Your task is to write a program to find the maximum value of ∑arr[i]*i, where i = 0, 1, 2,...., n – 1.\nYou are allowed to rearrange the elements of the array.\nNote: Since output could be large, hence module 109+7 and then print answer."
},
{
"code": null,
"e": 519,
"s": 508,
"text": "Example 1:"
},
{
"code": null,
"e": 800,
"s": 519,
"text": "Input : Arr[] = {5, 3, 2, 4, 1}\nOutput : 40\nExplanation:\nIf we arrange the array as 1 2 3 4 5 then \nwe can see that the minimum index will multiply\nwith minimum number and maximum index will \nmultiply with maximum number. \nSo 1*0+2*1+3*2+4*3+5*4=0+2+6+12+20 = 40 mod(109+7) = 40\n\n"
},
{
"code": null,
"e": 811,
"s": 800,
"text": "Example 2:"
},
{
"code": null,
"e": 850,
"s": 811,
"text": "Input : Arr[] = {1, 2, 3}\nOutput : 8\n\n"
},
{
"code": null,
"e": 1125,
"s": 850,
"text": "\nYour Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function Maximize() that takes an array (arr), sizeOfArray (n), and return the maximum value of an array. The driver code takes care of the printing."
},
{
"code": null,
"e": 1195,
"s": 1125,
"text": "Expected Time Complexity: O(nlog(n)).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1231,
"s": 1195,
"text": "Constraints:\n1 ≤ N ≤ 107\n1 ≤ Ai ≤ N"
},
{
"code": null,
"e": 1234,
"s": 1231,
"text": "+1"
},
{
"code": null,
"e": 1255,
"s": 1234,
"text": "harshscode5 days ago"
},
{
"code": null,
"e": 1525,
"s": 1255,
"text": "\n long long int sum=0;\n long long int prod=1;\n sort(a,a+n);\n long long int m=pow(10,9)+7;\n for(long long int i=0;i<n;i++)\n {\n prod=(a[i]*i);\n sum+=prod;\n \n }\n \n return sum%m;"
},
{
"code": null,
"e": 1527,
"s": 1525,
"text": "0"
},
{
"code": null,
"e": 1546,
"s": 1527,
"text": "tanashah1 week ago"
},
{
"code": null,
"e": 1549,
"s": 1546,
"text": "+1"
},
{
"code": null,
"e": 1574,
"s": 1549,
"text": "mestryruturaj2 weeks ago"
},
{
"code": null,
"e": 1579,
"s": 1574,
"text": "Java"
},
{
"code": null,
"e": 1877,
"s": 1579,
"text": "class Solution{\n \n long Maximize(int arr[], int n)\n {\n long res = 0;\n long mod = 1000000007;\n Arrays.sort(arr);\n \n for (int i = 0; i < n; i++) {\n res = (res + (arr[i] % mod * i % mod)) % mod;\n }\n \n return res;\n } \n}"
},
{
"code": null,
"e": 1880,
"s": 1877,
"text": "+1"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "sarthakgupta102 weeks ago"
},
{
"code": null,
"e": 2314,
"s": 1906,
"text": "//Execution time=0.65\nint Maximize(int a[],int n)\n {\n // Complete the function\n sort(a,a+n);\n long long int prod=1;\n long long int sum=0;\n long long int mod = pow(10,9)+7;\n\n for(long long int i=0;i<n;i++)\n {\n prod=(a[i]*i);\n sum+=prod;\n \n \n }\n //int ans=sum%1000000007;\n return sum%mod;\n }"
},
{
"code": null,
"e": 2316,
"s": 2314,
"text": "0"
},
{
"code": null,
"e": 2337,
"s": 2316,
"text": "zerefkhan2 weeks ago"
},
{
"code": null,
"e": 2350,
"s": 2337,
"text": "C++ solution"
},
{
"code": null,
"e": 2385,
"s": 2350,
"text": "Total Time Taken : 0.65/2.19"
},
{
"code": null,
"e": 2654,
"s": 2385,
"text": " int Maximize(int a[],int n)\n {\n sort(a,a+n); // First sort the array - increasing order\n \n int sum = 0;\n for(long long int i = 0; i < n; i++){\n sum = (sum+a[i]*i)%1000000007;\n }\n return sum%1000000007;\n }\n"
},
{
"code": null,
"e": 2656,
"s": 2654,
"text": "0"
},
{
"code": null,
"e": 2664,
"s": 2656,
"text": "951991g"
},
{
"code": null,
"e": 2690,
"s": 2664,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2692,
"s": 2690,
"text": "0"
},
{
"code": null,
"e": 2719,
"s": 2692,
"text": "somawatpravin023 weeks ago"
},
{
"code": null,
"e": 2903,
"s": 2719,
"text": " def Maximize(self, a, n): # Complete the function sum=0 a.sort() mod=(10**9)+7 for i in range(n): sum+= a[i]*i return sum%mod "
},
{
"code": null,
"e": 2905,
"s": 2903,
"text": "0"
},
{
"code": null,
"e": 2927,
"s": 2905,
"text": "rahulstm081 month ago"
},
{
"code": null,
"e": 2964,
"s": 2927,
"text": "//i got stuck at 600 test cases.why?"
},
{
"code": null,
"e": 3084,
"s": 2964,
"text": " sort(a,a+n); int sum=0; for(int i=0;i<n;i++) { sum+=a[i]*i; } return sum;"
},
{
"code": null,
"e": 3086,
"s": 3084,
"text": "0"
},
{
"code": null,
"e": 3110,
"s": 3086,
"text": "ajay7yadav951 month ago"
},
{
"code": null,
"e": 3173,
"s": 3110,
"text": "//why its not pass after 600 test cases.. this will fine in VS"
},
{
"code": null,
"e": 3346,
"s": 3175,
"text": " Maximize(arr,n){ //code here let sum = 0; arr.sort((x,y)=>x-y); for(let i=0; i<arr.length;i++){ sum += arr[i]*i; } return sum; }"
},
{
"code": null,
"e": 3350,
"s": 3348,
"text": "0"
},
{
"code": null,
"e": 3371,
"s": 3350,
"text": "atif836141 month ago"
},
{
"code": null,
"e": 3387,
"s": 3371,
"text": "JAVA SOLUTION :"
},
{
"code": null,
"e": 3604,
"s": 3387,
"text": "class Solution{\n \n int Maximize(int arr[], int n)\n {\n long sum=0;\n int mod = (int)(Math.pow(10,3)+7);\n for(int i=0;i<n;i++){\n sum =sum+(long)arr[i]*i;\n }\n return (int)(sum%mod);\n }\n }"
},
{
"code": null,
"e": 3750,
"s": 3604,
"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": 3786,
"s": 3750,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3796,
"s": 3786,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3806,
"s": 3796,
"text": "\nContest\n"
},
{
"code": null,
"e": 3869,
"s": 3806,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4017,
"s": 3869,
"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": 4225,
"s": 4017,
"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": 4331,
"s": 4225,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Scaling Analytical Insights with Python (Part 2) | by Kevin Boller | Towards Data Science
|
In this Part 2 post (Part 1 can be found here), I’ll combine several resources which I believe are remarkably useful, and this post will tie together a few key pieces of analyses for better understanding a direct-to-consumer, subscription / SaaS customer base. In order to meld all of this together, I’ll also use one of my favorite data analytics / data science tools, Mode Analytics. At the end, what I hope you’ll find both helpful and cool is an open source Mode Analytics report, which can be found here; this is a slimmed down version of the type of report that I would produce in my former role as the head of the data warehouse and data analytics at FloSports, and all of the code and visualizations are available to be cloned into your own Mode report and re-purposed for similar data sets (assuming you create an account, which is free for public data sets). If you do not have a Mode Analytics account and are not yet convinced to sign up, you should still be able to access the Python notebook and you’ll also see all underlying SQL queries at this link.
To quickly summarize what this post will cover (note that each part will use the same e-commerce user data set which Greg Reda referenced in his original post, found here):
Recreate Part 1’s subscriber cohort and retention analysis, this time using Mode’s SQL + PythonCreate a projected LTV analysis in SQL using exponential decay, leveraging an excellent blog post by Ryan Iyengar, which can be found hereDevelop an RFM (Recency, Frequency, Monetary Value) analysis, one method e-commerce sites use to segment and better understand user / subscriber buying behaviorsShow how this all ties together using a brief write up and visualizations from both SQL and Python in an overall, open source Mode Report
Recreate Part 1’s subscriber cohort and retention analysis, this time using Mode’s SQL + Python
Create a projected LTV analysis in SQL using exponential decay, leveraging an excellent blog post by Ryan Iyengar, which can be found here
Develop an RFM (Recency, Frequency, Monetary Value) analysis, one method e-commerce sites use to segment and better understand user / subscriber buying behaviors
Show how this all ties together using a brief write up and visualizations from both SQL and Python in an overall, open source Mode Report
Again, the Mode Analytics report is available here — you do not need to create a Mode Analytics account in order to see the report, however, cloning it requires a free account. The original data set can be found at the link provided before, and everything else (SQL, Python code, how to build the charts and Python visualizations) is all available within the linked report.
To start with, I took the relay-foods data set and added it as a public file on Mode — here are Mode’s instructions on how to do that (I also added an all_time dataset, more on that in the projected LTV portion). The Python code in this portion of the post can be found in the Notebook section of the report here; this is identical to the code utilized in my prior post — the difference is that a dataframe created from an SQL query is utilized within a Mode Python notebook. Additionally, the SQL code provided below shows a minor data enrichment step that I took on this dataset, where I categorize the first payment for a user as ‘Initial’ and any subsequent payments as ‘Repeat’. This is a fairly minor but quick example of the type of business logic that you can apply to data sources, generally using aggregate fact tables as I’ve mentioned in the past.
with payment_enrichment as ( select order_id , order_date , user_id , total_charges , common_id , pup_id , pickup_date , date_trunc('month', order_date) as order_month , row_number() over (partition by user_id order by order_date) as payment_number from kdboller.relay_foods_v1 ) select pe.* , case when payment_number = 1 then 'Initial' else 'Repeat' end as payment_type from payment_enrichment as pe
As the next step in this analysis, I will build a projected LTV analysis, referencing another previously mentioned and helpful resource which I found online — Ryan Iyengar posted this forecasting LTV post on Medium a little bit over a year ago, found here. If you’ve ever conducted an LTV analysis in Excel, you know that this can be rather time consuming and these models can become extremely large and much less dynamic than one would prefer. You would think that there has to be a better way to calculate a single value which is rather critical to understanding the health of a subscription business. Fortunately, there are at least a few better, highly repeatable ways to do this. Furthermore, evaluating different start/end date ranges for cohorts to include, e.g., to normalize for particularly strong “early adopter” cohorts, is a significant advantage of conducting this type of analysis in SQL and / or Python.
With all of this said, Ryan’s post definitely requires a fairly thorough understanding of SQL, particularly given the significant use of common table expressions (CTEs). Given the length of the resulting query, I’ve not pasted it directly into this post but you can find several build ups to the final query within the Mode Report. If you have specific questions on the background or rationale for this piece of my post, I would refer you to his rather insightful and informative explanations. For purposes of my article and report, I’ve shown how to create the needed data return from the original data set we’re using, provide some observational takeaways from our dataset below and also show a few key charts in the LTV section that Mode easily allows me to add to my overall report.
LTV Section — summary of the queries
The SQL queries related to LTV, which piggyback off of Ryan’s extremely helpful work, start with the numbering of 2–8 within the report. Within Mode, I try to order my queries using this system in order to track the natural progression of the queries written within a project — a nice feature request would be to have some type of a folder-ing system in order to organize these into payment, LTV, and RFM query sections. Query #2 manipulates the dataset in order to pull back a return that is consistent with the dataset which Ryan used in his post — as a result, this hopefully make this much more straightforward to follow. I also built out the query breaks to mimic where Ryan pauses during his blog post, so that it is easier to follow between his post and the Mode report that I created.
Within queries 4–6, you’ll see that while performing this I detected an anomalous situation within one of the cohorts (see screenshot below this paragraph). In the 2009/04/01 cohort, in the three latest months the cohort’s revenue share actually dramatically increased; while reactivations, users who leave a cohort and then later return, are not uncommon, this significantly skewed the forecasted revenue and therefore LTV for this particular cohort. As a result, rather than projecting a decay in revenue, the model was forecasting a greater than 20% month over month increase (for the whole forecast). While there are probably a few preferred ways to normalize this, in the interest of time I decided to just exclude this cohort from the overall analysis — I would say that something similar to this happens in almost every analysis, and it’s obviously critical to vet the data and determine how to adjust as needed. The adjustment decisions will somewhat vary given a company’s industry, future prospects, and maturity.
Queries 7 and 8 complete the query with the final expected return, one which shows the projected LTV for each cohort and one which shows the overall forecasted LTV when taking into account all cohorts’ forecasted projections and initial users. As you can see from the below screen scrape copied from the Mode Report output, the overall LTV is ~$315. In addition to that, we see that the initial cohort, most likely the “early adopters”, have a much higher LTV than those seen in subsequent months — with the caveat that we only have 12 monthly cohorts to evaluate and this is a rarely new company given this example, next steps could include further segmenting users and finding each LTV, as well as potentially normalizing overall LTV by excluding the “early adopter” contribution from this analysis. It’s also worth noting that the LTV is much lower with the higher volume recent cohorts, and we would want to understand if we can more effectively grow our user base while ideally growing, or at minimum maintaining, our LTV over time. Please note that when finalizing an analysis such as this, you should also calculate a gross margin, or preferably a contribution margin, to reflect the true underlying economics and LTV for each subscriber.
RFM Analyses
In this last section, I’ve included a Recency, Frequency, Monetary Value (RFM) analysis. While in the course of reviewing effective ways to segment subscribers and after discovering this methodology, I then found this helpful notebook on Joao Correia’s GitHub. Here’s a very brief rundown of RFM.
Recency: how recently from an evaluated date, e.g., today, a user / subscriber has purchased from a site.
Frequency: the number of times that a user / subscriber has purchased on a particular site in their entire lifetime as a customer.
Monetary Value: the dollar amount that the user / subscriber has paid in total from all of their purchases during their entire lifetime as a customer.
While there are a few ways to complete the RFM analysis, including via SQL, part of my intent here is to show how the useful work of others can be repurposed with a rather straightforward initial dataset. Within the Python notebook, RFM Analyses section, you will see that I’ve largely followed Joao’s notebook. As in his notebook’s conclusion, I show below the the top ten customers in the RFMClass 111 — this represents the users who are in the top quartile for all three RFM metrics; these users have paid rather recently, and have also paid more times and at a higher monetary value than 75% of the site’s other users. As a result, these users are prime for qualitative surveys requesting feedback on what they love and what could be better, and you can also study their site behavior to understand what they may be doing and discovering which is different than other visitors, among several different evaluations you can take on.
Utilizing Plotly within the Mode report, I then added three visualizations which help me to better understand the data and are also meant to anticipate potential questions from business stakeholders. The first shows the distribution of users within each RFMClass. On a positive note, 81 users are in the 111 class, but 75 are in 344 and 65 are in 444 — these are users who have not paid in a while, and who have also paid far fewer times and at a much lower monetary value than the median value for all users. We would want to see if we could resurrect these users or if there’s something that happened which caused them to (almost) never return to our site.
Lastly, I would want to know how each RFMClass indexes in terms of cohort groups — are earlier cohorts the ones that are primarily in the 111 class? If so, that would probably be a cause for concern. In order to accomplish this part, you will find a ‘Merge Data to show RFM Class by Cohorts’ section within the Python notebook, where I take a subset of the initial payments dataframe and merge this with the rfmSegmentation dataframe that was created. If you need a primer on merging dataframes in Python, similar to joining in SQL, I will refer you to another Greg Reda post here.
In reviewing the two charts (below), the first with total users by cohort and the second with RFM Class 111 users by cohort, we see that the largest contributors to the RFM Class 111 are from November 2009 and January 2010. However, when reviewing the first chart with total users per cohort, we see that November 2009 was a particularly large cohort, and on a relative basis is not as strong of a contributor to the top RFM class. An even better output would calculate, for each cohort, what percent RFMClass 111 users comprised of each monthly cohort; but I’ll leave that for another time / potentially a follow-up post.
And this concludes a post with analyses that I really enjoyed putting together. Hopefully this conveys the value of stepping out of Excel, leveraging the public contributions of insightful people and the benefits of tools such as SQL and Python.
Some quick notes on the benefits of working with Mode (also, here’s a post from Mode’s blog regarding their take on getting out of Excel and into SQL and Python):
Charts can be easily created either in SQL (built-in chart functionality) or in Python; these charts are then tied to your data’s queries and will be updated automatically
Reports are highly reproducible and can be cloned if you want to preserve a previous one, e.g., quarterly business reviews
Mitigates need to create a dataset and read out as a CSV into a Jupyter notebook; you can read each query directly into Mode’s Python notebook as a dataframe
I say all of this with the caveat that not all Python libraries are available within Mode, although quite a few are, and computing power is an area in which Mode is constantly looking to improve
Starting from a rather basic user data set and leveraging the full functionality of Mode Analytics, we were able to complete the following:
Contribute two public datasets onto Mode’s platform
Group the users into monthly cohorts via SQL and Python
Build retention curves / retention heatmaps for these monthly cohorts in Python
Calculate a weighted average retention curve for the cohorts in Python
Project LTV for the entire company and for each cohort using SQL
Conduct an RFM analysis and understand the distribution for each class and the contribution by Monthly cohort in Python — this is completed by merging two dataframes (one created from a combined SQL and Python effort and one created directly in Python) within Mode’s Python notebook
Finally, we created a (hopefully) intuitive, comprehensive and open-source report
This report is rather extensible as far as adding in additional analyses and can also be easily updated as new monthly data rolls in
Hopefully you found this post as helpful as I’ve found Mode to be, as well as the referenced posts that were leveraged to produce this Mode report, and please let me know if you have any questions or thoughts in the comments section.
|
[
{
"code": null,
"e": 1239,
"s": 172,
"text": "In this Part 2 post (Part 1 can be found here), I’ll combine several resources which I believe are remarkably useful, and this post will tie together a few key pieces of analyses for better understanding a direct-to-consumer, subscription / SaaS customer base. In order to meld all of this together, I’ll also use one of my favorite data analytics / data science tools, Mode Analytics. At the end, what I hope you’ll find both helpful and cool is an open source Mode Analytics report, which can be found here; this is a slimmed down version of the type of report that I would produce in my former role as the head of the data warehouse and data analytics at FloSports, and all of the code and visualizations are available to be cloned into your own Mode report and re-purposed for similar data sets (assuming you create an account, which is free for public data sets). If you do not have a Mode Analytics account and are not yet convinced to sign up, you should still be able to access the Python notebook and you’ll also see all underlying SQL queries at this link."
},
{
"code": null,
"e": 1412,
"s": 1239,
"text": "To quickly summarize what this post will cover (note that each part will use the same e-commerce user data set which Greg Reda referenced in his original post, found here):"
},
{
"code": null,
"e": 1944,
"s": 1412,
"text": "Recreate Part 1’s subscriber cohort and retention analysis, this time using Mode’s SQL + PythonCreate a projected LTV analysis in SQL using exponential decay, leveraging an excellent blog post by Ryan Iyengar, which can be found hereDevelop an RFM (Recency, Frequency, Monetary Value) analysis, one method e-commerce sites use to segment and better understand user / subscriber buying behaviorsShow how this all ties together using a brief write up and visualizations from both SQL and Python in an overall, open source Mode Report"
},
{
"code": null,
"e": 2040,
"s": 1944,
"text": "Recreate Part 1’s subscriber cohort and retention analysis, this time using Mode’s SQL + Python"
},
{
"code": null,
"e": 2179,
"s": 2040,
"text": "Create a projected LTV analysis in SQL using exponential decay, leveraging an excellent blog post by Ryan Iyengar, which can be found here"
},
{
"code": null,
"e": 2341,
"s": 2179,
"text": "Develop an RFM (Recency, Frequency, Monetary Value) analysis, one method e-commerce sites use to segment and better understand user / subscriber buying behaviors"
},
{
"code": null,
"e": 2479,
"s": 2341,
"text": "Show how this all ties together using a brief write up and visualizations from both SQL and Python in an overall, open source Mode Report"
},
{
"code": null,
"e": 2853,
"s": 2479,
"text": "Again, the Mode Analytics report is available here — you do not need to create a Mode Analytics account in order to see the report, however, cloning it requires a free account. The original data set can be found at the link provided before, and everything else (SQL, Python code, how to build the charts and Python visualizations) is all available within the linked report."
},
{
"code": null,
"e": 3713,
"s": 2853,
"text": "To start with, I took the relay-foods data set and added it as a public file on Mode — here are Mode’s instructions on how to do that (I also added an all_time dataset, more on that in the projected LTV portion). The Python code in this portion of the post can be found in the Notebook section of the report here; this is identical to the code utilized in my prior post — the difference is that a dataframe created from an SQL query is utilized within a Mode Python notebook. Additionally, the SQL code provided below shows a minor data enrichment step that I took on this dataset, where I categorize the first payment for a user as ‘Initial’ and any subsequent payments as ‘Repeat’. This is a fairly minor but quick example of the type of business logic that you can apply to data sources, generally using aggregate fact tables as I’ve mentioned in the past."
},
{
"code": null,
"e": 4167,
"s": 3713,
"text": "with payment_enrichment as ( select order_id , order_date , user_id , total_charges , common_id , pup_id , pickup_date , date_trunc('month', order_date) as order_month , row_number() over (partition by user_id order by order_date) as payment_number from kdboller.relay_foods_v1 ) select pe.* , case when payment_number = 1 then 'Initial' else 'Repeat' end as payment_type from payment_enrichment as pe"
},
{
"code": null,
"e": 5087,
"s": 4167,
"text": "As the next step in this analysis, I will build a projected LTV analysis, referencing another previously mentioned and helpful resource which I found online — Ryan Iyengar posted this forecasting LTV post on Medium a little bit over a year ago, found here. If you’ve ever conducted an LTV analysis in Excel, you know that this can be rather time consuming and these models can become extremely large and much less dynamic than one would prefer. You would think that there has to be a better way to calculate a single value which is rather critical to understanding the health of a subscription business. Fortunately, there are at least a few better, highly repeatable ways to do this. Furthermore, evaluating different start/end date ranges for cohorts to include, e.g., to normalize for particularly strong “early adopter” cohorts, is a significant advantage of conducting this type of analysis in SQL and / or Python."
},
{
"code": null,
"e": 5874,
"s": 5087,
"text": "With all of this said, Ryan’s post definitely requires a fairly thorough understanding of SQL, particularly given the significant use of common table expressions (CTEs). Given the length of the resulting query, I’ve not pasted it directly into this post but you can find several build ups to the final query within the Mode Report. If you have specific questions on the background or rationale for this piece of my post, I would refer you to his rather insightful and informative explanations. For purposes of my article and report, I’ve shown how to create the needed data return from the original data set we’re using, provide some observational takeaways from our dataset below and also show a few key charts in the LTV section that Mode easily allows me to add to my overall report."
},
{
"code": null,
"e": 5911,
"s": 5874,
"text": "LTV Section — summary of the queries"
},
{
"code": null,
"e": 6704,
"s": 5911,
"text": "The SQL queries related to LTV, which piggyback off of Ryan’s extremely helpful work, start with the numbering of 2–8 within the report. Within Mode, I try to order my queries using this system in order to track the natural progression of the queries written within a project — a nice feature request would be to have some type of a folder-ing system in order to organize these into payment, LTV, and RFM query sections. Query #2 manipulates the dataset in order to pull back a return that is consistent with the dataset which Ryan used in his post — as a result, this hopefully make this much more straightforward to follow. I also built out the query breaks to mimic where Ryan pauses during his blog post, so that it is easier to follow between his post and the Mode report that I created."
},
{
"code": null,
"e": 7728,
"s": 6704,
"text": "Within queries 4–6, you’ll see that while performing this I detected an anomalous situation within one of the cohorts (see screenshot below this paragraph). In the 2009/04/01 cohort, in the three latest months the cohort’s revenue share actually dramatically increased; while reactivations, users who leave a cohort and then later return, are not uncommon, this significantly skewed the forecasted revenue and therefore LTV for this particular cohort. As a result, rather than projecting a decay in revenue, the model was forecasting a greater than 20% month over month increase (for the whole forecast). While there are probably a few preferred ways to normalize this, in the interest of time I decided to just exclude this cohort from the overall analysis — I would say that something similar to this happens in almost every analysis, and it’s obviously critical to vet the data and determine how to adjust as needed. The adjustment decisions will somewhat vary given a company’s industry, future prospects, and maturity."
},
{
"code": null,
"e": 8974,
"s": 7728,
"text": "Queries 7 and 8 complete the query with the final expected return, one which shows the projected LTV for each cohort and one which shows the overall forecasted LTV when taking into account all cohorts’ forecasted projections and initial users. As you can see from the below screen scrape copied from the Mode Report output, the overall LTV is ~$315. In addition to that, we see that the initial cohort, most likely the “early adopters”, have a much higher LTV than those seen in subsequent months — with the caveat that we only have 12 monthly cohorts to evaluate and this is a rarely new company given this example, next steps could include further segmenting users and finding each LTV, as well as potentially normalizing overall LTV by excluding the “early adopter” contribution from this analysis. It’s also worth noting that the LTV is much lower with the higher volume recent cohorts, and we would want to understand if we can more effectively grow our user base while ideally growing, or at minimum maintaining, our LTV over time. Please note that when finalizing an analysis such as this, you should also calculate a gross margin, or preferably a contribution margin, to reflect the true underlying economics and LTV for each subscriber."
},
{
"code": null,
"e": 8987,
"s": 8974,
"text": "RFM Analyses"
},
{
"code": null,
"e": 9284,
"s": 8987,
"text": "In this last section, I’ve included a Recency, Frequency, Monetary Value (RFM) analysis. While in the course of reviewing effective ways to segment subscribers and after discovering this methodology, I then found this helpful notebook on Joao Correia’s GitHub. Here’s a very brief rundown of RFM."
},
{
"code": null,
"e": 9390,
"s": 9284,
"text": "Recency: how recently from an evaluated date, e.g., today, a user / subscriber has purchased from a site."
},
{
"code": null,
"e": 9521,
"s": 9390,
"text": "Frequency: the number of times that a user / subscriber has purchased on a particular site in their entire lifetime as a customer."
},
{
"code": null,
"e": 9672,
"s": 9521,
"text": "Monetary Value: the dollar amount that the user / subscriber has paid in total from all of their purchases during their entire lifetime as a customer."
},
{
"code": null,
"e": 10607,
"s": 9672,
"text": "While there are a few ways to complete the RFM analysis, including via SQL, part of my intent here is to show how the useful work of others can be repurposed with a rather straightforward initial dataset. Within the Python notebook, RFM Analyses section, you will see that I’ve largely followed Joao’s notebook. As in his notebook’s conclusion, I show below the the top ten customers in the RFMClass 111 — this represents the users who are in the top quartile for all three RFM metrics; these users have paid rather recently, and have also paid more times and at a higher monetary value than 75% of the site’s other users. As a result, these users are prime for qualitative surveys requesting feedback on what they love and what could be better, and you can also study their site behavior to understand what they may be doing and discovering which is different than other visitors, among several different evaluations you can take on."
},
{
"code": null,
"e": 11266,
"s": 10607,
"text": "Utilizing Plotly within the Mode report, I then added three visualizations which help me to better understand the data and are also meant to anticipate potential questions from business stakeholders. The first shows the distribution of users within each RFMClass. On a positive note, 81 users are in the 111 class, but 75 are in 344 and 65 are in 444 — these are users who have not paid in a while, and who have also paid far fewer times and at a much lower monetary value than the median value for all users. We would want to see if we could resurrect these users or if there’s something that happened which caused them to (almost) never return to our site."
},
{
"code": null,
"e": 11848,
"s": 11266,
"text": "Lastly, I would want to know how each RFMClass indexes in terms of cohort groups — are earlier cohorts the ones that are primarily in the 111 class? If so, that would probably be a cause for concern. In order to accomplish this part, you will find a ‘Merge Data to show RFM Class by Cohorts’ section within the Python notebook, where I take a subset of the initial payments dataframe and merge this with the rfmSegmentation dataframe that was created. If you need a primer on merging dataframes in Python, similar to joining in SQL, I will refer you to another Greg Reda post here."
},
{
"code": null,
"e": 12471,
"s": 11848,
"text": "In reviewing the two charts (below), the first with total users by cohort and the second with RFM Class 111 users by cohort, we see that the largest contributors to the RFM Class 111 are from November 2009 and January 2010. However, when reviewing the first chart with total users per cohort, we see that November 2009 was a particularly large cohort, and on a relative basis is not as strong of a contributor to the top RFM class. An even better output would calculate, for each cohort, what percent RFMClass 111 users comprised of each monthly cohort; but I’ll leave that for another time / potentially a follow-up post."
},
{
"code": null,
"e": 12717,
"s": 12471,
"text": "And this concludes a post with analyses that I really enjoyed putting together. Hopefully this conveys the value of stepping out of Excel, leveraging the public contributions of insightful people and the benefits of tools such as SQL and Python."
},
{
"code": null,
"e": 12880,
"s": 12717,
"text": "Some quick notes on the benefits of working with Mode (also, here’s a post from Mode’s blog regarding their take on getting out of Excel and into SQL and Python):"
},
{
"code": null,
"e": 13052,
"s": 12880,
"text": "Charts can be easily created either in SQL (built-in chart functionality) or in Python; these charts are then tied to your data’s queries and will be updated automatically"
},
{
"code": null,
"e": 13175,
"s": 13052,
"text": "Reports are highly reproducible and can be cloned if you want to preserve a previous one, e.g., quarterly business reviews"
},
{
"code": null,
"e": 13333,
"s": 13175,
"text": "Mitigates need to create a dataset and read out as a CSV into a Jupyter notebook; you can read each query directly into Mode’s Python notebook as a dataframe"
},
{
"code": null,
"e": 13528,
"s": 13333,
"text": "I say all of this with the caveat that not all Python libraries are available within Mode, although quite a few are, and computing power is an area in which Mode is constantly looking to improve"
},
{
"code": null,
"e": 13668,
"s": 13528,
"text": "Starting from a rather basic user data set and leveraging the full functionality of Mode Analytics, we were able to complete the following:"
},
{
"code": null,
"e": 13720,
"s": 13668,
"text": "Contribute two public datasets onto Mode’s platform"
},
{
"code": null,
"e": 13776,
"s": 13720,
"text": "Group the users into monthly cohorts via SQL and Python"
},
{
"code": null,
"e": 13856,
"s": 13776,
"text": "Build retention curves / retention heatmaps for these monthly cohorts in Python"
},
{
"code": null,
"e": 13927,
"s": 13856,
"text": "Calculate a weighted average retention curve for the cohorts in Python"
},
{
"code": null,
"e": 13992,
"s": 13927,
"text": "Project LTV for the entire company and for each cohort using SQL"
},
{
"code": null,
"e": 14275,
"s": 13992,
"text": "Conduct an RFM analysis and understand the distribution for each class and the contribution by Monthly cohort in Python — this is completed by merging two dataframes (one created from a combined SQL and Python effort and one created directly in Python) within Mode’s Python notebook"
},
{
"code": null,
"e": 14357,
"s": 14275,
"text": "Finally, we created a (hopefully) intuitive, comprehensive and open-source report"
},
{
"code": null,
"e": 14490,
"s": 14357,
"text": "This report is rather extensible as far as adding in additional analyses and can also be easily updated as new monthly data rolls in"
}
] |
Priority Queue using Queue and Heapdict module in Python - GeeksforGeeks
|
31 Dec, 2020
Priority Queue is an extension of the queue with the following properties.
An element with high priority is dequeued before an element with low priority.
If two elements have the same priority, they are served according to their order in the queue.
It is a constructor for a priority queue. maxsize is the number of elements which can be inserted into queue, its default value is 0. If the maxsize value is less than or equal to 0, then queue size is infinite. Items are retrieved priority order (lowest first).Functions-
put() – Puts an item into the queue.
get() – Removes and returns an item from the queue.
qsize() – Returns the current queue size.
empty() – Returns True if the queue is empty, False otherwise. It is equivalent to qsize()==0.
full() – Returns True if the queue is full, False otherwise. It is equivalent to qsize()>=maxsize.
Note : empty(), full(), qsize() are not reliable as they risk race condition where the queue size might change.
Example:
from queue import PriorityQueue q = PriorityQueue() # insert into queueq.put((2, 'g'))q.put((3, 'e'))q.put((4, 'k'))q.put((5, 's'))q.put((1, 'e')) # remove and return # lowest priority itemprint(q.get())print(q.get()) # check queue sizeprint('Items in queue :', q.qsize()) # check if queue is emptyprint('Is queue empty :', q.empty()) # check if queue is fullprint('Is queue full :', q.full())
Output :
(1, 'e')
(2, 'g')
Items in queue : 3
Is queue empty : False
Is queue full : False
Heapdict implements the MutableMapping ABC, meaning it works pretty much like a regular Python dictionary. It’s designed to be used as a priority queue. Along with functions provided by ordinary dict(), it also has popitem() and peekitem() functions which return the pair with the lowest priority. Unlike heapq module, the HeapDict supports efficiently changing the priority of an existing object (“decrease-key” ). Altering the priority is important for many algorithms such as Dijkstra’s Algorithm and A*.
Functions-
clear(self) – D.clear() -> None. Remove all items from D.
peekitem(self) – D.peekitem() -> (k, v), return the (key, value) pair with lowest value; but raise KeyError if D is empty.
popitem(self) – D.popitem() -> (k, v), remove and return the (key, value) pair with lowest value; but raise KeyError if D is empty.
get(self, key, default=None) – D.get(k[, d]) -> D[k] if k in D, else d. d defaults to None.
items(self) – D.items() -> a set-like object providing a view on D’s items
keys(self) – D.keys() -> a set-like object providing a view on D’s keys
values(self) – D.values() -> an object providing a view on D’s values
Example:
import heapdict h = heapdict.heapdict() # Adding pairs into heapdicth['g']= 2h['e']= 1h['k']= 3h['s']= 4 print('list of key:value pairs in h:\n', list(h.items()))print('pair with lowest priority:\n', h.peekitem())print('list of keys in h:\n', list(h.keys()))print('list of values in h:\n', list(h.values()))print('remove pair with lowest priority:\n', h.popitem())print('get value for key 5 in h:\n', h.get(5, 'Not found')) # clear heapdict hh.clear()print(list(h.items()))
Output :
list of key:value pairs in h:
[('g', 2), ('e', 1), ('k', 3), ('s', 4)]
pair with lowest priority:
('e', 1)
list of keys in h:
['g', 'e', 'k', 's']
list of values in h:
[2, 1, 3, 4]
remove pair with lowest priority:
('e', 1)
get value for key 5 in h:
Not found
[]
priority-queue
Python DSA-exercises
python-modules
Python
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
|
[
{
"code": null,
"e": 24236,
"s": 24208,
"text": "\n31 Dec, 2020"
},
{
"code": null,
"e": 24311,
"s": 24236,
"text": "Priority Queue is an extension of the queue with the following properties."
},
{
"code": null,
"e": 24390,
"s": 24311,
"text": "An element with high priority is dequeued before an element with low priority."
},
{
"code": null,
"e": 24485,
"s": 24390,
"text": "If two elements have the same priority, they are served according to their order in the queue."
},
{
"code": null,
"e": 24758,
"s": 24485,
"text": "It is a constructor for a priority queue. maxsize is the number of elements which can be inserted into queue, its default value is 0. If the maxsize value is less than or equal to 0, then queue size is infinite. Items are retrieved priority order (lowest first).Functions-"
},
{
"code": null,
"e": 24795,
"s": 24758,
"text": "put() – Puts an item into the queue."
},
{
"code": null,
"e": 24847,
"s": 24795,
"text": "get() – Removes and returns an item from the queue."
},
{
"code": null,
"e": 24889,
"s": 24847,
"text": "qsize() – Returns the current queue size."
},
{
"code": null,
"e": 24984,
"s": 24889,
"text": "empty() – Returns True if the queue is empty, False otherwise. It is equivalent to qsize()==0."
},
{
"code": null,
"e": 25083,
"s": 24984,
"text": "full() – Returns True if the queue is full, False otherwise. It is equivalent to qsize()>=maxsize."
},
{
"code": null,
"e": 25195,
"s": 25083,
"text": "Note : empty(), full(), qsize() are not reliable as they risk race condition where the queue size might change."
},
{
"code": null,
"e": 25204,
"s": 25195,
"text": "Example:"
},
{
"code": "from queue import PriorityQueue q = PriorityQueue() # insert into queueq.put((2, 'g'))q.put((3, 'e'))q.put((4, 'k'))q.put((5, 's'))q.put((1, 'e')) # remove and return # lowest priority itemprint(q.get())print(q.get()) # check queue sizeprint('Items in queue :', q.qsize()) # check if queue is emptyprint('Is queue empty :', q.empty()) # check if queue is fullprint('Is queue full :', q.full())",
"e": 25604,
"s": 25204,
"text": null
},
{
"code": null,
"e": 25613,
"s": 25604,
"text": "Output :"
},
{
"code": null,
"e": 25696,
"s": 25613,
"text": "(1, 'e')\n(2, 'g')\nItems in queue : 3\nIs queue empty : False\nIs queue full : False\n"
},
{
"code": null,
"e": 26204,
"s": 25696,
"text": "Heapdict implements the MutableMapping ABC, meaning it works pretty much like a regular Python dictionary. It’s designed to be used as a priority queue. Along with functions provided by ordinary dict(), it also has popitem() and peekitem() functions which return the pair with the lowest priority. Unlike heapq module, the HeapDict supports efficiently changing the priority of an existing object (“decrease-key” ). Altering the priority is important for many algorithms such as Dijkstra’s Algorithm and A*."
},
{
"code": null,
"e": 26215,
"s": 26204,
"text": "Functions-"
},
{
"code": null,
"e": 26273,
"s": 26215,
"text": "clear(self) – D.clear() -> None. Remove all items from D."
},
{
"code": null,
"e": 26396,
"s": 26273,
"text": "peekitem(self) – D.peekitem() -> (k, v), return the (key, value) pair with lowest value; but raise KeyError if D is empty."
},
{
"code": null,
"e": 26528,
"s": 26396,
"text": "popitem(self) – D.popitem() -> (k, v), remove and return the (key, value) pair with lowest value; but raise KeyError if D is empty."
},
{
"code": null,
"e": 26620,
"s": 26528,
"text": "get(self, key, default=None) – D.get(k[, d]) -> D[k] if k in D, else d. d defaults to None."
},
{
"code": null,
"e": 26695,
"s": 26620,
"text": "items(self) – D.items() -> a set-like object providing a view on D’s items"
},
{
"code": null,
"e": 26767,
"s": 26695,
"text": "keys(self) – D.keys() -> a set-like object providing a view on D’s keys"
},
{
"code": null,
"e": 26837,
"s": 26767,
"text": "values(self) – D.values() -> an object providing a view on D’s values"
},
{
"code": null,
"e": 26846,
"s": 26837,
"text": "Example:"
},
{
"code": "import heapdict h = heapdict.heapdict() # Adding pairs into heapdicth['g']= 2h['e']= 1h['k']= 3h['s']= 4 print('list of key:value pairs in h:\\n', list(h.items()))print('pair with lowest priority:\\n', h.peekitem())print('list of keys in h:\\n', list(h.keys()))print('list of values in h:\\n', list(h.values()))print('remove pair with lowest priority:\\n', h.popitem())print('get value for key 5 in h:\\n', h.get(5, 'Not found')) # clear heapdict hh.clear()print(list(h.items()))",
"e": 27355,
"s": 26846,
"text": null
},
{
"code": null,
"e": 27364,
"s": 27355,
"text": "Output :"
},
{
"code": null,
"e": 27634,
"s": 27364,
"text": "list of key:value pairs in h:\n [('g', 2), ('e', 1), ('k', 3), ('s', 4)]\npair with lowest priority:\n ('e', 1)\nlist of keys in h:\n ['g', 'e', 'k', 's']\nlist of values in h:\n [2, 1, 3, 4]\nremove pair with lowest priority:\n ('e', 1)\nget value for key 5 in h:\n Not found\n[]\n"
},
{
"code": null,
"e": 27649,
"s": 27634,
"text": "priority-queue"
},
{
"code": null,
"e": 27670,
"s": 27649,
"text": "Python DSA-exercises"
},
{
"code": null,
"e": 27685,
"s": 27670,
"text": "python-modules"
},
{
"code": null,
"e": 27692,
"s": 27685,
"text": "Python"
},
{
"code": null,
"e": 27707,
"s": 27692,
"text": "priority-queue"
},
{
"code": null,
"e": 27805,
"s": 27707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27814,
"s": 27805,
"text": "Comments"
},
{
"code": null,
"e": 27827,
"s": 27814,
"text": "Old Comments"
},
{
"code": null,
"e": 27848,
"s": 27827,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27880,
"s": 27848,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27903,
"s": 27880,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27925,
"s": 27903,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27952,
"s": 27925,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27968,
"s": 27952,
"text": "Deque in Python"
},
{
"code": null,
"e": 28010,
"s": 27968,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28066,
"s": 28010,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28111,
"s": 28066,
"text": "Python - Ways to remove duplicates from list"
}
] |
Tryit Editor v3.7
|
Tryit: Canvas with a circle
|
[] |
Synonym & Antonym Replacement
|
While working with NLP, especially in the case of frequency analysis and text indexing, it is always beneficial to compress the vocabulary without losing meaning because it saves lots of memory. To achieve this, we must have to define mapping of a word to its synonyms. In the example below, we will be creating a class named word_syn_replacer which can be used for replacing the words with their common synonyms.
First, import the necessary package re to work with regular expressions.
import re
from nltk.corpus import wordnet
Next, create the class that takes a word replacement mapping −
class word_syn_replacer(object):
def __init__(self, word_map):
self.word_map = word_map
def replace(self, word):
return self.word_map.get(word, word)
Save this python program (say replacesyn.py) and run it from python command prompt. After running it, import word_syn_replacer class when you want to replace words with common synonyms. Let us see how.
from replacesyn import word_syn_replacer
rep_syn = word_syn_replacer ({‘bday’: ‘birthday’)
rep_syn.replace(‘bday’)
'birthday'
import re
from nltk.corpus import wordnet
class word_syn_replacer(object):
def __init__(self, word_map):
self.word_map = word_map
def replace(self, word):
return self.word_map.get(word, word)
Now once you saved the above program and run it, you can import the class and use it as follows −
from replacesyn import word_syn_replacer
rep_syn = word_syn_replacer ({‘bday’: ‘birthday’)
rep_syn.replace(‘bday’)
'birthday'
The disadvantage of the above method is that we should have to hardcode the synonyms in a Python dictionary. We have two better alternatives in the form of CSV and YAML file. We can save our synonym vocabulary in any of the above-mentioned files and can construct word_map dictionary from them. Let us understand the concept with the help of examples.
In order to use CSV file for this purpose, the file should have two columns, first column consist of word and the second column consists of the synonyms meant to replace it. Let us save this file as syn.csv. In the example below, we will be creating a class named CSVword_syn_replacer which will extends word_syn_replacer in replacesyn.py file and will be used to construct the word_map dictionary from syn.csv file.
First, import the necessary packages.
import csv
Next, create the class that takes a word replacement mapping −
class CSVword_syn_replacer(word_syn_replacer):
def __init__(self, fname):
word_map = {}
for line in csv.reader(open(fname)):
word, syn = line
word_map[word] = syn
super(Csvword_syn_replacer, self).__init__(word_map)
After running it, import CSVword_syn_replacer class when you want to replace words with common synonyms. Let us see how?
from replacesyn import CSVword_syn_replacer
rep_syn = CSVword_syn_replacer (‘syn.csv’)
rep_syn.replace(‘bday’)
'birthday'
import csv
class CSVword_syn_replacer(word_syn_replacer):
def __init__(self, fname):
word_map = {}
for line in csv.reader(open(fname)):
word, syn = line
word_map[word] = syn
super(Csvword_syn_replacer, self).__init__(word_map)
Now once you saved the above program and run it, you can import the class and use it as follows −
from replacesyn import CSVword_syn_replacer
rep_syn = CSVword_syn_replacer (‘syn.csv’)
rep_syn.replace(‘bday’)
'birthday'
As we have used CSV file, we can also use YAML file to for this purpose (we must have PyYAML installed). Let us save the file as syn.yaml. In the example below, we will be creating a class named YAMLword_syn_replacer which will extends word_syn_replacer in replacesyn.py file and will be used to construct the word_map dictionary from syn.yaml file.
First, import the necessary packages.
import yaml
Next, create the class that takes a word replacement mapping −
class YAMLword_syn_replacer(word_syn_replacer):
def __init__(self, fname):
word_map = yaml.load(open(fname))
super(YamlWordReplacer, self).__init__(word_map)
After running it, import YAMLword_syn_replacer class when you want to replace words with common synonyms. Let us see how?
from replacesyn import YAMLword_syn_replacer
rep_syn = YAMLword_syn_replacer (‘syn.yaml’)
rep_syn.replace(‘bday’)
'birthday'
import yaml
class YAMLword_syn_replacer(word_syn_replacer):
def __init__(self, fname):
word_map = yaml.load(open(fname))
super(YamlWordReplacer, self).__init__(word_map)
Now once you saved the above program and run it, you can import the class and use it as follows −
from replacesyn import YAMLword_syn_replacer
rep_syn = YAMLword_syn_replacer (‘syn.yaml’)
rep_syn.replace(‘bday’)
'birthday'
As we know that an antonym is a word having opposite meaning of another word, and the opposite of synonym replacement is called antonym replacement. In this section, we will be dealing with antonym replacement, i.e., replacing words with unambiguous antonyms by using WordNet. In the example below, we will be creating a class named word_antonym_replacer which have two methods, one for replacing the word and other for removing the negations.
First, import the necessary packages.
from nltk.corpus import wordnet
Next, create the class named word_antonym_replacer −
class word_antonym_replacer(object):
def replace(self, word, pos=None):
antonyms = set()
for syn in wordnet.synsets(word, pos=pos):
for lemma in syn.lemmas():
for antonym in lemma.antonyms():
antonyms.add(antonym.name())
if len(antonyms) == 1:
return antonyms.pop()
else:
return None
def replace_negations(self, sent):
i, l = 0, len(sent)
words = []
while i < l:
word = sent[i]
if word == 'not' and i+1 < l:
ant = self.replace(sent[i+1])
if ant:
words.append(ant)
i += 2
continue
words.append(word)
i += 1
return words
Save this python program (say replaceantonym.py) and run it from python command prompt. After running it, import word_antonym_replacer class when you want to replace words with their unambiguous antonyms. Let us see how.
from replacerantonym import word_antonym_replacer
rep_antonym = word_antonym_replacer ()
rep_antonym.replace(‘uglify’)
['beautify'']
sentence = ["Let us", 'not', 'uglify', 'our', 'country']
rep_antonym.replace _negations(sentence)
["Let us", 'beautify', 'our', 'country']
nltk.corpus import wordnet
class word_antonym_replacer(object):
def replace(self, word, pos=None):
antonyms = set()
for syn in wordnet.synsets(word, pos=pos):
for lemma in syn.lemmas():
for antonym in lemma.antonyms():
antonyms.add(antonym.name())
if len(antonyms) == 1:
return antonyms.pop()
else:
return None
def replace_negations(self, sent):
i, l = 0, len(sent)
words = []
while i < l:
word = sent[i]
if word == 'not' and i+1 < l:
ant = self.replace(sent[i+1])
if ant:
words.append(ant)
i += 2
continue
words.append(word)
i += 1
return words
Now once you saved the above program and run it, you can import the class and use it as follows −
from replacerantonym import word_antonym_replacer
rep_antonym = word_antonym_replacer ()
rep_antonym.replace(‘uglify’)
sentence = ["Let us", 'not', 'uglify', 'our', 'country']
rep_antonym.replace _negations(sentence)
["Let us", 'beautify', 'our', 'country']
59 Lectures
2.5 hours
Mike West
17 Lectures
1 hours
Pranjal Srivastava
6 Lectures
1 hours
Prabh Kirpa Classes
12 Lectures
1 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2798,
"s": 2384,
"text": "While working with NLP, especially in the case of frequency analysis and text indexing, it is always beneficial to compress the vocabulary without losing meaning because it saves lots of memory. To achieve this, we must have to define mapping of a word to its synonyms. In the example below, we will be creating a class named word_syn_replacer which can be used for replacing the words with their common synonyms."
},
{
"code": null,
"e": 2871,
"s": 2798,
"text": "First, import the necessary package re to work with regular expressions."
},
{
"code": null,
"e": 2913,
"s": 2871,
"text": "import re\nfrom nltk.corpus import wordnet"
},
{
"code": null,
"e": 2976,
"s": 2913,
"text": "Next, create the class that takes a word replacement mapping −"
},
{
"code": null,
"e": 3135,
"s": 2976,
"text": "class word_syn_replacer(object):\n def __init__(self, word_map):\n self.word_map = word_map\ndef replace(self, word):\n return self.word_map.get(word, word)"
},
{
"code": null,
"e": 3337,
"s": 3135,
"text": "Save this python program (say replacesyn.py) and run it from python command prompt. After running it, import word_syn_replacer class when you want to replace words with common synonyms. Let us see how."
},
{
"code": null,
"e": 3452,
"s": 3337,
"text": "from replacesyn import word_syn_replacer\nrep_syn = word_syn_replacer ({‘bday’: ‘birthday’)\nrep_syn.replace(‘bday’)"
},
{
"code": null,
"e": 3464,
"s": 3452,
"text": "'birthday'\n"
},
{
"code": null,
"e": 3665,
"s": 3464,
"text": "import re\nfrom nltk.corpus import wordnet\nclass word_syn_replacer(object):\n def __init__(self, word_map):\n self.word_map = word_map\ndef replace(self, word):\n return self.word_map.get(word, word)"
},
{
"code": null,
"e": 3763,
"s": 3665,
"text": "Now once you saved the above program and run it, you can import the class and use it as follows −"
},
{
"code": null,
"e": 3878,
"s": 3763,
"text": "from replacesyn import word_syn_replacer\nrep_syn = word_syn_replacer ({‘bday’: ‘birthday’)\nrep_syn.replace(‘bday’)"
},
{
"code": null,
"e": 3890,
"s": 3878,
"text": "'birthday'\n"
},
{
"code": null,
"e": 4242,
"s": 3890,
"text": "The disadvantage of the above method is that we should have to hardcode the synonyms in a Python dictionary. We have two better alternatives in the form of CSV and YAML file. We can save our synonym vocabulary in any of the above-mentioned files and can construct word_map dictionary from them. Let us understand the concept with the help of examples."
},
{
"code": null,
"e": 4659,
"s": 4242,
"text": "In order to use CSV file for this purpose, the file should have two columns, first column consist of word and the second column consists of the synonyms meant to replace it. Let us save this file as syn.csv. In the example below, we will be creating a class named CSVword_syn_replacer which will extends word_syn_replacer in replacesyn.py file and will be used to construct the word_map dictionary from syn.csv file."
},
{
"code": null,
"e": 4697,
"s": 4659,
"text": "First, import the necessary packages."
},
{
"code": null,
"e": 4708,
"s": 4697,
"text": "import csv"
},
{
"code": null,
"e": 4771,
"s": 4708,
"text": "Next, create the class that takes a word replacement mapping −"
},
{
"code": null,
"e": 5026,
"s": 4771,
"text": "class CSVword_syn_replacer(word_syn_replacer):\n def __init__(self, fname):\n word_map = {}\n for line in csv.reader(open(fname)):\n word, syn = line\n word_map[word] = syn\n super(Csvword_syn_replacer, self).__init__(word_map)"
},
{
"code": null,
"e": 5147,
"s": 5026,
"text": "After running it, import CSVword_syn_replacer class when you want to replace words with common synonyms. Let us see how?"
},
{
"code": null,
"e": 5258,
"s": 5147,
"text": "from replacesyn import CSVword_syn_replacer\nrep_syn = CSVword_syn_replacer (‘syn.csv’)\nrep_syn.replace(‘bday’)"
},
{
"code": null,
"e": 5270,
"s": 5258,
"text": "'birthday'\n"
},
{
"code": null,
"e": 5503,
"s": 5270,
"text": "import csv\nclass CSVword_syn_replacer(word_syn_replacer):\ndef __init__(self, fname):\nword_map = {}\nfor line in csv.reader(open(fname)):\n word, syn = line\n word_map[word] = syn\nsuper(Csvword_syn_replacer, self).__init__(word_map)"
},
{
"code": null,
"e": 5601,
"s": 5503,
"text": "Now once you saved the above program and run it, you can import the class and use it as follows −"
},
{
"code": null,
"e": 5712,
"s": 5601,
"text": "from replacesyn import CSVword_syn_replacer\nrep_syn = CSVword_syn_replacer (‘syn.csv’)\nrep_syn.replace(‘bday’)"
},
{
"code": null,
"e": 5724,
"s": 5712,
"text": "'birthday'\n"
},
{
"code": null,
"e": 6074,
"s": 5724,
"text": "As we have used CSV file, we can also use YAML file to for this purpose (we must have PyYAML installed). Let us save the file as syn.yaml. In the example below, we will be creating a class named YAMLword_syn_replacer which will extends word_syn_replacer in replacesyn.py file and will be used to construct the word_map dictionary from syn.yaml file."
},
{
"code": null,
"e": 6112,
"s": 6074,
"text": "First, import the necessary packages."
},
{
"code": null,
"e": 6124,
"s": 6112,
"text": "import yaml"
},
{
"code": null,
"e": 6187,
"s": 6124,
"text": "Next, create the class that takes a word replacement mapping −"
},
{
"code": null,
"e": 6354,
"s": 6187,
"text": "class YAMLword_syn_replacer(word_syn_replacer):\n def __init__(self, fname):\n word_map = yaml.load(open(fname))\n super(YamlWordReplacer, self).__init__(word_map)"
},
{
"code": null,
"e": 6476,
"s": 6354,
"text": "After running it, import YAMLword_syn_replacer class when you want to replace words with common synonyms. Let us see how?"
},
{
"code": null,
"e": 6590,
"s": 6476,
"text": "from replacesyn import YAMLword_syn_replacer\nrep_syn = YAMLword_syn_replacer (‘syn.yaml’)\nrep_syn.replace(‘bday’)"
},
{
"code": null,
"e": 6602,
"s": 6590,
"text": "'birthday'\n"
},
{
"code": null,
"e": 6778,
"s": 6602,
"text": "import yaml\nclass YAMLword_syn_replacer(word_syn_replacer):\ndef __init__(self, fname):\n word_map = yaml.load(open(fname))\n super(YamlWordReplacer, self).__init__(word_map)"
},
{
"code": null,
"e": 6876,
"s": 6778,
"text": "Now once you saved the above program and run it, you can import the class and use it as follows −"
},
{
"code": null,
"e": 6990,
"s": 6876,
"text": "from replacesyn import YAMLword_syn_replacer\nrep_syn = YAMLword_syn_replacer (‘syn.yaml’)\nrep_syn.replace(‘bday’)"
},
{
"code": null,
"e": 7002,
"s": 6990,
"text": "'birthday'\n"
},
{
"code": null,
"e": 7446,
"s": 7002,
"text": "As we know that an antonym is a word having opposite meaning of another word, and the opposite of synonym replacement is called antonym replacement. In this section, we will be dealing with antonym replacement, i.e., replacing words with unambiguous antonyms by using WordNet. In the example below, we will be creating a class named word_antonym_replacer which have two methods, one for replacing the word and other for removing the negations."
},
{
"code": null,
"e": 7484,
"s": 7446,
"text": "First, import the necessary packages."
},
{
"code": null,
"e": 7516,
"s": 7484,
"text": "from nltk.corpus import wordnet"
},
{
"code": null,
"e": 7569,
"s": 7516,
"text": "Next, create the class named word_antonym_replacer −"
},
{
"code": null,
"e": 8301,
"s": 7569,
"text": "class word_antonym_replacer(object):\n def replace(self, word, pos=None):\n antonyms = set()\n for syn in wordnet.synsets(word, pos=pos):\n for lemma in syn.lemmas():\n for antonym in lemma.antonyms():\n antonyms.add(antonym.name())\n if len(antonyms) == 1:\n return antonyms.pop()\n else:\n return None\n def replace_negations(self, sent):\n i, l = 0, len(sent)\n words = []\n while i < l:\n word = sent[i]\n if word == 'not' and i+1 < l:\n ant = self.replace(sent[i+1])\n if ant:\n words.append(ant)\n i += 2\n continue\n words.append(word)\n i += 1\n return words"
},
{
"code": null,
"e": 8522,
"s": 8301,
"text": "Save this python program (say replaceantonym.py) and run it from python command prompt. After running it, import word_antonym_replacer class when you want to replace words with their unambiguous antonyms. Let us see how."
},
{
"code": null,
"e": 8641,
"s": 8522,
"text": "from replacerantonym import word_antonym_replacer\nrep_antonym = word_antonym_replacer ()\nrep_antonym.replace(‘uglify’)"
},
{
"code": null,
"e": 8754,
"s": 8641,
"text": "['beautify'']\nsentence = [\"Let us\", 'not', 'uglify', 'our', 'country']\nrep_antonym.replace _negations(sentence)\n"
},
{
"code": null,
"e": 8796,
"s": 8754,
"text": "[\"Let us\", 'beautify', 'our', 'country']\n"
},
{
"code": null,
"e": 9477,
"s": 8796,
"text": "nltk.corpus import wordnet\nclass word_antonym_replacer(object):\ndef replace(self, word, pos=None):\n antonyms = set()\n for syn in wordnet.synsets(word, pos=pos):\n for lemma in syn.lemmas():\n for antonym in lemma.antonyms():\n antonyms.add(antonym.name())\n if len(antonyms) == 1:\n return antonyms.pop()\n else:\n return None\ndef replace_negations(self, sent):\n i, l = 0, len(sent)\n words = []\n while i < l:\n word = sent[i]\n if word == 'not' and i+1 < l:\n ant = self.replace(sent[i+1])\n if ant:\n words.append(ant)\n i += 2\n continue\n words.append(word)\n i += 1\n return words"
},
{
"code": null,
"e": 9575,
"s": 9477,
"text": "Now once you saved the above program and run it, you can import the class and use it as follows −"
},
{
"code": null,
"e": 9792,
"s": 9575,
"text": "from replacerantonym import word_antonym_replacer\nrep_antonym = word_antonym_replacer ()\nrep_antonym.replace(‘uglify’)\nsentence = [\"Let us\", 'not', 'uglify', 'our', 'country']\nrep_antonym.replace _negations(sentence)"
},
{
"code": null,
"e": 9834,
"s": 9792,
"text": "[\"Let us\", 'beautify', 'our', 'country']\n"
},
{
"code": null,
"e": 9869,
"s": 9834,
"text": "\n 59 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9880,
"s": 9869,
"text": " Mike West"
},
{
"code": null,
"e": 9913,
"s": 9880,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9933,
"s": 9913,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 9965,
"s": 9933,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9986,
"s": 9965,
"text": " Prabh Kirpa Classes"
},
{
"code": null,
"e": 10019,
"s": 9986,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10042,
"s": 10019,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 10049,
"s": 10042,
"text": " Print"
},
{
"code": null,
"e": 10060,
"s": 10049,
"text": " Add Notes"
}
] |
Get Seconds from timestamp in Python-Pandas - GeeksforGeeks
|
05 Apr, 2022
In this program our task is to create a program in python which will extract seconds from a given timestamp. We will use the s attribute of the DateTime object to extract the second.Example : If we have a data frame that contains 5 different time stamps such as:
Timestamp
2012-12-11 04:12:01
2013-10-13 04:12:04
2014-12-14 04:12:05
2015-11-15 04:12:06
2016-10-15 04:12:07
And our task is to extract that seconds from given timestamps. So the output here will be:
seconds
1
4
5
6
7
Example 1 :
Python3
# importing the moduleimport pandas as pd # generating 10 timestamp starting from '2016-10-10 09:21:12'date1 = pd.Series(pd.date_range('2016-10-10 09:21:12', periods = 10, freq = 's')) # converting pandas series into data framedf = pd.DataFrame(dict(GENERATEDTIMESTAMP = date1)) # extracting seconds from time stampdf['extracted_seconds_timestamp'] = df['GENERATEDTIMESTAMP'].dt.second # displaying DataFramedisplay(df)
Output :
Example 2 :
Python3
# importing the moduleimport pandas as pd # generating 5 timestamp starting from '2020-01-01 00:00:00'date1 = pd.Series(pd.date_range('2020-01-01 00:00:00', periods = 5, freq = 's')) # converting pandas series into data framedf = pd.DataFrame(dict(GENERATEDTIMESTAMP = date1)) # extracting seconds from time stampdf['extracted_seconds_timestamp'] = df['GENERATEDTIMESTAMP'].dt.second # displaying DataFramedisplay(df)
Output :
ruhelaa48
simmytarika5
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 24322,
"s": 24294,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 24587,
"s": 24322,
"text": "In this program our task is to create a program in python which will extract seconds from a given timestamp. We will use the s attribute of the DateTime object to extract the second.Example : If we have a data frame that contains 5 different time stamps such as: "
},
{
"code": null,
"e": 24697,
"s": 24587,
"text": "Timestamp\n2012-12-11 04:12:01\n2013-10-13 04:12:04\n2014-12-14 04:12:05\n2015-11-15 04:12:06\n2016-10-15 04:12:07"
},
{
"code": null,
"e": 24790,
"s": 24697,
"text": "And our task is to extract that seconds from given timestamps. So the output here will be: "
},
{
"code": null,
"e": 24808,
"s": 24790,
"text": "seconds\n1\n4\n5\n6\n7"
},
{
"code": null,
"e": 24822,
"s": 24808,
"text": "Example 1 : "
},
{
"code": null,
"e": 24830,
"s": 24822,
"text": "Python3"
},
{
"code": "# importing the moduleimport pandas as pd # generating 10 timestamp starting from '2016-10-10 09:21:12'date1 = pd.Series(pd.date_range('2016-10-10 09:21:12', periods = 10, freq = 's')) # converting pandas series into data framedf = pd.DataFrame(dict(GENERATEDTIMESTAMP = date1)) # extracting seconds from time stampdf['extracted_seconds_timestamp'] = df['GENERATEDTIMESTAMP'].dt.second # displaying DataFramedisplay(df)",
"e": 25282,
"s": 24830,
"text": null
},
{
"code": null,
"e": 25293,
"s": 25282,
"text": "Output : "
},
{
"code": null,
"e": 25307,
"s": 25293,
"text": "Example 2 : "
},
{
"code": null,
"e": 25315,
"s": 25307,
"text": "Python3"
},
{
"code": "# importing the moduleimport pandas as pd # generating 5 timestamp starting from '2020-01-01 00:00:00'date1 = pd.Series(pd.date_range('2020-01-01 00:00:00', periods = 5, freq = 's')) # converting pandas series into data framedf = pd.DataFrame(dict(GENERATEDTIMESTAMP = date1)) # extracting seconds from time stampdf['extracted_seconds_timestamp'] = df['GENERATEDTIMESTAMP'].dt.second # displaying DataFramedisplay(df)",
"e": 25765,
"s": 25315,
"text": null
},
{
"code": null,
"e": 25776,
"s": 25765,
"text": "Output : "
},
{
"code": null,
"e": 25788,
"s": 25778,
"text": "ruhelaa48"
},
{
"code": null,
"e": 25801,
"s": 25788,
"text": "simmytarika5"
},
{
"code": null,
"e": 25825,
"s": 25801,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 25848,
"s": 25825,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 25862,
"s": 25848,
"text": "Python-pandas"
},
{
"code": null,
"e": 25869,
"s": 25862,
"text": "Python"
},
{
"code": null,
"e": 25967,
"s": 25869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25985,
"s": 25967,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26007,
"s": 25985,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26039,
"s": 26007,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26069,
"s": 26039,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26111,
"s": 26069,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26137,
"s": 26111,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26174,
"s": 26137,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26217,
"s": 26174,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26246,
"s": 26217,
"text": "*args and **kwargs in Python"
}
] |
Maximize sum of an Array by flipping sign of all elements of a single subarray - GeeksforGeeks
|
09 Nov, 2021
Given an array arr[] of N integers, the task is to find the maximum sum of the array that can be obtained by flipping signs of any subarray of the given array at most once.
Examples:
Input: arr[] = {-2, 3, -1, -4, -2} Output: 8Explanation: Flipping the signs of subarray {-1, -4, -2} modifies the array to {-2, 3, 1, 4, 2}. Therefore, the sum of the array = -2 + 3 + 1 + 4 + 2 = 8, which is the maximum possible.
Input: arr[] = {1, 2, -10, 2, -20}Output: 31 Explanation: Flipping the signs of subarray {-10, 2, -20} modifies the array to {1, 2, 10, -2, 20}. Therefore, the sum of the array = 1 + 2 + 10 – 2 + 20 = 31, which is the maximum possible.
Naive Approach: The simplest approach is to calculate the total sum of the array and then generate all possible subarrays. Now, for each subarray {A[i], ... A[j]}, subtract its sum, sum(A[i], ..., A[j]), from the total sum and flip the signs of the subarray elements. After flipping the subarray, add the sum of the flipped subarray, i.e. (-1 * sum(A[i], ..., A[j])), to the total sum. Below are the steps:
Find the total sum of the original array (say total_sum) and store it.Now, for all possible subarrays find the maximum of total_sum – 2 * sum(i, j).
Find the total sum of the original array (say total_sum) and store it.
Now, for all possible subarrays find the maximum of total_sum – 2 * sum(i, j).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum sum// after flipping a subarrayint maxSumFlip(int a[], int n){ // Stores the total sum of array int total_sum = 0; for (int i = 0; i < n; i++) total_sum += a[i]; // Initialize the maximum sum int max_sum = INT_MIN; // Iterate over all possible subarrays for (int i = 0; i < n; i++) { // Initialize sum of the subarray // before flipping sign int sum = 0; for (int j = i; j < n; j++) { // Calculate the sum of // original subarray sum += a[j]; // Subtract the original // subarray sum and add // the flipped subarray // sum to the total sum max_sum = max(max_sum, total_sum - 2 * sum); } } // Return the max_sum return max(max_sum, total_sum);} // Driver Codeint main(){ int arr[] = { -2, 3, -1, -4, -2 }; int N = sizeof(arr) / sizeof(int); cout << maxSumFlip(arr, N);} // This code is contributed by sanjoy_62
// Java program for the above approach import java.io.*; public class GFG{ // Function to find the maximum sum // after flipping a subarray public static int maxSumFlip(int a[], int n) { // Stores the total sum of array int total_sum = 0; for (int i = 0; i < n; i++) total_sum += a[i]; // Initialize the maximum sum int max_sum = Integer.MIN_VALUE; // Iterate over all possible subarrays for (int i = 0; i < n; i++) { // Initialize sum of the subarray // before flipping sign int sum = 0; for (int j = i; j < n; j++) { // Calculate the sum of // original subarray sum += a[j]; // Subtract the original // subarray sum and add // the flipped subarray // sum to the total sum max_sum = Math.max(max_sum, total_sum - 2 * sum); } } // Return the max_sum return Math.max(max_sum, total_sum); } // Driver Code public static void main(String args[]) { int arr[] = { -2, 3, -1, -4, -2 }; int N = arr.length; // Function call System.out.println(maxSumFlip(arr, N)); }}
# Python3 program for the above approachimport sys # Function to find the maximum sum# after flipping a subarray def maxSumFlip(a, n): # Stores the total sum of array total_sum = 0 for i in range(n): total_sum += a[i] # Initialize the maximum sum max_sum = -sys.maxsize - 1 # Iterate over all possible subarrays for i in range(n): # Initialize sum of the subarray # before flipping sign sum = 0 for j in range(i, n): # Calculate the sum of # original subarray sum += a[j] # Subtract the original # subarray sum and add # the flipped subarray # sum to the total sum max_sum = max(max_sum, total_sum - 2 * sum) # Return the max_sum return max(max_sum, total_sum) # Driver Codearr = [-2, 3, -1, -4, -2]N = len(arr) print(maxSumFlip(arr, N)) # This code is contributed by sanjoy_62
// C# program for the above approachusing System;class GFG { // Function to find the maximum sum // after flipping a subarray public static int maxSumFlip(int[] a, int n) { // Stores the total sum of array int total_sum = 0; for (int i = 0; i < n; i++) total_sum += a[i]; // Initialize the maximum sum int max_sum = int.MinValue; // Iterate over all possible subarrays for (int i = 0; i < n; i++) { // Initialize sum of the subarray // before flipping sign int sum = 0; for (int j = i; j < n; j++) { // Calculate the sum of // original subarray sum += a[j]; // Subtract the original // subarray sum and add // the flipped subarray // sum to the total sum max_sum = Math.Max(max_sum, total_sum - 2 * sum); } } // Return the max_sum return Math.Max(max_sum, total_sum); } // Driver Code public static void Main(String[] args) { int[] arr = { -2, 3, -1, -4, -2 }; int N = arr.Length; // Function call Console.WriteLine(maxSumFlip(arr, N)); }} // This code is contributed by 29AjayKumar
<script> // Javascript program to implement// the above approach // Function to find the maximum sum // after flipping a subarray function maxSumFlip(a, n) { // Find the total sum of array let total_sum = 0; for (let i = 0; i < n; i++) total_sum += a[i]; // Using Kadane's Algorithm let max_ending_here = -a[0] - a[0]; let curr_sum = -a[0] - a[0]; for (let i = 1; i < n; i++) { // Either extend previous // sub_array or start // new subarray curr_sum = Math.max(curr_sum + (-a[i] - a[i]), (-a[i] - a[i])); // Keep track of max_sum array max_ending_here = Math.max(max_ending_here, curr_sum); } // Add the sum to the total_sum let max_sum = total_sum + max_ending_here; // Check max_sum was maximum // with flip or without flip max_sum = Math.max(max_sum, total_sum); // Return max_sum return max_sum; } // Driver Code let arr = [ -2, 3, -1, -4, -2 ]; let N = arr.length; // Function Call document.write(maxSumFlip(arr, N)); </script>
8
Time Complexity: O(N2) Auxiliary Space: O(1)
Efficient Approach: From the above approach, it can be observed that, to obtain maximum array sum, (2 * subarray sum) needs to be maximized for all subarrays. This can be done by using Dynamic Programming. Below are the steps:
Find the minimum sum subarray from l[] using Kadane’s AlgorithmThis maximizes the contribution of (2 * sum) over all subarrays.Add the maximum contribution to the total sum of the array.
Find the minimum sum subarray from l[] using Kadane’s Algorithm
This maximizes the contribution of (2 * sum) over all subarrays.
Add the maximum contribution to the total sum of the array.
Below is the implementation of the above approach:
Python3
C++
def maxsum(l,n): total_sum=sum(l) #kadane's algorithm to find the minimum subarray sum current_sum=0 minimum_sum=0 for i in l: current_sum+=i minimum_sum=min(minimum_sum,current_sum) current_sum=min(current_sum,0) return max(total_sum,total_sum-2*minimum_sum)l=[-2,3,-1,-4,-2]n=len(l)print(maxsum(l,n))
#include <bits/stdc++.h>using namespace std; // Function to find the maximum sum// after flipping a subarrayint maxSumFlip(int a[], int n){ // Stores the total sum of array int total_sum = 0; for (int i = 0; i < n; i++) total_sum += a[i]; // Kadane's algorithm to find the minimum subarray sum int b,a=2e9; for (int i = 0; i < n; i++) { b+=ar[i]; if(a>b) a=b; if(b>0) b=0; } // Return the max_sum return max(total_sum,total_sum-2*a);} // Driver Codeint main(){ int arr[] = { -2, 3, -1, -4, -2 }; int N = sizeof(arr) / sizeof(int); cout << maxSumFlip(arr, N);}
8
Time Complexity: O(N) Auxiliary Space: O(1)Note: Can also be done by finding minimum subarray sum and print max(TotalSum, TotalSum-2*(minsubarraysum))
29AjayKumar
sanjoy_62
divyeshrabadiya07
yashk30
SURENDRA_GANGWAR
avijitmondal1998
surbhityagi15
vivekkancharla31416
discjockysubhra
Kadane
subarray
subarray-sum
subarray-sumsubarray
Arrays
Dynamic Programming
Mathematical
Arrays
Dynamic Programming
Mathematical
Kadane
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 24995,
"s": 24822,
"text": "Given an array arr[] of N integers, the task is to find the maximum sum of the array that can be obtained by flipping signs of any subarray of the given array at most once."
},
{
"code": null,
"e": 25005,
"s": 24995,
"text": "Examples:"
},
{
"code": null,
"e": 25235,
"s": 25005,
"text": "Input: arr[] = {-2, 3, -1, -4, -2} Output: 8Explanation: Flipping the signs of subarray {-1, -4, -2} modifies the array to {-2, 3, 1, 4, 2}. Therefore, the sum of the array = -2 + 3 + 1 + 4 + 2 = 8, which is the maximum possible."
},
{
"code": null,
"e": 25471,
"s": 25235,
"text": "Input: arr[] = {1, 2, -10, 2, -20}Output: 31 Explanation: Flipping the signs of subarray {-10, 2, -20} modifies the array to {1, 2, 10, -2, 20}. Therefore, the sum of the array = 1 + 2 + 10 – 2 + 20 = 31, which is the maximum possible."
},
{
"code": null,
"e": 25878,
"s": 25471,
"text": "Naive Approach: The simplest approach is to calculate the total sum of the array and then generate all possible subarrays. Now, for each subarray {A[i], ... A[j]}, subtract its sum, sum(A[i], ..., A[j]), from the total sum and flip the signs of the subarray elements. After flipping the subarray, add the sum of the flipped subarray, i.e. (-1 * sum(A[i], ..., A[j])), to the total sum. Below are the steps:"
},
{
"code": null,
"e": 26027,
"s": 25878,
"text": "Find the total sum of the original array (say total_sum) and store it.Now, for all possible subarrays find the maximum of total_sum – 2 * sum(i, j)."
},
{
"code": null,
"e": 26098,
"s": 26027,
"text": "Find the total sum of the original array (say total_sum) and store it."
},
{
"code": null,
"e": 26177,
"s": 26098,
"text": "Now, for all possible subarrays find the maximum of total_sum – 2 * sum(i, j)."
},
{
"code": null,
"e": 26228,
"s": 26177,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26232,
"s": 26228,
"text": "C++"
},
{
"code": null,
"e": 26237,
"s": 26232,
"text": "Java"
},
{
"code": null,
"e": 26245,
"s": 26237,
"text": "Python3"
},
{
"code": null,
"e": 26248,
"s": 26245,
"text": "C#"
},
{
"code": null,
"e": 26259,
"s": 26248,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum sum// after flipping a subarrayint maxSumFlip(int a[], int n){ // Stores the total sum of array int total_sum = 0; for (int i = 0; i < n; i++) total_sum += a[i]; // Initialize the maximum sum int max_sum = INT_MIN; // Iterate over all possible subarrays for (int i = 0; i < n; i++) { // Initialize sum of the subarray // before flipping sign int sum = 0; for (int j = i; j < n; j++) { // Calculate the sum of // original subarray sum += a[j]; // Subtract the original // subarray sum and add // the flipped subarray // sum to the total sum max_sum = max(max_sum, total_sum - 2 * sum); } } // Return the max_sum return max(max_sum, total_sum);} // Driver Codeint main(){ int arr[] = { -2, 3, -1, -4, -2 }; int N = sizeof(arr) / sizeof(int); cout << maxSumFlip(arr, N);} // This code is contributed by sanjoy_62",
"e": 27369,
"s": 26259,
"text": null
},
{
"code": "// Java program for the above approach import java.io.*; public class GFG{ // Function to find the maximum sum // after flipping a subarray public static int maxSumFlip(int a[], int n) { // Stores the total sum of array int total_sum = 0; for (int i = 0; i < n; i++) total_sum += a[i]; // Initialize the maximum sum int max_sum = Integer.MIN_VALUE; // Iterate over all possible subarrays for (int i = 0; i < n; i++) { // Initialize sum of the subarray // before flipping sign int sum = 0; for (int j = i; j < n; j++) { // Calculate the sum of // original subarray sum += a[j]; // Subtract the original // subarray sum and add // the flipped subarray // sum to the total sum max_sum = Math.max(max_sum, total_sum - 2 * sum); } } // Return the max_sum return Math.max(max_sum, total_sum); } // Driver Code public static void main(String args[]) { int arr[] = { -2, 3, -1, -4, -2 }; int N = arr.length; // Function call System.out.println(maxSumFlip(arr, N)); }}",
"e": 28705,
"s": 27369,
"text": null
},
{
"code": "# Python3 program for the above approachimport sys # Function to find the maximum sum# after flipping a subarray def maxSumFlip(a, n): # Stores the total sum of array total_sum = 0 for i in range(n): total_sum += a[i] # Initialize the maximum sum max_sum = -sys.maxsize - 1 # Iterate over all possible subarrays for i in range(n): # Initialize sum of the subarray # before flipping sign sum = 0 for j in range(i, n): # Calculate the sum of # original subarray sum += a[j] # Subtract the original # subarray sum and add # the flipped subarray # sum to the total sum max_sum = max(max_sum, total_sum - 2 * sum) # Return the max_sum return max(max_sum, total_sum) # Driver Codearr = [-2, 3, -1, -4, -2]N = len(arr) print(maxSumFlip(arr, N)) # This code is contributed by sanjoy_62",
"e": 29668,
"s": 28705,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG { // Function to find the maximum sum // after flipping a subarray public static int maxSumFlip(int[] a, int n) { // Stores the total sum of array int total_sum = 0; for (int i = 0; i < n; i++) total_sum += a[i]; // Initialize the maximum sum int max_sum = int.MinValue; // Iterate over all possible subarrays for (int i = 0; i < n; i++) { // Initialize sum of the subarray // before flipping sign int sum = 0; for (int j = i; j < n; j++) { // Calculate the sum of // original subarray sum += a[j]; // Subtract the original // subarray sum and add // the flipped subarray // sum to the total sum max_sum = Math.Max(max_sum, total_sum - 2 * sum); } } // Return the max_sum return Math.Max(max_sum, total_sum); } // Driver Code public static void Main(String[] args) { int[] arr = { -2, 3, -1, -4, -2 }; int N = arr.Length; // Function call Console.WriteLine(maxSumFlip(arr, N)); }} // This code is contributed by 29AjayKumar",
"e": 31023,
"s": 29668,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to find the maximum sum // after flipping a subarray function maxSumFlip(a, n) { // Find the total sum of array let total_sum = 0; for (let i = 0; i < n; i++) total_sum += a[i]; // Using Kadane's Algorithm let max_ending_here = -a[0] - a[0]; let curr_sum = -a[0] - a[0]; for (let i = 1; i < n; i++) { // Either extend previous // sub_array or start // new subarray curr_sum = Math.max(curr_sum + (-a[i] - a[i]), (-a[i] - a[i])); // Keep track of max_sum array max_ending_here = Math.max(max_ending_here, curr_sum); } // Add the sum to the total_sum let max_sum = total_sum + max_ending_here; // Check max_sum was maximum // with flip or without flip max_sum = Math.max(max_sum, total_sum); // Return max_sum return max_sum; } // Driver Code let arr = [ -2, 3, -1, -4, -2 ]; let N = arr.length; // Function Call document.write(maxSumFlip(arr, N)); </script>",
"e": 32269,
"s": 31023,
"text": null
},
{
"code": null,
"e": 32271,
"s": 32269,
"text": "8"
},
{
"code": null,
"e": 32316,
"s": 32271,
"text": "Time Complexity: O(N2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32543,
"s": 32316,
"text": "Efficient Approach: From the above approach, it can be observed that, to obtain maximum array sum, (2 * subarray sum) needs to be maximized for all subarrays. This can be done by using Dynamic Programming. Below are the steps:"
},
{
"code": null,
"e": 32730,
"s": 32543,
"text": "Find the minimum sum subarray from l[] using Kadane’s AlgorithmThis maximizes the contribution of (2 * sum) over all subarrays.Add the maximum contribution to the total sum of the array."
},
{
"code": null,
"e": 32794,
"s": 32730,
"text": "Find the minimum sum subarray from l[] using Kadane’s Algorithm"
},
{
"code": null,
"e": 32859,
"s": 32794,
"text": "This maximizes the contribution of (2 * sum) over all subarrays."
},
{
"code": null,
"e": 32919,
"s": 32859,
"text": "Add the maximum contribution to the total sum of the array."
},
{
"code": null,
"e": 32970,
"s": 32919,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 32978,
"s": 32970,
"text": "Python3"
},
{
"code": null,
"e": 32982,
"s": 32978,
"text": "C++"
},
{
"code": "def maxsum(l,n): total_sum=sum(l) #kadane's algorithm to find the minimum subarray sum current_sum=0 minimum_sum=0 for i in l: current_sum+=i minimum_sum=min(minimum_sum,current_sum) current_sum=min(current_sum,0) return max(total_sum,total_sum-2*minimum_sum)l=[-2,3,-1,-4,-2]n=len(l)print(maxsum(l,n))",
"e": 33300,
"s": 32982,
"text": null
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Function to find the maximum sum// after flipping a subarrayint maxSumFlip(int a[], int n){ // Stores the total sum of array int total_sum = 0; for (int i = 0; i < n; i++) total_sum += a[i]; // Kadane's algorithm to find the minimum subarray sum int b,a=2e9; for (int i = 0; i < n; i++) { b+=ar[i]; if(a>b) a=b; if(b>0) b=0; } // Return the max_sum return max(total_sum,total_sum-2*a);} // Driver Codeint main(){ int arr[] = { -2, 3, -1, -4, -2 }; int N = sizeof(arr) / sizeof(int); cout << maxSumFlip(arr, N);}",
"e": 33955,
"s": 33300,
"text": null
},
{
"code": null,
"e": 33958,
"s": 33955,
"text": "8\n"
},
{
"code": null,
"e": 34109,
"s": 33958,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)Note: Can also be done by finding minimum subarray sum and print max(TotalSum, TotalSum-2*(minsubarraysum))"
},
{
"code": null,
"e": 34121,
"s": 34109,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34131,
"s": 34121,
"text": "sanjoy_62"
},
{
"code": null,
"e": 34149,
"s": 34131,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 34157,
"s": 34149,
"text": "yashk30"
},
{
"code": null,
"e": 34174,
"s": 34157,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 34191,
"s": 34174,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 34205,
"s": 34191,
"text": "surbhityagi15"
},
{
"code": null,
"e": 34225,
"s": 34205,
"text": "vivekkancharla31416"
},
{
"code": null,
"e": 34241,
"s": 34225,
"text": "discjockysubhra"
},
{
"code": null,
"e": 34248,
"s": 34241,
"text": "Kadane"
},
{
"code": null,
"e": 34257,
"s": 34248,
"text": "subarray"
},
{
"code": null,
"e": 34270,
"s": 34257,
"text": "subarray-sum"
},
{
"code": null,
"e": 34291,
"s": 34270,
"text": "subarray-sumsubarray"
},
{
"code": null,
"e": 34298,
"s": 34291,
"text": "Arrays"
},
{
"code": null,
"e": 34318,
"s": 34298,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34331,
"s": 34318,
"text": "Mathematical"
},
{
"code": null,
"e": 34338,
"s": 34331,
"text": "Arrays"
},
{
"code": null,
"e": 34358,
"s": 34338,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34371,
"s": 34358,
"text": "Mathematical"
},
{
"code": null,
"e": 34378,
"s": 34371,
"text": "Kadane"
},
{
"code": null,
"e": 34476,
"s": 34378,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34501,
"s": 34476,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34521,
"s": 34501,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 34559,
"s": 34521,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34644,
"s": 34559,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 34693,
"s": 34644,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34722,
"s": 34693,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 34752,
"s": 34722,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34786,
"s": 34752,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 34817,
"s": 34786,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
Multiply two polynomials | Practice | GeeksforGeeks
|
Given two polynomials represented by two arrays that contains the coefficients of poynomials, returns the polynomial in form of array formed after multiplication of given polynomials.
Example 1:
Input:
M = 4, N = 3
Arr1 = {1 , 0, 3, 2}
Arr2 = {2, 0, 4}
Output: {2, 0, 10, 4, 12, 8}
Explaination:
First polynomial:
1 + 0x1 + 3x2 + 2x3
Second polynomial:
2 + 0x1 + 4x2
Product polynomial:
2 + 0x1 + 10x2 + 4x3 + 12x4 + 8x5
Example 2:
Input:
M = 5, N = 4
Arr1 = {1, 9, 3, 4, 7}
Arr1 = {4, 0, 2, 5}
Output: {4, 36, 14, 39, 79, 23, 34, 35}
Explaination:
First polynomial:
1 + 9x1 + 3x2 + 4x3 + 7x4
Second polynomial:
4 + 0x1 + 2x2 + 5x3
Product polynomial:
4 + 36x1 + 14x2 + 39x3 + 79x4 + 23x5 + 34x6 + 35x7
Your Task:
You don't need to read input or print anything. Your task is to complete the function polyMultiply() which takes the array Arr1[] and Arr2[]and their size M and N as input parameters and returns the polynomial in form of array formed after multiplication of given polynomials..
Expected Time Complexity: O(M*N)
Expected Auxiliary Space: O(M+N)
Constraints:
1 ≤ M, N ≤ 100
1 ≤ Arr1[i] , Arr2[i] ≤ 100
+1
shivi13verma3 months ago
return numpy.polymul(Arr1,Arr2)
0
harshakarimikonda223 months ago
vector<int> arr; for(int i=0;i<M+N;i++) arr.push_back(0); int index=0; for(int i=0;i<M;i++){ for(int j=0;j<N;j++){ int mul=Arr1[i]*Arr2[j]; index=i+j; int sum=arr[index]+mul; arr[index]=sum; } } return arr;
0
mohankrishnapeddineni3 months ago
class Solution{ public int[] polyMultiply(int Arr1[], int Arr2[], int M, int N) { int arr[]= new int[M+N-1]; for(int i=0;i<M;i++) { for(int j=0;j<N;j++) { arr[i+j]+= Arr1[i]*Arr2[j]; } } return arr; }}
-1
avinav26113 months ago
Easy C++ Solution
0
ritikyadavr113 months ago
vector<int>polyMultiply(int Arr1[], int Arr2[], int M, int N) { // code here vector<int>ans(N+M); int index = 0; for(int i=0; i<M; i++){ for(int j=0; j<N; j++){ int mul = Arr1[i] * Arr2[j]; index = i+j; int sum = ans[index] + mul; ans[index] = sum; } } return ans; }
0
mohitkumar423 months ago
java solution
class Solution{ public int[] polyMultiply(int Arr1[], int Arr2[], int M, int N) { int arr[] = new int[M+N-1]; int k =0; for(int i =0;i<M;i++) { for(int j =0;j<N;j++) { if(i==0) {arr[k]=Arr1[i]*Arr2[j]; k++;} else arr[i+j]= arr[i+j]+ Arr1[i]*Arr2[j]; } } return arr; }}
+1
swapniltayal4224 months ago
import numpy as npclass Solution:def polyMultiply(self, Arr1, Arr2, M, N): return np.polymul(Arr1, Arr2)
😑😑0.1sec
0
mashhadihossain5 months ago
SIMPLE JAVA SOLUTION (0.4 sec)
int value(int ans[][],int k) { int sum=0; for(int i=0;i<ans.length;i++) { for(int j=0;j<ans[i].length;j++) { if(i+j==k) { sum+=ans[i][j]; } } } return sum; } public int[] polyMultiply(int Arr1[], int Arr2[], int M, int N) { int ans[][]=new int[M][N]; for(int i=0;i<M;i++) { for(int j=0;j<N;j++) { ans[i][j]=Arr1[i]*Arr2[j]; } } int a[]=new int[M+N-1]; for(int i=0;i<a.length;i++) { a[i]=value(ans,i); } return a; }
0
e20040806 months ago
runtime: 0.1/16.1
import numpy as np
class Solution:
def polyMultiply(self, Arr1, Arr2, M, N):
return np.polymul(Arr1, Arr2)
0
deepikaballa137 months ago
for(int i=0;i<M;i++){ for(int j=0;j<N;j++){ arr[i+j]=arr[i+j]+Arr1[i]*Arr2[j]; } }
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": 422,
"s": 238,
"text": "Given two polynomials represented by two arrays that contains the coefficients of poynomials, returns the polynomial in form of array formed after multiplication of given polynomials."
},
{
"code": null,
"e": 434,
"s": 422,
"text": "\nExample 1:"
},
{
"code": null,
"e": 663,
"s": 434,
"text": "Input:\nM = 4, N = 3\nArr1 = {1 , 0, 3, 2}\nArr2 = {2, 0, 4}\nOutput: {2, 0, 10, 4, 12, 8}\nExplaination: \nFirst polynomial: \n1 + 0x1 + 3x2 + 2x3\nSecond polynomial: \n2 + 0x1 + 4x2\nProduct polynomial:\n2 + 0x1 + 10x2 + 4x3 + 12x4 + 8x5"
},
{
"code": null,
"e": 675,
"s": 663,
"text": "\nExample 2:"
},
{
"code": null,
"e": 950,
"s": 675,
"text": "Input:\nM = 5, N = 4\nArr1 = {1, 9, 3, 4, 7}\nArr1 = {4, 0, 2, 5}\nOutput: {4, 36, 14, 39, 79, 23, 34, 35}\nExplaination: \nFirst polynomial: \n1 + 9x1 + 3x2 + 4x3 + 7x4\nSecond polynomial: \n4 + 0x1 + 2x2 + 5x3\nProduct polynomial:\n4 + 36x1 + 14x2 + 39x3 + 79x4 + 23x5 + 34x6 + 35x7\n"
},
{
"code": null,
"e": 1240,
"s": 950,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function polyMultiply() which takes the array Arr1[] and Arr2[]and their size M and N as input parameters and returns the polynomial in form of array formed after multiplication of given polynomials.."
},
{
"code": null,
"e": 1307,
"s": 1240,
"text": "\nExpected Time Complexity: O(M*N)\nExpected Auxiliary Space: O(M+N)"
},
{
"code": null,
"e": 1366,
"s": 1307,
"text": "\nConstraints:\n1 ≤ M, N ≤ 100\n1 ≤ Arr1[i] , Arr2[i] ≤ 100"
},
{
"code": null,
"e": 1369,
"s": 1366,
"text": "+1"
},
{
"code": null,
"e": 1394,
"s": 1369,
"text": "shivi13verma3 months ago"
},
{
"code": null,
"e": 1426,
"s": 1394,
"text": "return numpy.polymul(Arr1,Arr2)"
},
{
"code": null,
"e": 1428,
"s": 1426,
"text": "0"
},
{
"code": null,
"e": 1460,
"s": 1428,
"text": "harshakarimikonda223 months ago"
},
{
"code": null,
"e": 1779,
"s": 1460,
"text": "vector<int> arr; for(int i=0;i<M+N;i++) arr.push_back(0); int index=0; for(int i=0;i<M;i++){ for(int j=0;j<N;j++){ int mul=Arr1[i]*Arr2[j]; index=i+j; int sum=arr[index]+mul; arr[index]=sum; } } return arr;"
},
{
"code": null,
"e": 1781,
"s": 1779,
"text": "0"
},
{
"code": null,
"e": 1815,
"s": 1781,
"text": "mohankrishnapeddineni3 months ago"
},
{
"code": null,
"e": 2101,
"s": 1815,
"text": "class Solution{ public int[] polyMultiply(int Arr1[], int Arr2[], int M, int N) { int arr[]= new int[M+N-1]; for(int i=0;i<M;i++) { for(int j=0;j<N;j++) { arr[i+j]+= Arr1[i]*Arr2[j]; } } return arr; }}"
},
{
"code": null,
"e": 2104,
"s": 2101,
"text": "-1"
},
{
"code": null,
"e": 2127,
"s": 2104,
"text": "avinav26113 months ago"
},
{
"code": null,
"e": 2145,
"s": 2127,
"text": "Easy C++ Solution"
},
{
"code": null,
"e": 2149,
"s": 2147,
"text": "0"
},
{
"code": null,
"e": 2175,
"s": 2149,
"text": "ritikyadavr113 months ago"
},
{
"code": null,
"e": 2562,
"s": 2175,
"text": " vector<int>polyMultiply(int Arr1[], int Arr2[], int M, int N) { // code here vector<int>ans(N+M); int index = 0; for(int i=0; i<M; i++){ for(int j=0; j<N; j++){ int mul = Arr1[i] * Arr2[j]; index = i+j; int sum = ans[index] + mul; ans[index] = sum; } } return ans; }"
},
{
"code": null,
"e": 2564,
"s": 2562,
"text": "0"
},
{
"code": null,
"e": 2589,
"s": 2564,
"text": "mohitkumar423 months ago"
},
{
"code": null,
"e": 2604,
"s": 2589,
"text": "java solution "
},
{
"code": null,
"e": 3007,
"s": 2608,
"text": "class Solution{ public int[] polyMultiply(int Arr1[], int Arr2[], int M, int N) { int arr[] = new int[M+N-1]; int k =0; for(int i =0;i<M;i++) { for(int j =0;j<N;j++) { if(i==0) {arr[k]=Arr1[i]*Arr2[j]; k++;} else arr[i+j]= arr[i+j]+ Arr1[i]*Arr2[j]; } } return arr; }}"
},
{
"code": null,
"e": 3010,
"s": 3007,
"text": "+1"
},
{
"code": null,
"e": 3038,
"s": 3010,
"text": "swapniltayal4224 months ago"
},
{
"code": null,
"e": 3143,
"s": 3038,
"text": "import numpy as npclass Solution:def polyMultiply(self, Arr1, Arr2, M, N): return np.polymul(Arr1, Arr2)"
},
{
"code": null,
"e": 3156,
"s": 3147,
"text": "😑😑0.1sec"
},
{
"code": null,
"e": 3160,
"s": 3158,
"text": "0"
},
{
"code": null,
"e": 3188,
"s": 3160,
"text": "mashhadihossain5 months ago"
},
{
"code": null,
"e": 3219,
"s": 3188,
"text": "SIMPLE JAVA SOLUTION (0.4 sec)"
},
{
"code": null,
"e": 3889,
"s": 3219,
"text": "int value(int ans[][],int k) { int sum=0; for(int i=0;i<ans.length;i++) { for(int j=0;j<ans[i].length;j++) { if(i+j==k) { sum+=ans[i][j]; } } } return sum; } public int[] polyMultiply(int Arr1[], int Arr2[], int M, int N) { int ans[][]=new int[M][N]; for(int i=0;i<M;i++) { for(int j=0;j<N;j++) { ans[i][j]=Arr1[i]*Arr2[j]; } } int a[]=new int[M+N-1]; for(int i=0;i<a.length;i++) { a[i]=value(ans,i); } return a; }"
},
{
"code": null,
"e": 3891,
"s": 3889,
"text": "0"
},
{
"code": null,
"e": 3912,
"s": 3891,
"text": "e20040806 months ago"
},
{
"code": null,
"e": 3930,
"s": 3912,
"text": "runtime: 0.1/16.1"
},
{
"code": null,
"e": 4040,
"s": 3930,
"text": "import numpy as np\nclass Solution:\n\tdef polyMultiply(self, Arr1, Arr2, M, N):\n\t\treturn np.polymul(Arr1, Arr2)"
},
{
"code": null,
"e": 4042,
"s": 4040,
"text": "0"
},
{
"code": null,
"e": 4069,
"s": 4042,
"text": "deepikaballa137 months ago"
},
{
"code": null,
"e": 4184,
"s": 4069,
"text": "for(int i=0;i<M;i++){ for(int j=0;j<N;j++){ arr[i+j]=arr[i+j]+Arr1[i]*Arr2[j]; } }"
},
{
"code": null,
"e": 4330,
"s": 4184,
"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": 4366,
"s": 4330,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4376,
"s": 4366,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4386,
"s": 4376,
"text": "\nContest\n"
},
{
"code": null,
"e": 4449,
"s": 4386,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4597,
"s": 4449,
"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": 4805,
"s": 4597,
"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": 4911,
"s": 4805,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Event Handling in Matplotlib - GeeksforGeeks
|
18 Oct, 2021
Event based System usually is part of a recurring set of patterns. Often, they comprise of the following :
An incoming event
A mechanism that is used to respond to an event
A looping construct (e.g. while loop, listener, and the message dispatch mechanism)
The events that are triggered are also a bit richer, including information like which Axes the event occurred in. The events also understand the Matplotlib coordinate system and report event locations in both pixel and data coordinates.
Syntax:
figure.canvas.mpl_connect( Event_name , callback function or method)
Parameters:
Event_name: It could be any from the below table
callback_function: It will define to handle the event.
Note: That the classes are defined in matplotlib.backend_bases
button_press_event: This event involves a mouse button press
button_release_event: This event involves a mouse button release
scroll_event: This event involves scrolling of the mouse
motion_notify_event: This event involves a notification pertaining to the mouse movement
Example:
We have used the mpl_connect method, which must be called if you want to provide custom user interaction features along with your plots. This method will take two arguments:
A string value for the event, which can be any of the values listed in the Event Name column of the preceding table
A callback function or method
Python3
# importing the necessary modulesfrom IPython.display import Imageimport matplotlib.pyplot as pltimport matplotlib as mplimport numpy as npimport timeimport sysimport randomimport matplotlibmatplotlib.use('nbagg') class MouseEvent: # initialization def __init__(self): (figure, axes) = plt.subplots() axes.set_aspect(1) figure.canvas.mpl_connect('button_press_event', self.press) figure.canvas.mpl_connect('button_release_event', self.release) # start event to show the plot def start(self): plt.show() # display the plot # press event will keep the starting time when u # press mouse button def press(self, event): self.start_time = time.time() # release event will keep the track when you release # mouse button def release(self, event): self.end_time = time.time() self.draw_click(event) # drawing the plot def draw_click(self, event): # size = square (4 * duration of the time button # is keep pressed ) size = 4 * (self.end_time - self.start_time) ** 2 # create a point of size=0.002 where mouse button # clicked on the plot c1 = plt.Circle([event.xdata, event.ydata], 0.002,) # create a circle of radius 0.02*size c2 = plt.Circle([event.xdata, event.ydata], 0.02 * size, alpha=0.2) event.canvas.figure.gca().add_artist(c1) event.canvas.figure.gca().add_artist(c2) event.canvas.figure.show() cbs = MouseEvent() # start the eventcbs.start()
Output :
Example 2:
We are going to add color using the draw_click method
Python3
def draw_click(self, event): # you can specified your own color list col = ['magneta', 'lavender', 'salmon', 'yellow', 'orange'] cn = random.randint(0, 5) # size = square (4 * duration of the time button # is keep pressed ) size = 4 * (self.end_time - self.start_time) ** 2 # create a point of size=0.002 where mouse button # clicked on the plot c1 = plt.Circle([event.xdata, event.ydata], 0.002,) # create a circle of radius 0.02*size c2 = plt.Circle([event.xdata, event.ydata], 0.02 * size, alpha=0.2, color=col[cn]) event.canvas.figure.gca().add_artist(c1) event.canvas.figure.gca().add_artist(c2) event.canvas.figure.show()
Output:
Picked
Python-matplotlib
TrueGeek-2021
Python
TrueGeek
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
Check if element exists in list in Python
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
Types of Internet Protocols
Basics of API Testing Using Postman
Data Communication - Definition, Components, Types, Channels
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 24399,
"s": 24292,
"text": "Event based System usually is part of a recurring set of patterns. Often, they comprise of the following :"
},
{
"code": null,
"e": 24417,
"s": 24399,
"text": "An incoming event"
},
{
"code": null,
"e": 24465,
"s": 24417,
"text": "A mechanism that is used to respond to an event"
},
{
"code": null,
"e": 24549,
"s": 24465,
"text": "A looping construct (e.g. while loop, listener, and the message dispatch mechanism)"
},
{
"code": null,
"e": 24786,
"s": 24549,
"text": "The events that are triggered are also a bit richer, including information like which Axes the event occurred in. The events also understand the Matplotlib coordinate system and report event locations in both pixel and data coordinates."
},
{
"code": null,
"e": 24794,
"s": 24786,
"text": "Syntax:"
},
{
"code": null,
"e": 24863,
"s": 24794,
"text": "figure.canvas.mpl_connect( Event_name , callback function or method)"
},
{
"code": null,
"e": 24875,
"s": 24863,
"text": "Parameters:"
},
{
"code": null,
"e": 24924,
"s": 24875,
"text": "Event_name: It could be any from the below table"
},
{
"code": null,
"e": 24979,
"s": 24924,
"text": "callback_function: It will define to handle the event."
},
{
"code": null,
"e": 25042,
"s": 24979,
"text": "Note: That the classes are defined in matplotlib.backend_bases"
},
{
"code": null,
"e": 25103,
"s": 25042,
"text": "button_press_event: This event involves a mouse button press"
},
{
"code": null,
"e": 25168,
"s": 25103,
"text": "button_release_event: This event involves a mouse button release"
},
{
"code": null,
"e": 25225,
"s": 25168,
"text": "scroll_event: This event involves scrolling of the mouse"
},
{
"code": null,
"e": 25314,
"s": 25225,
"text": "motion_notify_event: This event involves a notification pertaining to the mouse movement"
},
{
"code": null,
"e": 25323,
"s": 25314,
"text": "Example:"
},
{
"code": null,
"e": 25497,
"s": 25323,
"text": "We have used the mpl_connect method, which must be called if you want to provide custom user interaction features along with your plots. This method will take two arguments:"
},
{
"code": null,
"e": 25613,
"s": 25497,
"text": "A string value for the event, which can be any of the values listed in the Event Name column of the preceding table"
},
{
"code": null,
"e": 25643,
"s": 25613,
"text": "A callback function or method"
},
{
"code": null,
"e": 25651,
"s": 25643,
"text": "Python3"
},
{
"code": "# importing the necessary modulesfrom IPython.display import Imageimport matplotlib.pyplot as pltimport matplotlib as mplimport numpy as npimport timeimport sysimport randomimport matplotlibmatplotlib.use('nbagg') class MouseEvent: # initialization def __init__(self): (figure, axes) = plt.subplots() axes.set_aspect(1) figure.canvas.mpl_connect('button_press_event', self.press) figure.canvas.mpl_connect('button_release_event', self.release) # start event to show the plot def start(self): plt.show() # display the plot # press event will keep the starting time when u # press mouse button def press(self, event): self.start_time = time.time() # release event will keep the track when you release # mouse button def release(self, event): self.end_time = time.time() self.draw_click(event) # drawing the plot def draw_click(self, event): # size = square (4 * duration of the time button # is keep pressed ) size = 4 * (self.end_time - self.start_time) ** 2 # create a point of size=0.002 where mouse button # clicked on the plot c1 = plt.Circle([event.xdata, event.ydata], 0.002,) # create a circle of radius 0.02*size c2 = plt.Circle([event.xdata, event.ydata], 0.02 * size, alpha=0.2) event.canvas.figure.gca().add_artist(c1) event.canvas.figure.gca().add_artist(c2) event.canvas.figure.show() cbs = MouseEvent() # start the eventcbs.start()",
"e": 27208,
"s": 25651,
"text": null
},
{
"code": null,
"e": 27217,
"s": 27208,
"text": "Output :"
},
{
"code": null,
"e": 27228,
"s": 27217,
"text": "Example 2:"
},
{
"code": null,
"e": 27283,
"s": 27228,
"text": "We are going to add color using the draw_click method"
},
{
"code": null,
"e": 27291,
"s": 27283,
"text": "Python3"
},
{
"code": "def draw_click(self, event): # you can specified your own color list col = ['magneta', 'lavender', 'salmon', 'yellow', 'orange'] cn = random.randint(0, 5) # size = square (4 * duration of the time button # is keep pressed ) size = 4 * (self.end_time - self.start_time) ** 2 # create a point of size=0.002 where mouse button # clicked on the plot c1 = plt.Circle([event.xdata, event.ydata], 0.002,) # create a circle of radius 0.02*size c2 = plt.Circle([event.xdata, event.ydata], 0.02 * size, alpha=0.2, color=col[cn]) event.canvas.figure.gca().add_artist(c1) event.canvas.figure.gca().add_artist(c2) event.canvas.figure.show()",
"e": 28004,
"s": 27291,
"text": null
},
{
"code": null,
"e": 28012,
"s": 28004,
"text": "Output:"
},
{
"code": null,
"e": 28019,
"s": 28012,
"text": "Picked"
},
{
"code": null,
"e": 28037,
"s": 28019,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28051,
"s": 28037,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 28058,
"s": 28051,
"text": "Python"
},
{
"code": null,
"e": 28067,
"s": 28058,
"text": "TrueGeek"
},
{
"code": null,
"e": 28165,
"s": 28067,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28197,
"s": 28165,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28253,
"s": 28197,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28295,
"s": 28253,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28350,
"s": 28295,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28392,
"s": 28350,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28437,
"s": 28392,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 28494,
"s": 28437,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 28522,
"s": 28494,
"text": "Types of Internet Protocols"
},
{
"code": null,
"e": 28558,
"s": 28522,
"text": "Basics of API Testing Using Postman"
}
] |
Python Program to Implement Queues using Stacks
|
When it is required to implement a queue using a stack, a queue class can be defined, where two stack instances can be defined. Different operations can be performed on the queue that are defined as methods in this class.
Below is a demonstration of the same −
Live Demo
class Queue_structure:
def __init__(self):
self.in_val = Stack_structure()
self.out_val = Stack_structure()
def check_empty(self):
return (self.in_val.check_empty() and self.out_val.check_empty())
def enqueue_operation(self, data):
self.in_val.push_operation(data)
def dequeue_operation(self):
if self.out_val.check_empty():
while not self.in_val.check_empty():
deleted_val = self.in_val.pop_operation()
self.out_val.push_operation(deleted_val)
return self.out_val.pop_operation()
class Stack_structure:
def __init__(self):
self.items = []
def check_empty(self):
return self.items == []
def push_operation(self, data):
self.items.append(data)
def pop_operation(self):
return self.items.pop()
my_instance = Queue_structure()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
my_input = input('What operation would you like to perform ?').split()
operation = my_input[0].strip().lower()
if operation == 'enqueue':
my_instance.enqueue_operation(int(my_input[1]))
elif operation == 'dequeue':
if my_instance.check_empty():
print('The queue is empty')
else:
deleted_elem = my_instance.dequeue_operation()
print('The deleted element is : ', int(deleted_elem))
elif operation == 'quit':
break
enqueue <value>
dequeue
quit
What operation would you like to perform ?enqueue 45
enqueue <value>
dequeue
quit
What operation would you like to perform ?enqueue 23
enqueue <value>
dequeue
quit
What operation would you like to perform ?enqueue 78
enqueue <value>
dequeue
quit
What operation would you like to perform ?dequeue
The deleted element is : 45
enqueue <value>
dequeue
quit
What operation would you like to perform ?quit
A ‘Queue_structure’ is defined, that defines two instances of Stack.
A ‘Queue_structure’ is defined, that defines two instances of Stack.
It has a method named ‘check_empty’ that checks to see if the queue is empty.
It has a method named ‘check_empty’ that checks to see if the queue is empty.
Another method named ‘enqueue_operation’ is defined, that helps add elements to the queue.
Another method named ‘enqueue_operation’ is defined, that helps add elements to the queue.
Another method named ‘dequeue_operation’ is defined, that deletes an element from the queue.
Another method named ‘dequeue_operation’ is defined, that deletes an element from the queue.
Another ‘Stack_structure’ class is created.
Another ‘Stack_structure’ class is created.
It initializes an empty list.
It initializes an empty list.
It has a method named ‘check_empty’ that checks to see if the stack is empty.
It has a method named ‘check_empty’ that checks to see if the stack is empty.
Another method named ‘push_operation’ is defined, that helps add elements to the queue.
Another method named ‘push_operation’ is defined, that helps add elements to the queue.
Another method named ‘pop_operation’ is defined, that deletes an element from the queue.
Another method named ‘pop_operation’ is defined, that deletes an element from the queue.
A ‘Queue_structure’ instance is created.
A ‘Queue_structure’ instance is created.
Three options are given- enqueue, dequeue, and quit.
Three options are given- enqueue, dequeue, and quit.
Based on the option given by user, the operations are performed, and relevant output is displayed on the console.
Based on the option given by user, the operations are performed, and relevant output is displayed on the console.
|
[
{
"code": null,
"e": 1284,
"s": 1062,
"text": "When it is required to implement a queue using a stack, a queue class can be defined, where two stack instances can be defined. Different operations can be performed on the queue that are defined as methods in this class."
},
{
"code": null,
"e": 1323,
"s": 1284,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1334,
"s": 1323,
"text": " Live Demo"
},
{
"code": null,
"e": 2740,
"s": 1334,
"text": "class Queue_structure:\n def __init__(self):\n self.in_val = Stack_structure()\n self.out_val = Stack_structure()\n\n def check_empty(self):\n return (self.in_val.check_empty() and self.out_val.check_empty())\n\n def enqueue_operation(self, data):\n self.in_val.push_operation(data)\n\n def dequeue_operation(self):\n if self.out_val.check_empty():\n while not self.in_val.check_empty():\n deleted_val = self.in_val.pop_operation()\n self.out_val.push_operation(deleted_val)\n return self.out_val.pop_operation()\n\nclass Stack_structure:\n def __init__(self):\n self.items = []\n\n def check_empty(self):\n return self.items == []\n\n def push_operation(self, data):\n self.items.append(data)\n\n def pop_operation(self):\n return self.items.pop()\n\nmy_instance = Queue_structure()\n\nwhile True:\n print('enqueue <value>')\n print('dequeue')\n print('quit')\n my_input = input('What operation would you like to perform ?').split()\n\n operation = my_input[0].strip().lower()\n if operation == 'enqueue':\n my_instance.enqueue_operation(int(my_input[1]))\n elif operation == 'dequeue':\n if my_instance.check_empty():\n print('The queue is empty')\n else:\n deleted_elem = my_instance.dequeue_operation()\n print('The deleted element is : ', int(deleted_elem))\n elif operation == 'quit':\n break"
},
{
"code": null,
"e": 3169,
"s": 2740,
"text": "enqueue <value>\ndequeue\nquit\nWhat operation would you like to perform ?enqueue 45\nenqueue <value>\ndequeue\nquit\nWhat operation would you like to perform ?enqueue 23\nenqueue <value>\ndequeue\nquit\nWhat operation would you like to perform ?enqueue 78\nenqueue <value>\ndequeue\nquit\nWhat operation would you like to perform ?dequeue\nThe deleted element is : 45\nenqueue <value>\ndequeue\nquit\nWhat operation would you like to perform ?quit"
},
{
"code": null,
"e": 3238,
"s": 3169,
"text": "A ‘Queue_structure’ is defined, that defines two instances of Stack."
},
{
"code": null,
"e": 3307,
"s": 3238,
"text": "A ‘Queue_structure’ is defined, that defines two instances of Stack."
},
{
"code": null,
"e": 3385,
"s": 3307,
"text": "It has a method named ‘check_empty’ that checks to see if the queue is empty."
},
{
"code": null,
"e": 3463,
"s": 3385,
"text": "It has a method named ‘check_empty’ that checks to see if the queue is empty."
},
{
"code": null,
"e": 3554,
"s": 3463,
"text": "Another method named ‘enqueue_operation’ is defined, that helps add elements to the queue."
},
{
"code": null,
"e": 3645,
"s": 3554,
"text": "Another method named ‘enqueue_operation’ is defined, that helps add elements to the queue."
},
{
"code": null,
"e": 3738,
"s": 3645,
"text": "Another method named ‘dequeue_operation’ is defined, that deletes an element from the queue."
},
{
"code": null,
"e": 3831,
"s": 3738,
"text": "Another method named ‘dequeue_operation’ is defined, that deletes an element from the queue."
},
{
"code": null,
"e": 3875,
"s": 3831,
"text": "Another ‘Stack_structure’ class is created."
},
{
"code": null,
"e": 3919,
"s": 3875,
"text": "Another ‘Stack_structure’ class is created."
},
{
"code": null,
"e": 3949,
"s": 3919,
"text": "It initializes an empty list."
},
{
"code": null,
"e": 3979,
"s": 3949,
"text": "It initializes an empty list."
},
{
"code": null,
"e": 4057,
"s": 3979,
"text": "It has a method named ‘check_empty’ that checks to see if the stack is empty."
},
{
"code": null,
"e": 4135,
"s": 4057,
"text": "It has a method named ‘check_empty’ that checks to see if the stack is empty."
},
{
"code": null,
"e": 4223,
"s": 4135,
"text": "Another method named ‘push_operation’ is defined, that helps add elements to the queue."
},
{
"code": null,
"e": 4311,
"s": 4223,
"text": "Another method named ‘push_operation’ is defined, that helps add elements to the queue."
},
{
"code": null,
"e": 4400,
"s": 4311,
"text": "Another method named ‘pop_operation’ is defined, that deletes an element from the queue."
},
{
"code": null,
"e": 4489,
"s": 4400,
"text": "Another method named ‘pop_operation’ is defined, that deletes an element from the queue."
},
{
"code": null,
"e": 4530,
"s": 4489,
"text": "A ‘Queue_structure’ instance is created."
},
{
"code": null,
"e": 4571,
"s": 4530,
"text": "A ‘Queue_structure’ instance is created."
},
{
"code": null,
"e": 4624,
"s": 4571,
"text": "Three options are given- enqueue, dequeue, and quit."
},
{
"code": null,
"e": 4677,
"s": 4624,
"text": "Three options are given- enqueue, dequeue, and quit."
},
{
"code": null,
"e": 4791,
"s": 4677,
"text": "Based on the option given by user, the operations are performed, and relevant output is displayed on the console."
},
{
"code": null,
"e": 4905,
"s": 4791,
"text": "Based on the option given by user, the operations are performed, and relevant output is displayed on the console."
}
] |
SAP Scripts - Create a Script in the System
|
To start a script, you have to run Transaction SE71 and this will open the Form Painter.
In the Form Painter, request screen, enter a name and language for a SAPscript form in the Form and Language fields, respectively. Let’s enter 'RVINVOICE01' and 'EN' respectively in these fields.
Paragraph provides all the information required to format a paragraph of text and fonts. To create a Paragraph, click the Paragraph Formats tab as shown in the following screenshot.
Enter the left margin, right margin, alignment and line spacing to define the Paragraph format.
Click the Character Formats tab to enter character format and meaning as shown in the following screenshot.
Enter the following settings for format option −
Format
Meaning
Size
Then, you have to define Layout of the document. Click the Layout tab to design the window.
Using Layout, gives a GUI editor where you can drag the window position and it is easy to use.
By default, you can see the Main Window in the Layout. To create a new window, you can right-click on Layout → Create Window as seen in the following screenshot.
You can also add graph/logo to the layout part. Go to the Graph button next to Window tab and enter the details.
To make an element on the respective window, click the Edit text button.
You can define a driver program under Transaction SE38 to call this script. Use function modules to define the calling program −
START_FORM
WRITE_FORM
END_FORM
CLOSE_FORM
This is how you can develop a script and add multiple windows and define the paragraph and layout of the form.
Form OPEN_FORM
CALL FUNCTION 'OPEN_FORM'
EXPORTING
Form = 'FormName'
Endform “OPEN_FORM
Form START_FORM
CALL FUNCTION 'START_FORM'
EXPORTING
Form = 'FormName'.
Endform “START_FORM
CALL FUNCTION 'WRITE_FORM'
EXPORTING
Window = 'GRAPHNAME’
CALL FUNCTION 'WRITE_FORM'
EXPORTING
Element = 'ELEMENTNAME'
FUNCTION = 'SET'
TYPE = 'BODY'
Window = 'MAIN’
endform. " WRITE_FORM
CALL FUNCTION 'END_FORM'
IMPORTING
RESULT =
EXCEPTIONS
UNOPENED = 1
OTHERS = 5
endform. " END_FORM
CALL FUNCTION 'CLOSE_FORM'
IMPORTING
RESULT =
EXCEPTIONS
UNOPENED = 1
OTHERS = 5
endform. "CLOSE-FORM
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2612,
"s": 2523,
"text": "To start a script, you have to run Transaction SE71 and this will open the Form Painter."
},
{
"code": null,
"e": 2808,
"s": 2612,
"text": "In the Form Painter, request screen, enter a name and language for a SAPscript form in the Form and Language fields, respectively. Let’s enter 'RVINVOICE01' and 'EN' respectively in these fields."
},
{
"code": null,
"e": 2990,
"s": 2808,
"text": "Paragraph provides all the information required to format a paragraph of text and fonts. To create a Paragraph, click the Paragraph Formats tab as shown in the following screenshot."
},
{
"code": null,
"e": 3086,
"s": 2990,
"text": "Enter the left margin, right margin, alignment and line spacing to define the Paragraph format."
},
{
"code": null,
"e": 3194,
"s": 3086,
"text": "Click the Character Formats tab to enter character format and meaning as shown in the following screenshot."
},
{
"code": null,
"e": 3243,
"s": 3194,
"text": "Enter the following settings for format option −"
},
{
"code": null,
"e": 3250,
"s": 3243,
"text": "Format"
},
{
"code": null,
"e": 3258,
"s": 3250,
"text": "Meaning"
},
{
"code": null,
"e": 3263,
"s": 3258,
"text": "Size"
},
{
"code": null,
"e": 3355,
"s": 3263,
"text": "Then, you have to define Layout of the document. Click the Layout tab to design the window."
},
{
"code": null,
"e": 3450,
"s": 3355,
"text": "Using Layout, gives a GUI editor where you can drag the window position and it is easy to use."
},
{
"code": null,
"e": 3612,
"s": 3450,
"text": "By default, you can see the Main Window in the Layout. To create a new window, you can right-click on Layout → Create Window as seen in the following screenshot."
},
{
"code": null,
"e": 3725,
"s": 3612,
"text": "You can also add graph/logo to the layout part. Go to the Graph button next to Window tab and enter the details."
},
{
"code": null,
"e": 3798,
"s": 3725,
"text": "To make an element on the respective window, click the Edit text button."
},
{
"code": null,
"e": 3927,
"s": 3798,
"text": "You can define a driver program under Transaction SE38 to call this script. Use function modules to define the calling program −"
},
{
"code": null,
"e": 3938,
"s": 3927,
"text": "START_FORM"
},
{
"code": null,
"e": 3949,
"s": 3938,
"text": "WRITE_FORM"
},
{
"code": null,
"e": 3958,
"s": 3949,
"text": "END_FORM"
},
{
"code": null,
"e": 3969,
"s": 3958,
"text": "CLOSE_FORM"
},
{
"code": null,
"e": 4080,
"s": 3969,
"text": "This is how you can develop a script and add multiple windows and define the paragraph and layout of the form."
},
{
"code": null,
"e": 4200,
"s": 4080,
"text": "Form OPEN_FORM \nCALL FUNCTION 'OPEN_FORM' \nEXPORTING \nForm = 'FormName' \nEndform “OPEN_FORM \n"
},
{
"code": null,
"e": 4325,
"s": 4200,
"text": "Form START_FORM \nCALL FUNCTION 'START_FORM' \nEXPORTING \nForm = 'FormName'. \nEndform “START_FORM \n"
},
{
"code": null,
"e": 4392,
"s": 4325,
"text": "CALL FUNCTION 'WRITE_FORM' \nEXPORTING \nWindow = 'GRAPHNAME’ \n"
},
{
"code": null,
"e": 4567,
"s": 4392,
"text": "CALL FUNCTION 'WRITE_FORM' \nEXPORTING \nElement = 'ELEMENTNAME' \nFUNCTION = 'SET' \nTYPE = 'BODY' \nWindow = 'MAIN’ \nendform. \" WRITE_FORM \n"
},
{
"code": null,
"e": 4708,
"s": 4567,
"text": "CALL FUNCTION 'END_FORM' \nIMPORTING \nRESULT = \nEXCEPTIONS \nUNOPENED = 1 \nOTHERS = 5 \nendform. \" END_FORM \n"
},
{
"code": null,
"e": 4853,
"s": 4708,
"text": "CALL FUNCTION 'CLOSE_FORM' \nIMPORTING \nRESULT = \nEXCEPTIONS \nUNOPENED = 1 \nOTHERS = 5 \nendform. \"CLOSE-FORM \n"
},
{
"code": null,
"e": 4886,
"s": 4853,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4900,
"s": 4886,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 4933,
"s": 4900,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4945,
"s": 4933,
"text": " Neha Gupta"
},
{
"code": null,
"e": 4980,
"s": 4945,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4995,
"s": 4980,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 5028,
"s": 4995,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5043,
"s": 5028,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 5078,
"s": 5043,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5090,
"s": 5078,
"text": " Neha Malik"
},
{
"code": null,
"e": 5125,
"s": 5090,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5137,
"s": 5125,
"text": " Neha Malik"
},
{
"code": null,
"e": 5144,
"s": 5137,
"text": " Print"
},
{
"code": null,
"e": 5155,
"s": 5144,
"text": " Add Notes"
}
] |
How to write PHP script to fetch data, based on some conditions, from MySQL table?
|
If we want to fetch conditional data from MySQL table then we can write WHERE clause in SQL statement and use it with a PHP script. While writing the PHP script we can use PHP function mysql_query(). This function is used to execute the SQL command and later another PHP function mysql_fetch_array() can be used to fetch all the selected data. This function returns a row as an associative array, a numeric array, or both. This function returns FALSE if there are no more rows. To illustrate it we are having the following example −
In this example we are writing a PHP script that will return all the records from the table named ‘tutorial_tbl’ for which the author name is Sanjay −
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date
FROM tutorials_tbl
WHERE tutorial_author = "Sanjay"';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ".
"Author: {$row['tutorial_author']} <br> ".
"Submission Date : {$row['submission_date']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
|
[
{
"code": null,
"e": 1595,
"s": 1062,
"text": "If we want to fetch conditional data from MySQL table then we can write WHERE clause in SQL statement and use it with a PHP script. While writing the PHP script we can use PHP function mysql_query(). This function is used to execute the SQL command and later another PHP function mysql_fetch_array() can be used to fetch all the selected data. This function returns a row as an associative array, a numeric array, or both. This function returns FALSE if there are no more rows. To illustrate it we are having the following example −"
},
{
"code": null,
"e": 1746,
"s": 1595,
"text": "In this example we are writing a PHP script that will return all the records from the table named ‘tutorial_tbl’ for which the author name is Sanjay −"
},
{
"code": null,
"e": 2671,
"s": 1746,
"text": "<?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n $sql = 'SELECT tutorial_id, tutorial_title,\n tutorial_author, submission_date\n FROM tutorials_tbl\n WHERE tutorial_author = \"Sanjay\"';\n\n mysql_select_db('TUTORIALS');\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not get data: ' . mysql_error());\n }\n \n while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {\n echo \"Tutorial ID :{$row['tutorial_id']} <br> \".\n \"Title: {$row['tutorial_title']} <br> \".\n \"Author: {$row['tutorial_author']} <br> \".\n \"Submission Date : {$row['submission_date']} <br> \".\n \"--------------------------------<br>\";\n }\n echo \"Fetched data successfully\\n\";\n mysql_close($conn);\n?>"
}
] |
Accessing and Cleaning Data from Garmin Wearables for Analysis | by Adam Brownell | Towards Data Science
|
When I started working on a project to analyze my Garmin Fenix data, it wasn’t clear how to access this amazing dataset, and required some technical know-how.
Garmin’s documentation was also hard to follow and outdated, resulting in me having to dig through code repos and old internet forums...
Hopefully this article can transform what took me a non-trivial amount of time into something simple and easy to understand.
All images in the article unless otherwise noted are by the author
While there a bunch of factors on what data is available, ranging from what Garmin model you are using to if you are consistently wearing the chest heart rate monitor, here are the features I was able to extract from my Garmin Fenix without a chest strap:
General Fitness Data:
Wake Time
Steps
Cycles
Ascent/Descent
Heart Rate
Activity Type and Minutes (Moderate and Vigorous)
Total Moving Time
Walking Step Length, Average Speed
Calories burned, Total fat calories burned
Training Stress Score
Max & Average Temperature
Stress Level
Speed & Intensity
Resting Metabolic Rate, Resting Heart Rate
Swimming: Pool length, stroke length and distance, swimming cadence, first lap index
Running: Max running cadence, max general cadence, total strides
Exercise-Specific Event Data:
Time
Distance travelled
Location (Longitude/Latitude)
Altitude & Temperature
Heart Rate
Cadence (and Fractional Cadence)
Speed & Power
Left-Right Balance
While you can also access this data via Garmin’s SDK called “Garmin Connect IQ”, I will go over the manual way to access this data. It is actually a lot easier, especially for personal use, but Garmin has outdated documentation so it seems complicated...
First, head to your Garmin Account Data Management (https://www.garmin.com/en-US/account/datamanagement/) and log in:
Then head to “Export your Data” and clickRequest Data Export.
You will then receive a message stating:
Your request has successfully submitted.You can request a copy of all personal data, including your profile, order history, information from Garmin Connect and other applications, subscriptions, registered devices and more.We will send a link to download your export file to [[email protected]]Files typically take about 48 hours to prepare but, depending on the number of requests being processed and the amount of data associated with your profile, could take up to 30 days.
Congrats! You will get your data soon. While the message says up to 30 days, I got mine within 30 minutes. (Also why would it take them 30 days to process a data request? I requested it from inside my account, so there aren’t any permission/security issues... do they have someone manually sending me my data...?)
Eventually you’ll receive a .zip file. Open this to reveal the folder structure:
For me, most of these folders were empty because I was not using them. And of the ones that weren’t empty, nearly all of them contained a single JSON file of customer data or aggregated exercise data.
The only one we care about is DI_CONNECT > DI-Connect-Fitness-Uploaded-Files:
Click on the .zip file in this nested folders, and you will create a folder filled with .fit filetypes
This is the trickiest part, as we need to convert these from .fit to .CSV using the Command Line. .fit is a specialty filetype Garmin uses that none of your data analysis tools (Excel, Atom, Jupyter) can use.
We will be relying on Garmin’s FIT CSV Tool (https://developer.garmin.com/fit/fitcsvtool/) from the FIT SDK. It’s free but requires setup.
First, open Command Line Terminal. If you’re unfamiliar with CLI, it should look like this:
Next we need to check if we have JAVA installed. An easy way to check is to type java -version into our terminal. If we get a number returned, it’s installed. If we get an error message, we’ll need to install it
Installing Java: Depending if you’re running MacOS/Windows/Linux, you will need to download different files. Like the terminal message says, head to https://www.java.com/en/download/ and download the java package. This will prompt an installer window which you can follow along here. After download success, close + reopen your terminal and verify java was installed via the same java -version test.
Once we know Java has been downloaded, go ahead and Download the FIT SDK as well (https://developer.garmin.com/fit/download/) and decompress the .zip
This will give you a folder with the following contents:
Now, we can convert our .fit files into .csv 🚀 The jar file that will accomplish this is in a java folder called FitCSVTool.jar
Type the following into the command line, replacing <file> with the file path of a .fit file:
java -jar FitCSVTool.jar <file>
If you are getting errors such as Unable to access jarfile FitCSVTool or (No such file or directory) , you’ll need to figure out the right file paths. On a Mac, it’s as easy as dragging/dropping the file directly into terminal. In windows you’ll need to copy/paste file paths from file properties.
If you are successful, a .csv file will be created in the same directory as the original .fit file.
This could be the end of conversion process, but typing out the above command for every single file is a pain. I had over 8,000 .fit files, and you may have more. Luckily we can automate this.
The Windows and Mac guides will now diverge for this step. As mentioned in the documentation:
The FIT SDK includes multiple Windows batch files that provide a drag-n-drop interface for FitCSVTool. These batch files are not compatible with OSX; however, the same functionality can be accomplished using an Automator application.
For Macs, we can create an Automator as outlined in the above docs; Open up Automator and...
Select “Application” from the window and click Choose
Give it a Name
Find “Filter Finder Items” in the Library folder and drag it into the right-side screen. Type in “.fit” to the contains field
Find “Run Shell Script” in the Library folder and drag into the right-side screen. Fill out with the following code snippet, replacing path/to/fit/sdk/java/FitCSVTool.jar with your path to the tool used above (remember you can drag and drop!):
FitCSVToolJar=path/to/fit/sdk/java/FitCSVTool.jarwhile read inputfiledooutputfile=${inputfile/.fit/}java -jar $FitCSVToolJar -b "$inputfile" "$outputfile"_rawjava -jar $FitCSVToolJar -b "$inputfile" "$outputfile"_definitions --data nonejava -jar $FitCSVToolJar -b "$inputfile" "$outputfile"_records --defn none --data recorddone
After all this your Automator Application should look like this:
Save this to desktop
Highlight and drag all of the .fit files on to the Application Desktop icon, seen here
This should start to automatically convert all of the thousands of documents you have. For me, this made my MacBook fan very loud and took about a half hour.
While I don’t have a Windows machine to test this on, I do believe that Windows do a similar drag/drop system by dragging all of the .fit files onto one of the .bat files in the FitSDK folder:
As mentioned in the Windows docs:
An easier way to use FitCSVTool is to use one of the five batch files included in the SDK. These files are located in the same folder as FitCSVTool.jar. Drag-n-drop a FIT file onto any of the batch files and the output .csv files will be created in the same folder as the source FIT file.
As a consequence of the previous step of converting from .fit to .csv, we now have several .csv files per .fit file:
A _definitions files outlining which fields are present in the data
A _records_data file with a summarized data of distances, speed of an exercise routine
A _records file containing location, speed, and distance of an exercise routine moment by moment
A _raw file containing everything, including stress level, heart rate, and other metrics. (These are extremely messy as seen in the next section)
🎉 Congrats, you have your data in CSV format! 🎉
Everything in this step and beyond is data cleaning that I recommend, but optional. You may also have different data than me, so these cleaning processes may not work for you.
With that said, I am pretty confident the following steps will help anyone looking to analyze their Garmin data.
Looking at the definitions files, they don’t seem to contain anything useful. From spot checks, all the Value columns seem to be 1. I’m assuming this is important for .fit files, but not for our purposes.
To remove definitions files, navigate to the location of your csv files in terminal by running:
cd path/to/csv/files
and then running:
rm *definitions*
This could also be easily be done by removing the java -jar $FitCSVToolJar -b "$inputfile" "$outputfile".definitions --data none from our automator originally, but wanted to ensure anyone who wanted the file could use it
We still have an issue of having thousands of CSVs to parse through to look at our data. You can combine all CSVs with:
cat *.csv >garmin_combined.csv
or if you are planning to generate the same data schema as I have below:
cat *_records.csv >combined_records_full.csvcat *_raw.csv >combined_raw_full.csv
which creates 2 different combined CSVs for us to use.
😃Good News: The _records files generated from our .fit conversion look good.
🙁Bad News: The _raw data files are SO MESSY AND UGLY. Empty fields, special characters, column values meaning different things... oh my.
I highly recommend pivoting by timestamp so that the columns are meaningful. This way you can quickly and easily check any metric of interest by the time of recording, which is assumably the most common use of this data.
By aggregating by timestamp, we also greatly reduce the file size without losing any data. A win-win!
I have written a cleaner function in Python to create these columns. I’ve uploaded it to a Github Repo, file clean_garmin.py, or copy paste this following into you own clean_garmin.py file:
Installing Python: You’ll need Python on your computer to run the above function. Go to https://www.python.org/downloads/ and install Python. Then go to terminal to make sure download successful with python --version.
Once you save the above code block, you can run in terminal:
python clean_garmin.py -i combined_records_full.csv -o combined_records_clean.csvpython clean_garmin.py -i combined_raw_full.csv -o combined_raw_clean.csv
Note: This will take a long time, especially the raw files. It took my computer 10min for records, and about 2.5hr for raw. The reason for this is that sometimes the timestamp on a data entry is local rather than global, meaning it references the most recent global timestamp. So every time we do this conversion the code needs to find the most recent global timestamp and convert the local timestamp into global... But this runs in O(n2) time 💀
...And our data looks a lot better 🙌
If my clean function fails on your data, or if you have a better implementation of the data clean, please leave a comment so we can collaborate!
We still have thousands of files in our folder, and it stresses me out. Go ahead and remove all of the non-aggregated CSVs with:
rm *_raw.csv*rm *_records.csv*rm *_records_data.csv*
Now that we have a clean, usable CSV of our Garmin data, we can start analyzing and gaining insights from this beautiful dataset.
This is the fun part of data science/analytics, and hopefully made all the hoops we jumped through worth it!
Since this article is already quite long, I will write a follow-up with a few methods to analyze Garmin data to draw interesting insights on our exercise and fitness habits.
If any of the above steps did not work for you, PLEASE leave a comment so I can try to help debug and add the solution to the article. My hope is that no one has to go digging through the forums for answers again, getting all the answers here.
Hope you enjoy, and good luck in your analytics journey!
|
[
{
"code": null,
"e": 330,
"s": 171,
"text": "When I started working on a project to analyze my Garmin Fenix data, it wasn’t clear how to access this amazing dataset, and required some technical know-how."
},
{
"code": null,
"e": 467,
"s": 330,
"text": "Garmin’s documentation was also hard to follow and outdated, resulting in me having to dig through code repos and old internet forums..."
},
{
"code": null,
"e": 592,
"s": 467,
"text": "Hopefully this article can transform what took me a non-trivial amount of time into something simple and easy to understand."
},
{
"code": null,
"e": 659,
"s": 592,
"text": "All images in the article unless otherwise noted are by the author"
},
{
"code": null,
"e": 915,
"s": 659,
"text": "While there a bunch of factors on what data is available, ranging from what Garmin model you are using to if you are consistently wearing the chest heart rate monitor, here are the features I was able to extract from my Garmin Fenix without a chest strap:"
},
{
"code": null,
"e": 937,
"s": 915,
"text": "General Fitness Data:"
},
{
"code": null,
"e": 947,
"s": 937,
"text": "Wake Time"
},
{
"code": null,
"e": 953,
"s": 947,
"text": "Steps"
},
{
"code": null,
"e": 960,
"s": 953,
"text": "Cycles"
},
{
"code": null,
"e": 975,
"s": 960,
"text": "Ascent/Descent"
},
{
"code": null,
"e": 986,
"s": 975,
"text": "Heart Rate"
},
{
"code": null,
"e": 1036,
"s": 986,
"text": "Activity Type and Minutes (Moderate and Vigorous)"
},
{
"code": null,
"e": 1054,
"s": 1036,
"text": "Total Moving Time"
},
{
"code": null,
"e": 1089,
"s": 1054,
"text": "Walking Step Length, Average Speed"
},
{
"code": null,
"e": 1132,
"s": 1089,
"text": "Calories burned, Total fat calories burned"
},
{
"code": null,
"e": 1154,
"s": 1132,
"text": "Training Stress Score"
},
{
"code": null,
"e": 1180,
"s": 1154,
"text": "Max & Average Temperature"
},
{
"code": null,
"e": 1193,
"s": 1180,
"text": "Stress Level"
},
{
"code": null,
"e": 1211,
"s": 1193,
"text": "Speed & Intensity"
},
{
"code": null,
"e": 1254,
"s": 1211,
"text": "Resting Metabolic Rate, Resting Heart Rate"
},
{
"code": null,
"e": 1339,
"s": 1254,
"text": "Swimming: Pool length, stroke length and distance, swimming cadence, first lap index"
},
{
"code": null,
"e": 1404,
"s": 1339,
"text": "Running: Max running cadence, max general cadence, total strides"
},
{
"code": null,
"e": 1434,
"s": 1404,
"text": "Exercise-Specific Event Data:"
},
{
"code": null,
"e": 1439,
"s": 1434,
"text": "Time"
},
{
"code": null,
"e": 1458,
"s": 1439,
"text": "Distance travelled"
},
{
"code": null,
"e": 1488,
"s": 1458,
"text": "Location (Longitude/Latitude)"
},
{
"code": null,
"e": 1511,
"s": 1488,
"text": "Altitude & Temperature"
},
{
"code": null,
"e": 1522,
"s": 1511,
"text": "Heart Rate"
},
{
"code": null,
"e": 1555,
"s": 1522,
"text": "Cadence (and Fractional Cadence)"
},
{
"code": null,
"e": 1569,
"s": 1555,
"text": "Speed & Power"
},
{
"code": null,
"e": 1588,
"s": 1569,
"text": "Left-Right Balance"
},
{
"code": null,
"e": 1843,
"s": 1588,
"text": "While you can also access this data via Garmin’s SDK called “Garmin Connect IQ”, I will go over the manual way to access this data. It is actually a lot easier, especially for personal use, but Garmin has outdated documentation so it seems complicated..."
},
{
"code": null,
"e": 1961,
"s": 1843,
"text": "First, head to your Garmin Account Data Management (https://www.garmin.com/en-US/account/datamanagement/) and log in:"
},
{
"code": null,
"e": 2023,
"s": 1961,
"text": "Then head to “Export your Data” and clickRequest Data Export."
},
{
"code": null,
"e": 2064,
"s": 2023,
"text": "You will then receive a message stating:"
},
{
"code": null,
"e": 2550,
"s": 2064,
"text": "Your request has successfully submitted.You can request a copy of all personal data, including your profile, order history, information from Garmin Connect and other applications, subscriptions, registered devices and more.We will send a link to download your export file to [[email protected]]Files typically take about 48 hours to prepare but, depending on the number of requests being processed and the amount of data associated with your profile, could take up to 30 days."
},
{
"code": null,
"e": 2864,
"s": 2550,
"text": "Congrats! You will get your data soon. While the message says up to 30 days, I got mine within 30 minutes. (Also why would it take them 30 days to process a data request? I requested it from inside my account, so there aren’t any permission/security issues... do they have someone manually sending me my data...?)"
},
{
"code": null,
"e": 2945,
"s": 2864,
"text": "Eventually you’ll receive a .zip file. Open this to reveal the folder structure:"
},
{
"code": null,
"e": 3146,
"s": 2945,
"text": "For me, most of these folders were empty because I was not using them. And of the ones that weren’t empty, nearly all of them contained a single JSON file of customer data or aggregated exercise data."
},
{
"code": null,
"e": 3224,
"s": 3146,
"text": "The only one we care about is DI_CONNECT > DI-Connect-Fitness-Uploaded-Files:"
},
{
"code": null,
"e": 3327,
"s": 3224,
"text": "Click on the .zip file in this nested folders, and you will create a folder filled with .fit filetypes"
},
{
"code": null,
"e": 3536,
"s": 3327,
"text": "This is the trickiest part, as we need to convert these from .fit to .CSV using the Command Line. .fit is a specialty filetype Garmin uses that none of your data analysis tools (Excel, Atom, Jupyter) can use."
},
{
"code": null,
"e": 3675,
"s": 3536,
"text": "We will be relying on Garmin’s FIT CSV Tool (https://developer.garmin.com/fit/fitcsvtool/) from the FIT SDK. It’s free but requires setup."
},
{
"code": null,
"e": 3767,
"s": 3675,
"text": "First, open Command Line Terminal. If you’re unfamiliar with CLI, it should look like this:"
},
{
"code": null,
"e": 3979,
"s": 3767,
"text": "Next we need to check if we have JAVA installed. An easy way to check is to type java -version into our terminal. If we get a number returned, it’s installed. If we get an error message, we’ll need to install it"
},
{
"code": null,
"e": 4379,
"s": 3979,
"text": "Installing Java: Depending if you’re running MacOS/Windows/Linux, you will need to download different files. Like the terminal message says, head to https://www.java.com/en/download/ and download the java package. This will prompt an installer window which you can follow along here. After download success, close + reopen your terminal and verify java was installed via the same java -version test."
},
{
"code": null,
"e": 4529,
"s": 4379,
"text": "Once we know Java has been downloaded, go ahead and Download the FIT SDK as well (https://developer.garmin.com/fit/download/) and decompress the .zip"
},
{
"code": null,
"e": 4586,
"s": 4529,
"text": "This will give you a folder with the following contents:"
},
{
"code": null,
"e": 4714,
"s": 4586,
"text": "Now, we can convert our .fit files into .csv 🚀 The jar file that will accomplish this is in a java folder called FitCSVTool.jar"
},
{
"code": null,
"e": 4808,
"s": 4714,
"text": "Type the following into the command line, replacing <file> with the file path of a .fit file:"
},
{
"code": null,
"e": 4840,
"s": 4808,
"text": "java -jar FitCSVTool.jar <file>"
},
{
"code": null,
"e": 5138,
"s": 4840,
"text": "If you are getting errors such as Unable to access jarfile FitCSVTool or (No such file or directory) , you’ll need to figure out the right file paths. On a Mac, it’s as easy as dragging/dropping the file directly into terminal. In windows you’ll need to copy/paste file paths from file properties."
},
{
"code": null,
"e": 5238,
"s": 5138,
"text": "If you are successful, a .csv file will be created in the same directory as the original .fit file."
},
{
"code": null,
"e": 5431,
"s": 5238,
"text": "This could be the end of conversion process, but typing out the above command for every single file is a pain. I had over 8,000 .fit files, and you may have more. Luckily we can automate this."
},
{
"code": null,
"e": 5525,
"s": 5431,
"text": "The Windows and Mac guides will now diverge for this step. As mentioned in the documentation:"
},
{
"code": null,
"e": 5759,
"s": 5525,
"text": "The FIT SDK includes multiple Windows batch files that provide a drag-n-drop interface for FitCSVTool. These batch files are not compatible with OSX; however, the same functionality can be accomplished using an Automator application."
},
{
"code": null,
"e": 5852,
"s": 5759,
"text": "For Macs, we can create an Automator as outlined in the above docs; Open up Automator and..."
},
{
"code": null,
"e": 5906,
"s": 5852,
"text": "Select “Application” from the window and click Choose"
},
{
"code": null,
"e": 5921,
"s": 5906,
"text": "Give it a Name"
},
{
"code": null,
"e": 6047,
"s": 5921,
"text": "Find “Filter Finder Items” in the Library folder and drag it into the right-side screen. Type in “.fit” to the contains field"
},
{
"code": null,
"e": 6291,
"s": 6047,
"text": "Find “Run Shell Script” in the Library folder and drag into the right-side screen. Fill out with the following code snippet, replacing path/to/fit/sdk/java/FitCSVTool.jar with your path to the tool used above (remember you can drag and drop!):"
},
{
"code": null,
"e": 6620,
"s": 6291,
"text": "FitCSVToolJar=path/to/fit/sdk/java/FitCSVTool.jarwhile read inputfiledooutputfile=${inputfile/.fit/}java -jar $FitCSVToolJar -b \"$inputfile\" \"$outputfile\"_rawjava -jar $FitCSVToolJar -b \"$inputfile\" \"$outputfile\"_definitions --data nonejava -jar $FitCSVToolJar -b \"$inputfile\" \"$outputfile\"_records --defn none --data recorddone"
},
{
"code": null,
"e": 6685,
"s": 6620,
"text": "After all this your Automator Application should look like this:"
},
{
"code": null,
"e": 6706,
"s": 6685,
"text": "Save this to desktop"
},
{
"code": null,
"e": 6793,
"s": 6706,
"text": "Highlight and drag all of the .fit files on to the Application Desktop icon, seen here"
},
{
"code": null,
"e": 6951,
"s": 6793,
"text": "This should start to automatically convert all of the thousands of documents you have. For me, this made my MacBook fan very loud and took about a half hour."
},
{
"code": null,
"e": 7144,
"s": 6951,
"text": "While I don’t have a Windows machine to test this on, I do believe that Windows do a similar drag/drop system by dragging all of the .fit files onto one of the .bat files in the FitSDK folder:"
},
{
"code": null,
"e": 7178,
"s": 7144,
"text": "As mentioned in the Windows docs:"
},
{
"code": null,
"e": 7467,
"s": 7178,
"text": "An easier way to use FitCSVTool is to use one of the five batch files included in the SDK. These files are located in the same folder as FitCSVTool.jar. Drag-n-drop a FIT file onto any of the batch files and the output .csv files will be created in the same folder as the source FIT file."
},
{
"code": null,
"e": 7584,
"s": 7467,
"text": "As a consequence of the previous step of converting from .fit to .csv, we now have several .csv files per .fit file:"
},
{
"code": null,
"e": 7652,
"s": 7584,
"text": "A _definitions files outlining which fields are present in the data"
},
{
"code": null,
"e": 7739,
"s": 7652,
"text": "A _records_data file with a summarized data of distances, speed of an exercise routine"
},
{
"code": null,
"e": 7836,
"s": 7739,
"text": "A _records file containing location, speed, and distance of an exercise routine moment by moment"
},
{
"code": null,
"e": 7982,
"s": 7836,
"text": "A _raw file containing everything, including stress level, heart rate, and other metrics. (These are extremely messy as seen in the next section)"
},
{
"code": null,
"e": 8030,
"s": 7982,
"text": "🎉 Congrats, you have your data in CSV format! 🎉"
},
{
"code": null,
"e": 8206,
"s": 8030,
"text": "Everything in this step and beyond is data cleaning that I recommend, but optional. You may also have different data than me, so these cleaning processes may not work for you."
},
{
"code": null,
"e": 8319,
"s": 8206,
"text": "With that said, I am pretty confident the following steps will help anyone looking to analyze their Garmin data."
},
{
"code": null,
"e": 8524,
"s": 8319,
"text": "Looking at the definitions files, they don’t seem to contain anything useful. From spot checks, all the Value columns seem to be 1. I’m assuming this is important for .fit files, but not for our purposes."
},
{
"code": null,
"e": 8620,
"s": 8524,
"text": "To remove definitions files, navigate to the location of your csv files in terminal by running:"
},
{
"code": null,
"e": 8641,
"s": 8620,
"text": "cd path/to/csv/files"
},
{
"code": null,
"e": 8659,
"s": 8641,
"text": "and then running:"
},
{
"code": null,
"e": 8676,
"s": 8659,
"text": "rm *definitions*"
},
{
"code": null,
"e": 8897,
"s": 8676,
"text": "This could also be easily be done by removing the java -jar $FitCSVToolJar -b \"$inputfile\" \"$outputfile\".definitions --data none from our automator originally, but wanted to ensure anyone who wanted the file could use it"
},
{
"code": null,
"e": 9017,
"s": 8897,
"text": "We still have an issue of having thousands of CSVs to parse through to look at our data. You can combine all CSVs with:"
},
{
"code": null,
"e": 9048,
"s": 9017,
"text": "cat *.csv >garmin_combined.csv"
},
{
"code": null,
"e": 9121,
"s": 9048,
"text": "or if you are planning to generate the same data schema as I have below:"
},
{
"code": null,
"e": 9202,
"s": 9121,
"text": "cat *_records.csv >combined_records_full.csvcat *_raw.csv >combined_raw_full.csv"
},
{
"code": null,
"e": 9257,
"s": 9202,
"text": "which creates 2 different combined CSVs for us to use."
},
{
"code": null,
"e": 9334,
"s": 9257,
"text": "😃Good News: The _records files generated from our .fit conversion look good."
},
{
"code": null,
"e": 9471,
"s": 9334,
"text": "🙁Bad News: The _raw data files are SO MESSY AND UGLY. Empty fields, special characters, column values meaning different things... oh my."
},
{
"code": null,
"e": 9692,
"s": 9471,
"text": "I highly recommend pivoting by timestamp so that the columns are meaningful. This way you can quickly and easily check any metric of interest by the time of recording, which is assumably the most common use of this data."
},
{
"code": null,
"e": 9794,
"s": 9692,
"text": "By aggregating by timestamp, we also greatly reduce the file size without losing any data. A win-win!"
},
{
"code": null,
"e": 9984,
"s": 9794,
"text": "I have written a cleaner function in Python to create these columns. I’ve uploaded it to a Github Repo, file clean_garmin.py, or copy paste this following into you own clean_garmin.py file:"
},
{
"code": null,
"e": 10202,
"s": 9984,
"text": "Installing Python: You’ll need Python on your computer to run the above function. Go to https://www.python.org/downloads/ and install Python. Then go to terminal to make sure download successful with python --version."
},
{
"code": null,
"e": 10263,
"s": 10202,
"text": "Once you save the above code block, you can run in terminal:"
},
{
"code": null,
"e": 10418,
"s": 10263,
"text": "python clean_garmin.py -i combined_records_full.csv -o combined_records_clean.csvpython clean_garmin.py -i combined_raw_full.csv -o combined_raw_clean.csv"
},
{
"code": null,
"e": 10864,
"s": 10418,
"text": "Note: This will take a long time, especially the raw files. It took my computer 10min for records, and about 2.5hr for raw. The reason for this is that sometimes the timestamp on a data entry is local rather than global, meaning it references the most recent global timestamp. So every time we do this conversion the code needs to find the most recent global timestamp and convert the local timestamp into global... But this runs in O(n2) time 💀"
},
{
"code": null,
"e": 10901,
"s": 10864,
"text": "...And our data looks a lot better 🙌"
},
{
"code": null,
"e": 11046,
"s": 10901,
"text": "If my clean function fails on your data, or if you have a better implementation of the data clean, please leave a comment so we can collaborate!"
},
{
"code": null,
"e": 11175,
"s": 11046,
"text": "We still have thousands of files in our folder, and it stresses me out. Go ahead and remove all of the non-aggregated CSVs with:"
},
{
"code": null,
"e": 11228,
"s": 11175,
"text": "rm *_raw.csv*rm *_records.csv*rm *_records_data.csv*"
},
{
"code": null,
"e": 11358,
"s": 11228,
"text": "Now that we have a clean, usable CSV of our Garmin data, we can start analyzing and gaining insights from this beautiful dataset."
},
{
"code": null,
"e": 11467,
"s": 11358,
"text": "This is the fun part of data science/analytics, and hopefully made all the hoops we jumped through worth it!"
},
{
"code": null,
"e": 11641,
"s": 11467,
"text": "Since this article is already quite long, I will write a follow-up with a few methods to analyze Garmin data to draw interesting insights on our exercise and fitness habits."
},
{
"code": null,
"e": 11885,
"s": 11641,
"text": "If any of the above steps did not work for you, PLEASE leave a comment so I can try to help debug and add the solution to the article. My hope is that no one has to go digging through the forums for answers again, getting all the answers here."
}
] |
File.Delete() Method in C# with Examples - GeeksforGeeks
|
12 Apr, 2021
File.Delete(String) is an inbuilt File class method which is used to delete the specified file.Syntax:
public static void Delete (string path);
Parameter: This function accepts a parameter which is illustrated below:
path: This is the specified file path which is to be deleted.
Exceptions:
ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
ArgumentNullException: The path is null.
DirectoryNotFoundException: The given path is invalid.
IOException: The given file is in use. OR there is an open handle on the file, and the operating system is Windows XP or earlier. This open handle can result from enumerating directories and files. For more information, see How to: Enumerate Directories and Files.
NotSupportedException: The path is in an invalid format.
PathTooLongException: The given path, file name, or both exceed the system-defined maximum length.
UnauthorizedAccessException: The caller does not have the required permission. OR the file is an executable file that is in use. OR the path is a directory. OR the path specified a read-only file.
Below are the programs to illustrate the File.Delete(String) method.Program 1: Before running the below code, a file file.txt is created with some contents shown below:
CSharp
// C# program to illustrate the usage// of File.Delete(String) method // Using System and System.IO namespacesusing System;using System.IO; public class GFG { // Using main() function public static void Main() { // Specifying a file String myfile = @"file.txt"; // Calling the Delete() function to // delete the file file.txt File.Delete(myfile); // Printing a line Console.WriteLine("Specified file has been deleted"); }}
Executing:
mcs -out:main.exe main.cs
mono main.exe
Specified file has been deleted
After running the above code, the above output is shown and the file file.txt has been deleted.Program 2: Before running the below code, two files have been created shown below:
CSharp
// C# program to illustrate the usage// of File.Delete(String) method // Using System and System.IO namespacesusing System;using System.IO; public class GFG { // Using main() function public static void Main() { // Specifying two files String myfile1 = @"file.txt"; String myfile2 = @"gfg.txt"; // Calling the Delete() function to // delete the file file.txt and gfg.txt File.Delete(myfile1); File.Delete(myfile2); // Printing a line Console.WriteLine("Specified files have been deleted."); }}
Executing:
mcs -out:main.exe main.cs
mono main.exe
Specified files have been deleted.
After running the above code, above output is shown and two existing files file.txt and gfg.txt have been deleted.
arorakashish0911
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Method Overriding
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | Class and Object
|
[
{
"code": null,
"e": 24658,
"s": 24630,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 24763,
"s": 24658,
"text": "File.Delete(String) is an inbuilt File class method which is used to delete the specified file.Syntax: "
},
{
"code": null,
"e": 24804,
"s": 24763,
"text": "public static void Delete (string path);"
},
{
"code": null,
"e": 24879,
"s": 24804,
"text": "Parameter: This function accepts a parameter which is illustrated below: "
},
{
"code": null,
"e": 24941,
"s": 24879,
"text": "path: This is the specified file path which is to be deleted."
},
{
"code": null,
"e": 24954,
"s": 24941,
"text": "Exceptions: "
},
{
"code": null,
"e": 25100,
"s": 24954,
"text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars."
},
{
"code": null,
"e": 25141,
"s": 25100,
"text": "ArgumentNullException: The path is null."
},
{
"code": null,
"e": 25196,
"s": 25141,
"text": "DirectoryNotFoundException: The given path is invalid."
},
{
"code": null,
"e": 25461,
"s": 25196,
"text": "IOException: The given file is in use. OR there is an open handle on the file, and the operating system is Windows XP or earlier. This open handle can result from enumerating directories and files. For more information, see How to: Enumerate Directories and Files."
},
{
"code": null,
"e": 25518,
"s": 25461,
"text": "NotSupportedException: The path is in an invalid format."
},
{
"code": null,
"e": 25617,
"s": 25518,
"text": "PathTooLongException: The given path, file name, or both exceed the system-defined maximum length."
},
{
"code": null,
"e": 25814,
"s": 25617,
"text": "UnauthorizedAccessException: The caller does not have the required permission. OR the file is an executable file that is in use. OR the path is a directory. OR the path specified a read-only file."
},
{
"code": null,
"e": 25984,
"s": 25814,
"text": "Below are the programs to illustrate the File.Delete(String) method.Program 1: Before running the below code, a file file.txt is created with some contents shown below: "
},
{
"code": null,
"e": 25993,
"s": 25986,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the usage// of File.Delete(String) method // Using System and System.IO namespacesusing System;using System.IO; public class GFG { // Using main() function public static void Main() { // Specifying a file String myfile = @\"file.txt\"; // Calling the Delete() function to // delete the file file.txt File.Delete(myfile); // Printing a line Console.WriteLine(\"Specified file has been deleted\"); }}",
"e": 26479,
"s": 25993,
"text": null
},
{
"code": null,
"e": 26492,
"s": 26479,
"text": "Executing: "
},
{
"code": null,
"e": 26564,
"s": 26492,
"text": "mcs -out:main.exe main.cs\nmono main.exe\nSpecified file has been deleted"
},
{
"code": null,
"e": 26743,
"s": 26564,
"text": "After running the above code, the above output is shown and the file file.txt has been deleted.Program 2: Before running the below code, two files have been created shown below: "
},
{
"code": null,
"e": 26754,
"s": 26747,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the usage// of File.Delete(String) method // Using System and System.IO namespacesusing System;using System.IO; public class GFG { // Using main() function public static void Main() { // Specifying two files String myfile1 = @\"file.txt\"; String myfile2 = @\"gfg.txt\"; // Calling the Delete() function to // delete the file file.txt and gfg.txt File.Delete(myfile1); File.Delete(myfile2); // Printing a line Console.WriteLine(\"Specified files have been deleted.\"); }}",
"e": 27325,
"s": 26754,
"text": null
},
{
"code": null,
"e": 27338,
"s": 27325,
"text": "Executing: "
},
{
"code": null,
"e": 27413,
"s": 27338,
"text": "mcs -out:main.exe main.cs\nmono main.exe\nSpecified files have been deleted."
},
{
"code": null,
"e": 27529,
"s": 27413,
"text": "After running the above code, above output is shown and two existing files file.txt and gfg.txt have been deleted. "
},
{
"code": null,
"e": 27546,
"s": 27529,
"text": "arorakashish0911"
},
{
"code": null,
"e": 27567,
"s": 27546,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 27570,
"s": 27567,
"text": "C#"
},
{
"code": null,
"e": 27668,
"s": 27570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27696,
"s": 27668,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27719,
"s": 27696,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 27737,
"s": 27719,
"text": "Destructors in C#"
},
{
"code": null,
"e": 27783,
"s": 27737,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27798,
"s": 27783,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27838,
"s": 27798,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27856,
"s": 27838,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27879,
"s": 27856,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27910,
"s": 27879,
"text": "Introduction to .NET Framework"
}
] |
Implement Runnable vs Extend Thread in Java
|
We can create Thread by either by implementing a runnable interface or by extending Thread class. Below are the detailed steps of using both ways to create Thread.
If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps −
Step 1
As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method −
public void run( )
Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.
Step 3
Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −
void start();
Live Demo
Here is an example that creates a new thread and starts running it −
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
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[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
This will produce the following result −
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.
Step 1
You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method −
public void run( )
Step 2
Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −
void start( );
Here is the preceding program rewritten to extend the Thread −
Live Demo
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
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[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}
This will produce the following result −
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
|
[
{
"code": null,
"e": 1226,
"s": 1062,
"text": "We can create Thread by either by implementing a runnable interface or by extending Thread class. Below are the detailed steps of using both ways to create Thread."
},
{
"code": null,
"e": 1387,
"s": 1226,
"text": "If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps −"
},
{
"code": null,
"e": 1394,
"s": 1387,
"text": "Step 1"
},
{
"code": null,
"e": 1650,
"s": 1394,
"text": "As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method −"
},
{
"code": null,
"e": 1669,
"s": 1650,
"text": "public void run( )"
},
{
"code": null,
"e": 1676,
"s": 1669,
"text": "Step 2"
},
{
"code": null,
"e": 1765,
"s": 1676,
"text": "As a second step, you will instantiate a Thread object using the following constructor −"
},
{
"code": null,
"e": 1812,
"s": 1765,
"text": "Thread(Runnable threadObj, String threadName);"
},
{
"code": null,
"e": 1946,
"s": 1812,
"text": "Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread."
},
{
"code": null,
"e": 1953,
"s": 1946,
"text": "Step 3"
},
{
"code": null,
"e": 2119,
"s": 1953,
"text": "Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −"
},
{
"code": null,
"e": 2133,
"s": 2119,
"text": "void start();"
},
{
"code": null,
"e": 2144,
"s": 2133,
"text": " Live Demo"
},
{
"code": null,
"e": 2213,
"s": 2144,
"text": "Here is an example that creates a new thread and starts running it −"
},
{
"code": null,
"e": 3303,
"s": 2213,
"text": "class RunnableDemo implements Runnable {\n private Thread t;\n private String threadName;\n\n RunnableDemo( String name) {\n threadName = name;\n System.out.println(\"Creating \" + threadName );\n }\n\n public void run() {\n System.out.println(\"Running \" + threadName );\n try {\n for(int i = 4; i > 0; i--) {\n System.out.println(\"Thread: \" + threadName + \", \" + i);\n\n // Let the thread sleep for a while.\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n System.out.println(\"Thread \" + threadName + \" interrupted.\");\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 public static void main(String args[]) {\n RunnableDemo R1 = new RunnableDemo( \"Thread-1\");\n R1.start();\n\n RunnableDemo R2 = new RunnableDemo( \"Thread-2\");\n R2.start();\n }\n}"
},
{
"code": null,
"e": 3344,
"s": 3303,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3660,
"s": 3344,
"text": "Creating Thread-1\nStarting Thread-1\nCreating Thread-2\nStarting Thread-2\nRunning Thread-1\nThread: Thread-1, 4\nRunning Thread-2\nThread: Thread-2, 4\nThread: Thread-1, 3\nThread: Thread-2, 3\nThread: Thread-1, 2\nThread: Thread-2, 2\nThread: Thread-1, 1\nThread: Thread-2, 1\nThread Thread-1 exiting.\nThread Thread-2 exiting."
},
{
"code": null,
"e": 3901,
"s": 3660,
"text": "The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class."
},
{
"code": null,
"e": 3908,
"s": 3901,
"text": "Step 1"
},
{
"code": null,
"e": 4139,
"s": 3908,
"text": "You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method −"
},
{
"code": null,
"e": 4158,
"s": 4139,
"text": "public void run( )"
},
{
"code": null,
"e": 4165,
"s": 4158,
"text": "Step 2"
},
{
"code": null,
"e": 4329,
"s": 4165,
"text": "Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −"
},
{
"code": null,
"e": 4344,
"s": 4329,
"text": "void start( );"
},
{
"code": null,
"e": 4407,
"s": 4344,
"text": "Here is the preceding program rewritten to extend the Thread −"
},
{
"code": null,
"e": 4418,
"s": 4407,
"text": " Live Demo"
},
{
"code": null,
"e": 5491,
"s": 4418,
"text": "class ThreadDemo extends Thread {\n private Thread t;\n private String threadName;\n\n ThreadDemo( String name) {\n threadName = name;\n System.out.println(\"Creating \" + threadName );\n }\n\n public void run() {\n System.out.println(\"Running \" + threadName );\n try {\n for(int i = 4; i > 0; i--) {\n System.out.println(\"Thread: \" + threadName + \", \" + i);\n // Let the thread sleep for a while.\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n System.out.println(\"Thread \" + threadName + \" interrupted.\");\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 ThreadDemo T1 = new ThreadDemo( \"Thread-1\");\n T1.start();\n\n ThreadDemo T2 = new ThreadDemo( \"Thread-2\");\n T2.start();\n }\n}"
},
{
"code": null,
"e": 5532,
"s": 5491,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 5848,
"s": 5532,
"text": "Creating Thread-1\nStarting Thread-1\nCreating Thread-2\nStarting Thread-2\nRunning Thread-1\nThread: Thread-1, 4\nRunning Thread-2\nThread: Thread-2, 4\nThread: Thread-1, 3\nThread: Thread-2, 3\nThread: Thread-1, 2\nThread: Thread-2, 2\nThread: Thread-1, 1\nThread: Thread-2, 1\nThread Thread-1 exiting.\nThread Thread-2 exiting."
}
] |
Split Button Dropdowns with Bootstrap
|
Split button dropdowns use the same general style as the dropdown button but add a primary action along with the dropdown. Split buttons have the primary action on the left and a toggle on the right that displays the dropdown.
You can try to run the following code to split button dropdowns −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "btn-group">
<button type = "button" class = "btn btn-default">Admissions</button>
<button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown">
<span class = "caret"></span>
<span class = "sr-only">Toggle Dropdown</span>
</button>
<ul class = "dropdown-menu" role = "menu">
<li><a href = "#">Masters</a></li>
<li><a href = "#">Bachelors</a></li>
</ul>
</div>
<div class = "btn-group">
<button type = "button" class = "btn btn-primary">Faculty</button>
<button type = "button" class = "btn btn-primary dropdown-toggle" data-toggle = "dropdown">
<span class = "caret"></span>
<span class = "sr-only">Toggle Dropdown</span>
</button>
<ul class = "dropdown-menu" role = "menu">
<li><a href = "#">Management</a></li>
<li><a href = "#">Technical</a></li>
<li><a href = "#">Staff</a></li>
</ul>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1289,
"s": 1062,
"text": "Split button dropdowns use the same general style as the dropdown button but add a primary action along with the dropdown. Split buttons have the primary action on the left and a toggle on the right that displays the dropdown."
},
{
"code": null,
"e": 1355,
"s": 1289,
"text": "You can try to run the following code to split button dropdowns −"
},
{
"code": null,
"e": 1365,
"s": 1355,
"text": "Live Demo"
},
{
"code": null,
"e": 2730,
"s": 1365,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default\">Admissions</button>\n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" data-toggle = \"dropdown\">\n <span class = \"caret\"></span>\n <span class = \"sr-only\">Toggle Dropdown</span>\n </button>\n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Masters</a></li>\n <li><a href = \"#\">Bachelors</a></li>\n </ul>\n </div>\n <div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-primary\">Faculty</button>\n <button type = \"button\" class = \"btn btn-primary dropdown-toggle\" data-toggle = \"dropdown\">\n <span class = \"caret\"></span>\n <span class = \"sr-only\">Toggle Dropdown</span>\n </button>\n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Management</a></li>\n <li><a href = \"#\">Technical</a></li>\n <li><a href = \"#\">Staff</a></li>\n </ul>\n </div>\n </body>\n</html>"
}
] |
Selenium on Airflow: Automate a daily task on the web! | by Harry Daniels | Towards Data Science
|
This post demonstrates how to build an Airflow plugin, which uses the Selenium WebDriver, to automate a daily online task.
Increased productivity.
Greater quality.
Removing the possibility of human error and reducing manual labour.
Additional frequency and consistency (Working on the weekend!).
If your daily task involves the web, then using Selenium on Airflow could potentially save hundreds of hours per year and improve the quality and consistency of your work.
The goal of this post is to develop a plugin which utilises Selenium to automate a daily task on Airflow.
Setting up the Airflow environment.Developing the Selenium plugin.Using the Selenium plugin within an Airflow DAG.
Setting up the Airflow environment.
Developing the Selenium plugin.
Using the Selenium plugin within an Airflow DAG.
If you’d like to skip ahead, all the code discussed in this post is available on my GitHub here.
Below is a brief overview of topics and softwares covered:
Selenium: In a nutshell, Selenium automates browsers. Primarily it is used to automate web applications for testing purposes, however it isn’t limited to that at all. A key component of selenium is the WebDriver, the WebDriver API sends commands directly to the browser. Example commands could be navigating to a webpage, filling out a form, or even downloading a file. The WebDriver used in this post will be the Selenium/standalone-chrome driver.
Airflow: Airflow is a platform to programmatically author, schedule and monitor workflows. The key components of Airflow are the web server, scheduler, and workers. The web server refers to the Airflow user interface, while the scheduler executes your tasks on an array of workers as per predefined instructions.
Finally, to use Selenium and Airflow together, the containerisation software docker is also required.
Docker: Docker is a software which makes it easier to deploy and develop software via the use of containers. Containers allow a developer to package up an application with all of its requirements and also isolate the software from its environment to ensure it works in different development settings. A great feature of Docker is the compose tool which is used to define and run multi-container Docker applications.
We will use Docker in the first instance to setup our Airflow environment and then to spin up an additional Selenium Container as part of our plugin.
As mentioned above, Docker will be used to set up the Airflow environment. To do this go to https://github.com/puckel/docker-airflow and download the docker-compose-CeleryExecutor.yml file. This is a docker-compose file created by a Github user named Puckel which allows you to quickly get up and running with Airflow. The compose file opts for the Celery executor which is necessary if you require tasks to run concurrently as it scales out the number of workers.
There are some basic changes to make to the docker-compose file.
Rename the compose file: docker-compose.yml.
Uncomment the custom plugins volumes.
- ./plugins:/usr/local/airflow/plugin
To ensure that the Airflow containers have the correct permissions on the plugins and dags directory ensure that the directories exist on the host prior to running the compose.
Test that the environment runs locally using the docker-compose up command, the UI should be available at http://localhost:8080.
Before completing the environment, it is necessary to briefly explain how the Selenium plugin will work as some of its functionality will directly impact setup. The plugin will be covered in greater detail later in the post.
The plugin will execute the following steps:
Start a Selenium docker containerConfigure the remote Selenium driverSend commands to the driver: This will result in a file downloaded from the internet.Remove the running container
Start a Selenium docker container
Configure the remote Selenium driver
Send commands to the driver: This will result in a file downloaded from the internet.
Remove the running container
The steps above can be distilled into two categories:
Using Docker from Airflow.
Interacting with the remote container
The Airflow worker needs to be able to create the Selenium container and subsequently send commands to execute the task. As explained very well by Jérôme Petazzoni in this post, it is bad practice to spin up a Docker container within another container, and not necessary so long as a container exists and is accessible. The easiest way to allow the worker to create containers is by exposing the host Docker socket to the worker by mounting it as a volume in the docker-compose file.
worker: volumes: - /var/run/docker.sock:/var/run/docker.sock
The Airflow worker still cant access the host Docker socket due to not having the correct permissions so these will have to be changed. This can be achieved by creating a new Dockerfile called ‘Dockerfile-airflow’ which extends the puckel/docker-airflow base image as follows:
FROM puckel/docker-airflow:1.10.4USER rootRUN groupadd --gid 999 docker \ && usermod -aG docker airflowUSER airflow
The Dockerfile first calls the puckel/docker-airflow base image
As the root user, creates the docker user group with the id 999 and adds the airflow user to the group.
Sets the airflow user.
It is imperative that the docker group id (999) must be the same on both the worker and the host. To find out the host docker group id use the following command:
grep 'docker' /etc/group
Create the new docker image:
docker build -t docker_airflow -f Dockerfile-selenium .
The next thing to do is change the airflow image name in the Docker-compose file, from puckel/docker-airflow:latest to docker_airflow:latest. This means the compose file will use the newly created image.
The Airflow worker can now create Docker containers on the host, however still requires the Docker python package. Additional installations can also be handled in the Dockerfile. The installations below are necessary for the Selenium plugin and DAG.
RUN pip install docker && \ pip install selenium && \ pip install bs4 && \ pip install lxml && \ pip install boto3
To start a Selenium container with the plugin the image must already exist on the host machine:
docker pull selenium/standalone-chrome
Finally, for the worker container to send commands to the new Selenium container, they will both need to be on the same Docker network. Both containers will be on the external network: ‘container_bridge’ which is created with the following command:
docker network create container_bridge
The container bridge network also needs to be added to the compose file.
worker: networks: - default - container_bridgenetworks: default: container_bridge:
NB It is important to note that the above method for exposing the host docker sock to the worker container and setting permissions will only work in a linux environment, to configure a dev environment for MacOS please refer to these two brilliant articles:
Yet Another Scalable Apache Airflow With Docker Example Setup
Solving permission denied while trying to connect to Docker daemon socket from container in Mac OS
The Selenium plugin sends commands to the docker container via the remote driver, which it connects to over the container_bridge network. The Selenium commands will be added to the environment as a mounted volume in the home directory: {AIRFLOW_USER_HOME}
volumes: # Selenium scripts - ./selenium_scripts:/usr/local/airflow/selenium_scripts
The commands will come from a custom Python module (selenium_scripts) which needs to be in the Python Path. This can be done in the Airflow Dockerfile.
ENV PYTHONPATH=$PYTHONPATH:${AIRFLOW_USER_HOME}
The last change to the Airflow environment is to enable the Selenium container and Airflow workers to share files and content. This is required when downloading content from the internet with Selenium and can be achieved with an external named volume.
docker volume create downloads
The ‘downloads’ volume needs to be added to docker-compose file:
worker: volumes: - downloads:/usr/local/airflow/downloadsvolumes: downloads: external: true
When Docker volumes are created on containers, without the corresponding directories already pre-existing, they are created by the root user, which means that the container user won’t have write privileges. The simplest way to circumvent this is to create the directories as the container user during the initial build.
For the Airflow Dockerfile add the line:
RUN mkdir downloads
A new Dockerfile will have to be created for the Selenium container, this will be called Dockerfile-selenium.
FROM selenium/standalone-chromeRUN mkdir /home/seluser/downloads
Build both new images:
docker build -t docker_selenium -f Dockerfile-selenium .docker build -t docker_airflow -f Dockerfile-airflow .
The environment is now complete, the complete environments are below:
A great feature of Airflow is the plugins, plugins are an easy way to extend the existing feature set of Airflow. To integrate a new plugin with the existing airflow environment, simply move the plugin files into the plugins folder.
The Selenium plugin will work as follows:
Start the Selenium Docker container in the host environment.Configure the remote Selenium WebDriver on the docker container.Send commands to the WebDriver to fulfil the task.Stop and remove the container.
Start the Selenium Docker container in the host environment.
Configure the remote Selenium WebDriver on the docker container.
Send commands to the WebDriver to fulfil the task.
Stop and remove the container.
This method has been used over using the standalone Docker operator as it provides greater control and facilitates easier debugging.
The Selenium plugin will contain a Hook and Operator, Hooks handle external connections and make up the building blocks of an Operator. The operator will execute our task. The plugin folder structure is as follows:
.├── README.md├── __init__.py├── hooks│ ├── __init__.py│ └── Selenium_hook.py└── operators├── __init__.py└── Selenium_operator.py
To create a plugin, you need to derive the AirflowPlugin class and reference the objects you want to plug into Airflow, we do this in the __init__.py file:
The Selenium hook inherits from the BaseHook module, which is the base class for all hooks. The hook consists of several methods to start, stop and send commands to a Selenium container.
Creating the Container: The hook makes use of the Python Docker library to send commands to the host Docker socket and creates the Selenium container on the host. The external named volume (Downloads) is mounted on the local downloads directory which will be configured as the browser default downloads location. To enable interaction with the worker, the container_bridge network is also included.
Configuring the driver: Once the create_container method has been executed, the next step is to configure and connect to the driver so it meets the task requirements.
Since the Selenium container is on the container_bridge network, the WebDriver can be found on the network IP at the following location: <network IP>:4444/wd/hub . The driver can be connected to using the WebDriver remote.
The first step in configuring the driver is to use the Options class to enable the driver to run in headless mode and to set the window size to ensure the page content loads correctly. Headless mode essentially means that the driver doesn’t have a user interface.
options = Options()options.add_argument("--headless")options.add_argument("--window-size=1920x1080")
The second step is to enable the browser to download in headless mode. This is done by sending a post request to the driver which fixes the download behaviour.
driver.command_executor._commands["send_command"] = ( "POST", '/session/$sessionId/chromium/send_command')params = {'cmd': 'Page.setDownloadBehaviour', 'params': {'behavior': 'allow', 'downloadPath': <DOWNLOADS>}}driver.execute("send_command", params)
Executing a task: To keep the plugin as task agnostic as possible the Selenium commands have been abstracted to a separate python module to be imported at run time in the DAG. The one condition on each script is that they are imported as functions and the first argument is the driver. This will be covered in more detail later.
Removing the container: Once the task is complete the container can be removed.
As mentioned above, Airflow hooks are the building blocks for operators. The operator below uses the Selenium hook and Airflow’s execution context to run a Selenium task.
All Airflow operators must inherit the BaseOperator class, this class creates objects that become nodes in the DAG. A great feature of the Airflow operator is the ability to define template fields; these are Jinjafied fields that can accept Airflow macros when executed. The airflow_args variable is a template_field which means they can be set dynamically using macros at runtime.
Since the Airflow environment and Selenium plugin are now complete, the next step is to bring it all together in the form of an Airflow DAG. An Airflow DAG runs a collection of tasks is a predefined way.
The example DAG below is designed to download the daily podcast: Wake up to Money from the BBC and upload the mp3 file to S3 for later consumption. Wake Up to Money is an early morning financial radio programme on BBC Radio 5 Live with new episodes every weekday at 5am.
The Wake up to Money script uses the Selenium WebDriver to navigate to the url: https://www.bbc.co.uk/programmes/b0070lr5/episodes/downloads and download the latest episode.
Once the page has been rendered by the browser, Beautiful soup is used to parse the html for the download link. Calling the driver.get method on the download link starts the download, which is polled to completion. Once downloaded, the file is renamed so it is easy to keep track of between tasks.
As mentioned in the plugin section, the Selenium scripts need to be an executable function with the driver set as the first argument.
Once complete, ensure that the Selenium scripts are in the folder which was mounted on the Airflow environment and added to the Python path in the previous steps.
As mentioned above a DAG is a collection of tasks, the first step in creating a DAG, is describing how those tasks will run. The arguments used when creating a DAG object do just that.
Since the podcast airs every weekday at 5am, the DAG schedule_interval will be set to pick up each episode at 7am. It’s not that easy to set an Airflow chron expression to run only on weekdays so instead the DAG will run every day and a branch operator will be used to set the task based on the day of the week.
The DAG schedule is now defined, the next step is to add the tasks. The DAG tasks are:
Start: Starts the DAG
Weekday Branch: Determines which branch of the DAG to follow depending on whether the execution day is a weekday or not.
Get Podcast: Downloads the podcast.
Upload Podcast to S3: Uploads the podcast to S3.
Remove local Podcast: Removes the local copy of the podcast.
End: Ends the DAG.
The Start and End tasks make use of the Airflow DummyOperator, they don’t do anything but a useful when grouping tasks.
The Selenium plugin will be used in the download podcast task. The SeleniumOperator will execute the download_podcast function which is imported from at from the Selenium scripts module at runtime. Once the podcast is downloaded it will be saved under the new name: episode_{{ds_nodash}}.mp3 , but since the filename is a templated field, this will be rendered at runtime. e.g. On the 2019–10–13 the file name will be episode_20191013.mp3 .
The Weekday Branch task, splits the DAG into two branches based on whether the execution day is a weekday or weekend. The Branch task uses the Airflow Python Branch Operator to set the next task based on the output of the weekday_branch function.
If the execution day is a weekday, the next task to be run by the DAG is the get_podcast task, if the execution day is a weekend, the next task to run is end.
The last two tasks are: Upload podcast to S3 and Remove local podcast. These both use the PythonOperator which is extended to ‘Jinjafy’ the arguments. This is necessary to keep track of the podcast file name, as per the Selenium operator.
The S3 function will require an S3 connection with the name: S3_conn_id.
Finally the last step is to define the task order, note how the weekday_branch task precedes both the get_podcast and end task.
start >> weekday_branchweekday_branch >> get_podcastget_podcast >> upload_podcast_to_s3upload_podcast_to_s3 >> remove_local_podcastremove_local_podcast >> endweekday_branch >> end
I hope you enjoyed this post; if you have any questions or suggestions, or even ideas for future posts, let me know in the comments section and I’ll do my best to get back to you.
Please checkout my other Airflow posts:
|
[
{
"code": null,
"e": 295,
"s": 172,
"text": "This post demonstrates how to build an Airflow plugin, which uses the Selenium WebDriver, to automate a daily online task."
},
{
"code": null,
"e": 319,
"s": 295,
"text": "Increased productivity."
},
{
"code": null,
"e": 336,
"s": 319,
"text": "Greater quality."
},
{
"code": null,
"e": 404,
"s": 336,
"text": "Removing the possibility of human error and reducing manual labour."
},
{
"code": null,
"e": 468,
"s": 404,
"text": "Additional frequency and consistency (Working on the weekend!)."
},
{
"code": null,
"e": 640,
"s": 468,
"text": "If your daily task involves the web, then using Selenium on Airflow could potentially save hundreds of hours per year and improve the quality and consistency of your work."
},
{
"code": null,
"e": 746,
"s": 640,
"text": "The goal of this post is to develop a plugin which utilises Selenium to automate a daily task on Airflow."
},
{
"code": null,
"e": 861,
"s": 746,
"text": "Setting up the Airflow environment.Developing the Selenium plugin.Using the Selenium plugin within an Airflow DAG."
},
{
"code": null,
"e": 897,
"s": 861,
"text": "Setting up the Airflow environment."
},
{
"code": null,
"e": 929,
"s": 897,
"text": "Developing the Selenium plugin."
},
{
"code": null,
"e": 978,
"s": 929,
"text": "Using the Selenium plugin within an Airflow DAG."
},
{
"code": null,
"e": 1075,
"s": 978,
"text": "If you’d like to skip ahead, all the code discussed in this post is available on my GitHub here."
},
{
"code": null,
"e": 1134,
"s": 1075,
"text": "Below is a brief overview of topics and softwares covered:"
},
{
"code": null,
"e": 1583,
"s": 1134,
"text": "Selenium: In a nutshell, Selenium automates browsers. Primarily it is used to automate web applications for testing purposes, however it isn’t limited to that at all. A key component of selenium is the WebDriver, the WebDriver API sends commands directly to the browser. Example commands could be navigating to a webpage, filling out a form, or even downloading a file. The WebDriver used in this post will be the Selenium/standalone-chrome driver."
},
{
"code": null,
"e": 1896,
"s": 1583,
"text": "Airflow: Airflow is a platform to programmatically author, schedule and monitor workflows. The key components of Airflow are the web server, scheduler, and workers. The web server refers to the Airflow user interface, while the scheduler executes your tasks on an array of workers as per predefined instructions."
},
{
"code": null,
"e": 1998,
"s": 1896,
"text": "Finally, to use Selenium and Airflow together, the containerisation software docker is also required."
},
{
"code": null,
"e": 2414,
"s": 1998,
"text": "Docker: Docker is a software which makes it easier to deploy and develop software via the use of containers. Containers allow a developer to package up an application with all of its requirements and also isolate the software from its environment to ensure it works in different development settings. A great feature of Docker is the compose tool which is used to define and run multi-container Docker applications."
},
{
"code": null,
"e": 2564,
"s": 2414,
"text": "We will use Docker in the first instance to setup our Airflow environment and then to spin up an additional Selenium Container as part of our plugin."
},
{
"code": null,
"e": 3029,
"s": 2564,
"text": "As mentioned above, Docker will be used to set up the Airflow environment. To do this go to https://github.com/puckel/docker-airflow and download the docker-compose-CeleryExecutor.yml file. This is a docker-compose file created by a Github user named Puckel which allows you to quickly get up and running with Airflow. The compose file opts for the Celery executor which is necessary if you require tasks to run concurrently as it scales out the number of workers."
},
{
"code": null,
"e": 3094,
"s": 3029,
"text": "There are some basic changes to make to the docker-compose file."
},
{
"code": null,
"e": 3139,
"s": 3094,
"text": "Rename the compose file: docker-compose.yml."
},
{
"code": null,
"e": 3177,
"s": 3139,
"text": "Uncomment the custom plugins volumes."
},
{
"code": null,
"e": 3215,
"s": 3177,
"text": "- ./plugins:/usr/local/airflow/plugin"
},
{
"code": null,
"e": 3392,
"s": 3215,
"text": "To ensure that the Airflow containers have the correct permissions on the plugins and dags directory ensure that the directories exist on the host prior to running the compose."
},
{
"code": null,
"e": 3521,
"s": 3392,
"text": "Test that the environment runs locally using the docker-compose up command, the UI should be available at http://localhost:8080."
},
{
"code": null,
"e": 3746,
"s": 3521,
"text": "Before completing the environment, it is necessary to briefly explain how the Selenium plugin will work as some of its functionality will directly impact setup. The plugin will be covered in greater detail later in the post."
},
{
"code": null,
"e": 3791,
"s": 3746,
"text": "The plugin will execute the following steps:"
},
{
"code": null,
"e": 3974,
"s": 3791,
"text": "Start a Selenium docker containerConfigure the remote Selenium driverSend commands to the driver: This will result in a file downloaded from the internet.Remove the running container"
},
{
"code": null,
"e": 4008,
"s": 3974,
"text": "Start a Selenium docker container"
},
{
"code": null,
"e": 4045,
"s": 4008,
"text": "Configure the remote Selenium driver"
},
{
"code": null,
"e": 4131,
"s": 4045,
"text": "Send commands to the driver: This will result in a file downloaded from the internet."
},
{
"code": null,
"e": 4160,
"s": 4131,
"text": "Remove the running container"
},
{
"code": null,
"e": 4214,
"s": 4160,
"text": "The steps above can be distilled into two categories:"
},
{
"code": null,
"e": 4241,
"s": 4214,
"text": "Using Docker from Airflow."
},
{
"code": null,
"e": 4279,
"s": 4241,
"text": "Interacting with the remote container"
},
{
"code": null,
"e": 4765,
"s": 4279,
"text": "The Airflow worker needs to be able to create the Selenium container and subsequently send commands to execute the task. As explained very well by Jérôme Petazzoni in this post, it is bad practice to spin up a Docker container within another container, and not necessary so long as a container exists and is accessible. The easiest way to allow the worker to create containers is by exposing the host Docker socket to the worker by mounting it as a volume in the docker-compose file."
},
{
"code": null,
"e": 4835,
"s": 4765,
"text": "worker: volumes: - /var/run/docker.sock:/var/run/docker.sock"
},
{
"code": null,
"e": 5112,
"s": 4835,
"text": "The Airflow worker still cant access the host Docker socket due to not having the correct permissions so these will have to be changed. This can be achieved by creating a new Dockerfile called ‘Dockerfile-airflow’ which extends the puckel/docker-airflow base image as follows:"
},
{
"code": null,
"e": 5230,
"s": 5112,
"text": "FROM puckel/docker-airflow:1.10.4USER rootRUN groupadd --gid 999 docker \\ && usermod -aG docker airflowUSER airflow"
},
{
"code": null,
"e": 5294,
"s": 5230,
"text": "The Dockerfile first calls the puckel/docker-airflow base image"
},
{
"code": null,
"e": 5398,
"s": 5294,
"text": "As the root user, creates the docker user group with the id 999 and adds the airflow user to the group."
},
{
"code": null,
"e": 5421,
"s": 5398,
"text": "Sets the airflow user."
},
{
"code": null,
"e": 5583,
"s": 5421,
"text": "It is imperative that the docker group id (999) must be the same on both the worker and the host. To find out the host docker group id use the following command:"
},
{
"code": null,
"e": 5608,
"s": 5583,
"text": "grep 'docker' /etc/group"
},
{
"code": null,
"e": 5637,
"s": 5608,
"text": "Create the new docker image:"
},
{
"code": null,
"e": 5693,
"s": 5637,
"text": "docker build -t docker_airflow -f Dockerfile-selenium ."
},
{
"code": null,
"e": 5897,
"s": 5693,
"text": "The next thing to do is change the airflow image name in the Docker-compose file, from puckel/docker-airflow:latest to docker_airflow:latest. This means the compose file will use the newly created image."
},
{
"code": null,
"e": 6147,
"s": 5897,
"text": "The Airflow worker can now create Docker containers on the host, however still requires the Docker python package. Additional installations can also be handled in the Dockerfile. The installations below are necessary for the Selenium plugin and DAG."
},
{
"code": null,
"e": 6274,
"s": 6147,
"text": "RUN pip install docker && \\ pip install selenium && \\ pip install bs4 && \\ pip install lxml && \\ pip install boto3"
},
{
"code": null,
"e": 6370,
"s": 6274,
"text": "To start a Selenium container with the plugin the image must already exist on the host machine:"
},
{
"code": null,
"e": 6409,
"s": 6370,
"text": "docker pull selenium/standalone-chrome"
},
{
"code": null,
"e": 6658,
"s": 6409,
"text": "Finally, for the worker container to send commands to the new Selenium container, they will both need to be on the same Docker network. Both containers will be on the external network: ‘container_bridge’ which is created with the following command:"
},
{
"code": null,
"e": 6697,
"s": 6658,
"text": "docker network create container_bridge"
},
{
"code": null,
"e": 6770,
"s": 6697,
"text": "The container bridge network also needs to be added to the compose file."
},
{
"code": null,
"e": 6876,
"s": 6770,
"text": "worker: networks: - default - container_bridgenetworks: default: container_bridge:"
},
{
"code": null,
"e": 7133,
"s": 6876,
"text": "NB It is important to note that the above method for exposing the host docker sock to the worker container and setting permissions will only work in a linux environment, to configure a dev environment for MacOS please refer to these two brilliant articles:"
},
{
"code": null,
"e": 7195,
"s": 7133,
"text": "Yet Another Scalable Apache Airflow With Docker Example Setup"
},
{
"code": null,
"e": 7294,
"s": 7195,
"text": "Solving permission denied while trying to connect to Docker daemon socket from container in Mac OS"
},
{
"code": null,
"e": 7550,
"s": 7294,
"text": "The Selenium plugin sends commands to the docker container via the remote driver, which it connects to over the container_bridge network. The Selenium commands will be added to the environment as a mounted volume in the home directory: {AIRFLOW_USER_HOME}"
},
{
"code": null,
"e": 7642,
"s": 7550,
"text": "volumes: # Selenium scripts - ./selenium_scripts:/usr/local/airflow/selenium_scripts"
},
{
"code": null,
"e": 7794,
"s": 7642,
"text": "The commands will come from a custom Python module (selenium_scripts) which needs to be in the Python Path. This can be done in the Airflow Dockerfile."
},
{
"code": null,
"e": 7842,
"s": 7794,
"text": "ENV PYTHONPATH=$PYTHONPATH:${AIRFLOW_USER_HOME}"
},
{
"code": null,
"e": 8094,
"s": 7842,
"text": "The last change to the Airflow environment is to enable the Selenium container and Airflow workers to share files and content. This is required when downloading content from the internet with Selenium and can be achieved with an external named volume."
},
{
"code": null,
"e": 8125,
"s": 8094,
"text": "docker volume create downloads"
},
{
"code": null,
"e": 8190,
"s": 8125,
"text": "The ‘downloads’ volume needs to be added to docker-compose file:"
},
{
"code": null,
"e": 8307,
"s": 8190,
"text": "worker: volumes: - downloads:/usr/local/airflow/downloadsvolumes: downloads: external: true"
},
{
"code": null,
"e": 8627,
"s": 8307,
"text": "When Docker volumes are created on containers, without the corresponding directories already pre-existing, they are created by the root user, which means that the container user won’t have write privileges. The simplest way to circumvent this is to create the directories as the container user during the initial build."
},
{
"code": null,
"e": 8668,
"s": 8627,
"text": "For the Airflow Dockerfile add the line:"
},
{
"code": null,
"e": 8688,
"s": 8668,
"text": "RUN mkdir downloads"
},
{
"code": null,
"e": 8798,
"s": 8688,
"text": "A new Dockerfile will have to be created for the Selenium container, this will be called Dockerfile-selenium."
},
{
"code": null,
"e": 8863,
"s": 8798,
"text": "FROM selenium/standalone-chromeRUN mkdir /home/seluser/downloads"
},
{
"code": null,
"e": 8886,
"s": 8863,
"text": "Build both new images:"
},
{
"code": null,
"e": 8997,
"s": 8886,
"text": "docker build -t docker_selenium -f Dockerfile-selenium .docker build -t docker_airflow -f Dockerfile-airflow ."
},
{
"code": null,
"e": 9067,
"s": 8997,
"text": "The environment is now complete, the complete environments are below:"
},
{
"code": null,
"e": 9300,
"s": 9067,
"text": "A great feature of Airflow is the plugins, plugins are an easy way to extend the existing feature set of Airflow. To integrate a new plugin with the existing airflow environment, simply move the plugin files into the plugins folder."
},
{
"code": null,
"e": 9342,
"s": 9300,
"text": "The Selenium plugin will work as follows:"
},
{
"code": null,
"e": 9547,
"s": 9342,
"text": "Start the Selenium Docker container in the host environment.Configure the remote Selenium WebDriver on the docker container.Send commands to the WebDriver to fulfil the task.Stop and remove the container."
},
{
"code": null,
"e": 9608,
"s": 9547,
"text": "Start the Selenium Docker container in the host environment."
},
{
"code": null,
"e": 9673,
"s": 9608,
"text": "Configure the remote Selenium WebDriver on the docker container."
},
{
"code": null,
"e": 9724,
"s": 9673,
"text": "Send commands to the WebDriver to fulfil the task."
},
{
"code": null,
"e": 9755,
"s": 9724,
"text": "Stop and remove the container."
},
{
"code": null,
"e": 9888,
"s": 9755,
"text": "This method has been used over using the standalone Docker operator as it provides greater control and facilitates easier debugging."
},
{
"code": null,
"e": 10103,
"s": 9888,
"text": "The Selenium plugin will contain a Hook and Operator, Hooks handle external connections and make up the building blocks of an Operator. The operator will execute our task. The plugin folder structure is as follows:"
},
{
"code": null,
"e": 10233,
"s": 10103,
"text": ".├── README.md├── __init__.py├── hooks│ ├── __init__.py│ └── Selenium_hook.py└── operators├── __init__.py└── Selenium_operator.py"
},
{
"code": null,
"e": 10389,
"s": 10233,
"text": "To create a plugin, you need to derive the AirflowPlugin class and reference the objects you want to plug into Airflow, we do this in the __init__.py file:"
},
{
"code": null,
"e": 10576,
"s": 10389,
"text": "The Selenium hook inherits from the BaseHook module, which is the base class for all hooks. The hook consists of several methods to start, stop and send commands to a Selenium container."
},
{
"code": null,
"e": 10975,
"s": 10576,
"text": "Creating the Container: The hook makes use of the Python Docker library to send commands to the host Docker socket and creates the Selenium container on the host. The external named volume (Downloads) is mounted on the local downloads directory which will be configured as the browser default downloads location. To enable interaction with the worker, the container_bridge network is also included."
},
{
"code": null,
"e": 11142,
"s": 10975,
"text": "Configuring the driver: Once the create_container method has been executed, the next step is to configure and connect to the driver so it meets the task requirements."
},
{
"code": null,
"e": 11365,
"s": 11142,
"text": "Since the Selenium container is on the container_bridge network, the WebDriver can be found on the network IP at the following location: <network IP>:4444/wd/hub . The driver can be connected to using the WebDriver remote."
},
{
"code": null,
"e": 11629,
"s": 11365,
"text": "The first step in configuring the driver is to use the Options class to enable the driver to run in headless mode and to set the window size to ensure the page content loads correctly. Headless mode essentially means that the driver doesn’t have a user interface."
},
{
"code": null,
"e": 11730,
"s": 11629,
"text": "options = Options()options.add_argument(\"--headless\")options.add_argument(\"--window-size=1920x1080\")"
},
{
"code": null,
"e": 11890,
"s": 11730,
"text": "The second step is to enable the browser to download in headless mode. This is done by sending a post request to the driver which fixes the download behaviour."
},
{
"code": null,
"e": 12174,
"s": 11890,
"text": "driver.command_executor._commands[\"send_command\"] = ( \"POST\", '/session/$sessionId/chromium/send_command')params = {'cmd': 'Page.setDownloadBehaviour', 'params': {'behavior': 'allow', 'downloadPath': <DOWNLOADS>}}driver.execute(\"send_command\", params)"
},
{
"code": null,
"e": 12503,
"s": 12174,
"text": "Executing a task: To keep the plugin as task agnostic as possible the Selenium commands have been abstracted to a separate python module to be imported at run time in the DAG. The one condition on each script is that they are imported as functions and the first argument is the driver. This will be covered in more detail later."
},
{
"code": null,
"e": 12583,
"s": 12503,
"text": "Removing the container: Once the task is complete the container can be removed."
},
{
"code": null,
"e": 12754,
"s": 12583,
"text": "As mentioned above, Airflow hooks are the building blocks for operators. The operator below uses the Selenium hook and Airflow’s execution context to run a Selenium task."
},
{
"code": null,
"e": 13136,
"s": 12754,
"text": "All Airflow operators must inherit the BaseOperator class, this class creates objects that become nodes in the DAG. A great feature of the Airflow operator is the ability to define template fields; these are Jinjafied fields that can accept Airflow macros when executed. The airflow_args variable is a template_field which means they can be set dynamically using macros at runtime."
},
{
"code": null,
"e": 13340,
"s": 13136,
"text": "Since the Airflow environment and Selenium plugin are now complete, the next step is to bring it all together in the form of an Airflow DAG. An Airflow DAG runs a collection of tasks is a predefined way."
},
{
"code": null,
"e": 13611,
"s": 13340,
"text": "The example DAG below is designed to download the daily podcast: Wake up to Money from the BBC and upload the mp3 file to S3 for later consumption. Wake Up to Money is an early morning financial radio programme on BBC Radio 5 Live with new episodes every weekday at 5am."
},
{
"code": null,
"e": 13785,
"s": 13611,
"text": "The Wake up to Money script uses the Selenium WebDriver to navigate to the url: https://www.bbc.co.uk/programmes/b0070lr5/episodes/downloads and download the latest episode."
},
{
"code": null,
"e": 14083,
"s": 13785,
"text": "Once the page has been rendered by the browser, Beautiful soup is used to parse the html for the download link. Calling the driver.get method on the download link starts the download, which is polled to completion. Once downloaded, the file is renamed so it is easy to keep track of between tasks."
},
{
"code": null,
"e": 14217,
"s": 14083,
"text": "As mentioned in the plugin section, the Selenium scripts need to be an executable function with the driver set as the first argument."
},
{
"code": null,
"e": 14380,
"s": 14217,
"text": "Once complete, ensure that the Selenium scripts are in the folder which was mounted on the Airflow environment and added to the Python path in the previous steps."
},
{
"code": null,
"e": 14565,
"s": 14380,
"text": "As mentioned above a DAG is a collection of tasks, the first step in creating a DAG, is describing how those tasks will run. The arguments used when creating a DAG object do just that."
},
{
"code": null,
"e": 14877,
"s": 14565,
"text": "Since the podcast airs every weekday at 5am, the DAG schedule_interval will be set to pick up each episode at 7am. It’s not that easy to set an Airflow chron expression to run only on weekdays so instead the DAG will run every day and a branch operator will be used to set the task based on the day of the week."
},
{
"code": null,
"e": 14964,
"s": 14877,
"text": "The DAG schedule is now defined, the next step is to add the tasks. The DAG tasks are:"
},
{
"code": null,
"e": 14986,
"s": 14964,
"text": "Start: Starts the DAG"
},
{
"code": null,
"e": 15107,
"s": 14986,
"text": "Weekday Branch: Determines which branch of the DAG to follow depending on whether the execution day is a weekday or not."
},
{
"code": null,
"e": 15143,
"s": 15107,
"text": "Get Podcast: Downloads the podcast."
},
{
"code": null,
"e": 15192,
"s": 15143,
"text": "Upload Podcast to S3: Uploads the podcast to S3."
},
{
"code": null,
"e": 15253,
"s": 15192,
"text": "Remove local Podcast: Removes the local copy of the podcast."
},
{
"code": null,
"e": 15272,
"s": 15253,
"text": "End: Ends the DAG."
},
{
"code": null,
"e": 15392,
"s": 15272,
"text": "The Start and End tasks make use of the Airflow DummyOperator, they don’t do anything but a useful when grouping tasks."
},
{
"code": null,
"e": 15833,
"s": 15392,
"text": "The Selenium plugin will be used in the download podcast task. The SeleniumOperator will execute the download_podcast function which is imported from at from the Selenium scripts module at runtime. Once the podcast is downloaded it will be saved under the new name: episode_{{ds_nodash}}.mp3 , but since the filename is a templated field, this will be rendered at runtime. e.g. On the 2019–10–13 the file name will be episode_20191013.mp3 ."
},
{
"code": null,
"e": 16080,
"s": 15833,
"text": "The Weekday Branch task, splits the DAG into two branches based on whether the execution day is a weekday or weekend. The Branch task uses the Airflow Python Branch Operator to set the next task based on the output of the weekday_branch function."
},
{
"code": null,
"e": 16239,
"s": 16080,
"text": "If the execution day is a weekday, the next task to be run by the DAG is the get_podcast task, if the execution day is a weekend, the next task to run is end."
},
{
"code": null,
"e": 16478,
"s": 16239,
"text": "The last two tasks are: Upload podcast to S3 and Remove local podcast. These both use the PythonOperator which is extended to ‘Jinjafy’ the arguments. This is necessary to keep track of the podcast file name, as per the Selenium operator."
},
{
"code": null,
"e": 16551,
"s": 16478,
"text": "The S3 function will require an S3 connection with the name: S3_conn_id."
},
{
"code": null,
"e": 16679,
"s": 16551,
"text": "Finally the last step is to define the task order, note how the weekday_branch task precedes both the get_podcast and end task."
},
{
"code": null,
"e": 16859,
"s": 16679,
"text": "start >> weekday_branchweekday_branch >> get_podcastget_podcast >> upload_podcast_to_s3upload_podcast_to_s3 >> remove_local_podcastremove_local_podcast >> endweekday_branch >> end"
},
{
"code": null,
"e": 17039,
"s": 16859,
"text": "I hope you enjoyed this post; if you have any questions or suggestions, or even ideas for future posts, let me know in the comments section and I’ll do my best to get back to you."
}
] |
Dropdown Menus - Tkinter - GeeksforGeeks
|
26 Nov, 2020
Prerequisite: Python GUI – tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
OptionMenu is an important part of any GUI. It creates a popup menu, and a button to display it. It is similar to the combobox widgets commonly used on Windows.
Syntax:
OptionMenu(master,options)
Parameters:
master: This parameter is used to represents the parent window.
options: Contain the Menu values
Define the datatype of menu text, means integer, string, or any other datatypeSet initial menu text (That display initially)Add menu value in option as a listCreate Dropdown menu
Define the datatype of menu text, means integer, string, or any other datatype
Set initial menu text (That display initially)
Add menu value in option as a list
Create Dropdown menu
Below is an Implementation that creates Dropdown menus in Tkinter:
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry( "200x200" ) # Change the label textdef show(): label.config( text = clicked.get() ) # Dropdown menu optionsoptions = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] # datatype of menu textclicked = StringVar() # initial menu textclicked.set( "Monday" ) # Create Dropdown menudrop = OptionMenu( root , clicked , *options )drop.pack() # Create button, it will change label textbutton = Button( root , text = "click Me" , command = show ).pack() # Create Labellabel = Label( root , text = " " )label.pack() # Execute tkinterroot.mainloop()
Output:-
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 24351,
"s": 24316,
"text": "Prerequisite: Python GUI – tkinter"
},
{
"code": null,
"e": 24703,
"s": 24351,
"text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task."
},
{
"code": null,
"e": 24864,
"s": 24703,
"text": "OptionMenu is an important part of any GUI. It creates a popup menu, and a button to display it. It is similar to the combobox widgets commonly used on Windows."
},
{
"code": null,
"e": 24872,
"s": 24864,
"text": "Syntax:"
},
{
"code": null,
"e": 24899,
"s": 24872,
"text": "OptionMenu(master,options)"
},
{
"code": null,
"e": 24911,
"s": 24899,
"text": "Parameters:"
},
{
"code": null,
"e": 24975,
"s": 24911,
"text": "master: This parameter is used to represents the parent window."
},
{
"code": null,
"e": 25008,
"s": 24975,
"text": "options: Contain the Menu values"
},
{
"code": null,
"e": 25187,
"s": 25008,
"text": "Define the datatype of menu text, means integer, string, or any other datatypeSet initial menu text (That display initially)Add menu value in option as a listCreate Dropdown menu"
},
{
"code": null,
"e": 25266,
"s": 25187,
"text": "Define the datatype of menu text, means integer, string, or any other datatype"
},
{
"code": null,
"e": 25313,
"s": 25266,
"text": "Set initial menu text (That display initially)"
},
{
"code": null,
"e": 25348,
"s": 25313,
"text": "Add menu value in option as a list"
},
{
"code": null,
"e": 25369,
"s": 25348,
"text": "Create Dropdown menu"
},
{
"code": null,
"e": 25436,
"s": 25369,
"text": "Below is an Implementation that creates Dropdown menus in Tkinter:"
},
{
"code": null,
"e": 25444,
"s": 25436,
"text": "Python3"
},
{
"code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry( \"200x200\" ) # Change the label textdef show(): label.config( text = clicked.get() ) # Dropdown menu optionsoptions = [ \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"] # datatype of menu textclicked = StringVar() # initial menu textclicked.set( \"Monday\" ) # Create Dropdown menudrop = OptionMenu( root , clicked , *options )drop.pack() # Create button, it will change label textbutton = Button( root , text = \"click Me\" , command = show ).pack() # Create Labellabel = Label( root , text = \" \" )label.pack() # Execute tkinterroot.mainloop()",
"e": 26139,
"s": 25444,
"text": null
},
{
"code": null,
"e": 26148,
"s": 26139,
"text": "Output:-"
},
{
"code": null,
"e": 26163,
"s": 26148,
"text": "Python-tkinter"
},
{
"code": null,
"e": 26170,
"s": 26163,
"text": "Python"
},
{
"code": null,
"e": 26268,
"s": 26170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26300,
"s": 26268,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26356,
"s": 26300,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26398,
"s": 26356,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26440,
"s": 26398,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26462,
"s": 26440,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26501,
"s": 26462,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26532,
"s": 26501,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26587,
"s": 26532,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26616,
"s": 26587,
"text": "Create a directory in Python"
}
] |
GATE | GATE-CS-2004 | Question 90 - GeeksforGeeks
|
28 Jul, 2021
The recurrence equation
T(1) = 1
T(n) = 2T(n - 1) + n, n ≥ 2
evaluates to
a. 2n + 1– n – 2b. 2n – nc. 2n + 1 – 2n – 2d. 2n + n(A) a(B) b(C) c(D) dAnswer: (A)Explanation: If draw recursion tree, we can notice that total work done is,T(n) = n + 2(n-1) + 4(n-2) + 8(n-3) + 2n-1 * (n – n + 1)T(n) = n + 2(n-1) + 4(n-2) + 8(n-3) + 2n-1 * 1
To solve this series, let us use our school trick, we multiply T(n) with 2 and subtract after shifting terms.
2*T(n) = 2n + 4(n-1) + 8(n-2) + 16(n-3) + 2n
T(n) = n + 2(n-1) + 4(n-2) + 8(n-3) + 2n-1 * 1
We get
2T(n) - T(n) = -n + 2 + 4 + 8 + ..... 2n
T(n) = -n + 2n+1 - 2 [Applying GP sum formula for 2, 4, ...]
= 2n+1 - 2 - n
Alternate Way to solve is to use hit and try method.
Given T(n) = 2T(n-1) + n and T(1) = 1
For n = 2, T(2) = 2T(2-1) + 2
= 2T(1) + 2
= 2.1 + 2 = 4
Now when you will put n = 2 in all options,
only 1st option 2^(n+1) - n - 2 satisfies it.
Quiz of this Question
OnkarMarbhal
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
|
[
{
"code": null,
"e": 24043,
"s": 24015,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 24067,
"s": 24043,
"text": "The recurrence equation"
},
{
"code": null,
"e": 24105,
"s": 24067,
"text": "T(1) = 1\nT(n) = 2T(n - 1) + n, n ≥ 2 "
},
{
"code": null,
"e": 24118,
"s": 24105,
"text": "evaluates to"
},
{
"code": null,
"e": 24379,
"s": 24118,
"text": "a. 2n + 1– n – 2b. 2n – nc. 2n + 1 – 2n – 2d. 2n + n(A) a(B) b(C) c(D) dAnswer: (A)Explanation: If draw recursion tree, we can notice that total work done is,T(n) = n + 2(n-1) + 4(n-2) + 8(n-3) + 2n-1 * (n – n + 1)T(n) = n + 2(n-1) + 4(n-2) + 8(n-3) + 2n-1 * 1"
},
{
"code": null,
"e": 24489,
"s": 24379,
"text": "To solve this series, let us use our school trick, we multiply T(n) with 2 and subtract after shifting terms."
},
{
"code": null,
"e": 24588,
"s": 24489,
"text": "2*T(n) = 2n + 4(n-1) + 8(n-2) + 16(n-3) + 2n \n T(n) = n + 2(n-1) + 4(n-2) + 8(n-3) + 2n-1 * 1"
},
{
"code": null,
"e": 24595,
"s": 24588,
"text": "We get"
},
{
"code": null,
"e": 24718,
"s": 24595,
"text": "2T(n) - T(n) = -n + 2 + 4 + 8 + ..... 2n\nT(n) = -n + 2n+1 - 2 [Applying GP sum formula for 2, 4, ...]\n = 2n+1 - 2 - n"
},
{
"code": null,
"e": 24993,
"s": 24718,
"text": "Alternate Way to solve is to use hit and try method.\nGiven T(n) = 2T(n-1) + n and T(1) = 1\n\nFor n = 2, T(2) = 2T(2-1) + 2 \n = 2T(1) + 2 \n = 2.1 + 2 = 4\n\nNow when you will put n = 2 in all options, \nonly 1st option 2^(n+1) - n - 2 satisfies it. "
},
{
"code": null,
"e": 25015,
"s": 24993,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25028,
"s": 25015,
"text": "OnkarMarbhal"
},
{
"code": null,
"e": 25041,
"s": 25028,
"text": "GATE-CS-2004"
},
{
"code": null,
"e": 25059,
"s": 25041,
"text": "GATE-GATE-CS-2004"
},
{
"code": null,
"e": 25064,
"s": 25059,
"text": "GATE"
},
{
"code": null,
"e": 25162,
"s": 25064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25171,
"s": 25162,
"text": "Comments"
},
{
"code": null,
"e": 25184,
"s": 25171,
"text": "Old Comments"
},
{
"code": null,
"e": 25226,
"s": 25184,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25268,
"s": 25226,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 25302,
"s": 25268,
"text": "GATE | GATE-CS-2001 | Question 23"
},
{
"code": null,
"e": 25344,
"s": 25302,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 25378,
"s": 25344,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 25420,
"s": 25378,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25462,
"s": 25420,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 25516,
"s": 25462,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 25549,
"s": 25516,
"text": "GATE | GATE-CS-2004 | Question 3"
}
] |
Set the height of an image with CSS
|
The height property is used to set the height of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available.
You can try to run the following code to set the height of an image −
<html>
<head>
</head>
<body>
<img style = "border:2px solid green; height:100px;" src="/css/images/logo.png" />
<br />
<img style="border:2px solid green; height:50%;" src="/css/images/logo.png" />
</body>
</html>
|
[
{
"code": null,
"e": 1264,
"s": 1062,
"text": "The height property is used to set the height of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available."
},
{
"code": null,
"e": 1334,
"s": 1264,
"text": "You can try to run the following code to set the height of an image −"
},
{
"code": null,
"e": 1578,
"s": 1334,
"text": "<html>\n <head>\n </head>\n <body>\n <img style = \"border:2px solid green; height:100px;\" src=\"/css/images/logo.png\" />\n <br />\n <img style=\"border:2px solid green; height:50%;\" src=\"/css/images/logo.png\" />\n </body>\n</html>"
}
] |
\ln - Tex Command
|
\ln - Used to draw natural logarithm symbol.
{ \ln }
\ln command draws natural logarithm symbol.
\ln
ln
\ln
ln
\ln
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8031,
"s": 7986,
"text": "\\ln - Used to draw natural logarithm symbol."
},
{
"code": null,
"e": 8039,
"s": 8031,
"text": "{ \\ln }"
},
{
"code": null,
"e": 8083,
"s": 8039,
"text": "\\ln command draws natural logarithm symbol."
},
{
"code": null,
"e": 8095,
"s": 8083,
"text": "\n\\ln\n\nln\n\n\n"
},
{
"code": null,
"e": 8105,
"s": 8095,
"text": "\\ln\n\nln\n\n"
},
{
"code": null,
"e": 8109,
"s": 8105,
"text": "\\ln"
},
{
"code": null,
"e": 8141,
"s": 8109,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8154,
"s": 8141,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8187,
"s": 8154,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8200,
"s": 8187,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8232,
"s": 8200,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8268,
"s": 8232,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8303,
"s": 8268,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8320,
"s": 8303,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8353,
"s": 8320,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8367,
"s": 8353,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8399,
"s": 8367,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8414,
"s": 8399,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8421,
"s": 8414,
"text": " Print"
},
{
"code": null,
"e": 8432,
"s": 8421,
"text": " Add Notes"
}
] |
Check if a number is Palindrome in C++
|
Here we will see, how to check whether a number is a palindrome or not. The palindrome numbers are the same in both directions. For example, a number 12321 is a palindrome, but 12345 is not a palindrome.
The logic is very straight forward. We have to reverse the number, and if the reversed number is the same as the actual number, then that is a palindrome, otherwise not. Let us see the algorithm to get a better idea.
isPalindrome(n) −
input − The number n
output − true, if the number is a palindrome, otherwise, false
begin
temp := n
rev := 0
while n > 0, do
rev := rev * 10 + (n mod 10)
n := n / 10
done
if rev = temp, then
return true
return false
end
Live Demo
#include <iostream>
using namespace std;
bool isPalindrome(int number) {
int temp = number;
int rev = 0;
while(number > 0){
rev = 10 * rev + number % 10; //take the last digit, and attach with the rev number /= 10;
}
if(rev == temp)
return true;
return false;
}
int main() {
int n = 12321;
if(isPalindrome(n)){
cout << n << " is palindrome number";
} else {
cout << n << " is not a palindrome number";
}
}
12321 is palindrome number
|
[
{
"code": null,
"e": 1266,
"s": 1062,
"text": "Here we will see, how to check whether a number is a palindrome or not. The palindrome numbers are the same in both directions. For example, a number 12321 is a palindrome, but 12345 is not a palindrome."
},
{
"code": null,
"e": 1483,
"s": 1266,
"text": "The logic is very straight forward. We have to reverse the number, and if the reversed number is the same as the actual number, then that is a palindrome, otherwise not. Let us see the algorithm to get a better idea."
},
{
"code": null,
"e": 1501,
"s": 1483,
"text": "isPalindrome(n) −"
},
{
"code": null,
"e": 1522,
"s": 1501,
"text": "input − The number n"
},
{
"code": null,
"e": 1585,
"s": 1522,
"text": "output − true, if the number is a palindrome, otherwise, false"
},
{
"code": null,
"e": 1757,
"s": 1585,
"text": "begin\n temp := n\n rev := 0\n while n > 0, do\n rev := rev * 10 + (n mod 10)\n n := n / 10\n done\n if rev = temp, then\n return true\n return false\nend"
},
{
"code": null,
"e": 1768,
"s": 1757,
"text": " Live Demo"
},
{
"code": null,
"e": 2228,
"s": 1768,
"text": "#include <iostream>\nusing namespace std;\nbool isPalindrome(int number) {\n int temp = number;\n int rev = 0;\n while(number > 0){\n rev = 10 * rev + number % 10; //take the last digit, and attach with the rev number /= 10;\n }\n if(rev == temp)\n return true;\n return false;\n}\nint main() {\n int n = 12321;\n if(isPalindrome(n)){\n cout << n << \" is palindrome number\";\n } else {\n cout << n << \" is not a palindrome number\";\n }\n}"
},
{
"code": null,
"e": 2255,
"s": 2228,
"text": "12321 is palindrome number"
}
] |
C++ | Misc C++ | Question 8 - GeeksforGeeks
|
28 Jun, 2021
#include<iostream>using namespace std;int main (){ int cin; cin >> cin; cout << "cin" << cin; return 0;}
Thanks to Gokul Kumar for contributing this question.(A) error in using cin keyword(B) cin+junk value(C) cin+input(D) Runtime errorAnswer: (B)Explanation:Quiz of this Question
C++-Misc C++
Misc C++
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Different methods to reverse a string in C/C++
C++ | Exception Handling | Question 3
C++ | new and delete | Question 4
C++ | Operator Overloading | Question 10
C++ | Virtual Functions | Question 2
C++ | Virtual Functions | Question 4
|
[
{
"code": null,
"e": 24244,
"s": 24216,
"text": "\n28 Jun, 2021"
},
{
"code": "#include<iostream>using namespace std;int main (){ int cin; cin >> cin; cout << \"cin\" << cin; return 0;}",
"e": 24373,
"s": 24244,
"text": null
},
{
"code": null,
"e": 24549,
"s": 24373,
"text": "Thanks to Gokul Kumar for contributing this question.(A) error in using cin keyword(B) cin+junk value(C) cin+input(D) Runtime errorAnswer: (B)Explanation:Quiz of this Question"
},
{
"code": null,
"e": 24562,
"s": 24549,
"text": "C++-Misc C++"
},
{
"code": null,
"e": 24571,
"s": 24562,
"text": "Misc C++"
},
{
"code": null,
"e": 24582,
"s": 24571,
"text": "C Language"
},
{
"code": null,
"e": 24591,
"s": 24582,
"text": "C++ Quiz"
},
{
"code": null,
"e": 24689,
"s": 24591,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24701,
"s": 24689,
"text": "fork() in C"
},
{
"code": null,
"e": 24733,
"s": 24701,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 24755,
"s": 24733,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 24772,
"s": 24755,
"text": "Substring in C++"
},
{
"code": null,
"e": 24819,
"s": 24772,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 24857,
"s": 24819,
"text": "C++ | Exception Handling | Question 3"
},
{
"code": null,
"e": 24891,
"s": 24857,
"text": "C++ | new and delete | Question 4"
},
{
"code": null,
"e": 24932,
"s": 24891,
"text": "C++ | Operator Overloading | Question 10"
},
{
"code": null,
"e": 24969,
"s": 24932,
"text": "C++ | Virtual Functions | Question 2"
}
] |
switch statement in java
|
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
The syntax of enhanced for loop is −
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
// You can have any number of case statements.
default : // Optional
// Statements
}
The following rules apply to a switch statement −
The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums.
The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums.
You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
public class Test {
public static void main(String args[]) {
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Compile and run the above program using various command line arguments. This will produce the following result −
Well done
Your grade is C
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2556,
"s": 2377,
"text": "A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case."
},
{
"code": null,
"e": 2593,
"s": 2556,
"text": "The syntax of enhanced for loop is −"
},
{
"code": null,
"e": 2842,
"s": 2593,
"text": "switch(expression) {\n case value :\n // Statements\n break; // optional\n \n case value :\n // Statements\n break; // optional\n \n // You can have any number of case statements.\n default : // Optional\n // Statements\n}\n"
},
{
"code": null,
"e": 2892,
"s": 2842,
"text": "The following rules apply to a switch statement −"
},
{
"code": null,
"e": 3015,
"s": 2892,
"text": "The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums."
},
{
"code": null,
"e": 3138,
"s": 3015,
"text": "The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums."
},
{
"code": null,
"e": 3264,
"s": 3138,
"text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon."
},
{
"code": null,
"e": 3390,
"s": 3264,
"text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon."
},
{
"code": null,
"e": 3508,
"s": 3390,
"text": "The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal."
},
{
"code": null,
"e": 3626,
"s": 3508,
"text": "The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal."
},
{
"code": null,
"e": 3766,
"s": 3626,
"text": "When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached."
},
{
"code": null,
"e": 3906,
"s": 3766,
"text": "When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached."
},
{
"code": null,
"e": 4043,
"s": 3906,
"text": "When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement."
},
{
"code": null,
"e": 4180,
"s": 4043,
"text": "When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement."
},
{
"code": null,
"e": 4327,
"s": 4180,
"text": "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached."
},
{
"code": null,
"e": 4474,
"s": 4327,
"text": "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached."
},
{
"code": null,
"e": 4695,
"s": 4474,
"text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case."
},
{
"code": null,
"e": 4916,
"s": 4695,
"text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case."
},
{
"code": null,
"e": 5551,
"s": 4916,
"text": "public class Test {\n\n public static void main(String args[]) {\n // char grade = args[0].charAt(0);\n char grade = 'C';\n\n switch(grade) {\n case 'A' :\n System.out.println(\"Excellent!\"); \n break;\n case 'B' :\n case 'C' :\n System.out.println(\"Well done\");\n break;\n case 'D' :\n System.out.println(\"You passed\");\n case 'F' :\n System.out.println(\"Better try again\");\n break;\n default :\n System.out.println(\"Invalid grade\");\n }\n System.out.println(\"Your grade is \" + grade);\n }\n}"
},
{
"code": null,
"e": 5664,
"s": 5551,
"text": "Compile and run the above program using various command line arguments. This will produce the following result −"
},
{
"code": null,
"e": 5691,
"s": 5664,
"text": "Well done\nYour grade is C\n"
},
{
"code": null,
"e": 5724,
"s": 5691,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5740,
"s": 5724,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5773,
"s": 5740,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5789,
"s": 5773,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5824,
"s": 5789,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5838,
"s": 5824,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5872,
"s": 5838,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5886,
"s": 5872,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5923,
"s": 5886,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5938,
"s": 5923,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5971,
"s": 5938,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5990,
"s": 5971,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5997,
"s": 5990,
"text": " Print"
},
{
"code": null,
"e": 6008,
"s": 5997,
"text": " Add Notes"
}
] |
Algorithmic trading based on Technical Analysis in Python | by Eryk Lewinson | Towards Data Science
|
This is the fourth part of a series of articles on backtesting trading strategies in Python. The previous ones described the following topics:
introducing the zipline framework and presenting how to test basic strategies (link)
importing custom data to use with zipline (link)
evaluating the performance of trading strategies (link)
This time, the goal of the article is to show how to create trading strategies based on Technical Analysis (TA in short). Quoting Wikipedia, technical analysis is a “methodology for forecasting the direction of prices through the study of past market data, primarily price, and volume”.
In this article, I show how to use a popular Python library for calculating TA indicators — TA-Lib — together with the zipline backtesting framework. I will create 5 strategies and then investigate which one performs best over the investment horizon.
For this article I use the following libraries:
pyfolio 0.9.2numpy 1.14.6matplotlib 3.0.0pandas 0.22.0json 2.0.9empyrical 0.5.0zipline 1.3.0
Before creating the strategies, I define a few helper functions (here I only describe one of them, as it is the most important one affecting the backtests).
The function is used for getting the modified start date of the backtest. That is because I would like all the strategies to start working on the same day — the first day of 2016. However, some strategies based on technical indicators require a certain number of past observations — the so-called “warm-up period”. That is why using this function I calculate the date the backtest should start so that on the first day of the investment horizon I already have enough past observations to calculate the indicators. Please bear in mind that no trading decision can happen before the true start date of the backtest!
UPDATE: Actually there is no explicit need to use this approach. When we specify the bar_count in the data.history, zipline will automatically take the previous number of bars available, even when they are from a period before the backtest. I used this approach here.
In this article we use the following problem setting:
the investor has a capital of 10000$
the investment horizon covers years 2016–2017
the investor can only invest in Tesla’s stock
we assume no transactions costs — zero-commission trading
there is no short selling (the investor can only sell what he/she currently owns)
when the investor opens a position (buys the stock), the investor goes “all in” — allocates all available resources for the purchase
One of the reasons for selecting this range of dates is the fact that from mid-2018 the Quandl dataset was not updated and we want to keep the code as simple as possible. For details on how to load custom data (including the latest stock prices) into zipline, please refer to my previous article.
We start with the most basic strategy — Buy and Hold. The idea is that we buy a certain asset and do not do anything for the entire duration of the investment horizon. So at the first possible date, we buy as much Tesla stock as we can with our capital and do nothing later.
This simple strategy can also be considered a benchmark for more advanced ones — because there is no point in using a very complex strategy that generates less money (in general or due to transaction costs) than buying once and doing nothing.
We load the performance DataFrame:
buy_and_hold_results = pd.read_pickle('buy_and_hold.pkl')
What can happen here (it did not, but it is good to be aware of the possibility) is the sudden appearance of negative ending_cash. The reason for that could be the fact that the amount of shares we want to buy is calculated at the end of the day, using that day’s (closing) price. However, the order is executed on the next day, and the price can change significantly. In zipline the order is not rejected due to insufficient funds, but we can end up with a negative balance. This can happen mostly with strategies that go “all-in”. We could come up with some ways to avoid it — for example manually calculating the number of shares we can buy the next day and also including some markup to prevent such a situation from occurring, however, for simplicity we accept that this can happen.
We use a helper function to visualize some details of the strategy: the evolution of the portfolio’s value, the transactions on top of the price series, and the daily returns.
visualize_results(buy_and_hold_results, 'Buy and Hold Strategy - TSLA')
We also create the performance summary (using another helper function), which will be used in the last section:
buy_and_hold_perf = get_performance_summary(buy_and_hold_results.returns)
For brevity, we will not show all these steps (such as loading the performance DataFrame or getting the performance summary) for each strategy, because they are done in the same manner each time.
The second strategy we consider is based on the simple moving average (SMA). The logic of the strategy can be summarized by the following:
when the price crosses the 20-day SMA upwards — buy shares
when the price crosses the 20-day SMA downwards — sell all the shares
the moving average uses 19 prior days and the current day — the trading decision is for the next day
This is the first time we need to use the previously defined helper function to calculate the adjusted starting date, which will enable the investor to make trading decisions on the first trading day of 2016.
get_start_date('TSLA', '2016-01-04', 19)# '2015-12-04'
In the strategy below, we use the adjusted date as the start date.
Note: data.current(context.asset, ‘price’) is equivalent to price_history[-1].
Below we illustrate the strategy:
The plot below shows the price series together with the 20-day moving average. We have additionally marked the orders, which are executed on the next trading day after the signal was generated.
This strategy can be considered an extension of the previous one — instead of a single moving average, we use two averages of different window sizes. The 100-day moving average is the one that takes longer to adjust to sudden price changes, while the 20-day one is much faster to account for sudden changes.
The logic of the strategy is as follows:
when the fast MA crosses the slow one upwards, we buy the asset
when the slow MA crosses the fast one upwards, we sell the asset
Bear in mind that many different window-lengths combinations defining the fast and slow MA can be considered for this strategy.
For this strategy, we need to additionally take 100 days of data in order to counter the “warm-up period”.
Below we plotted the two moving averages on top of the price series. We see that the strategy generated much fewer signals than the one based on SMA.
MACD stands for Moving Average Convergence/Divergence and is an indicator/oscillator used in technical analysis of stock prices.
MACD is a collection of three time-series calculated using historical close prices:
the MACD series — the difference between the fast (shorter period) and slow (longer period) exponential moving averages
the signal — EMA on the MACD series
the divergence — the difference between the MACD series and the signal
MACD is parametrized by the number of days used to calculate the three moving averages — MACD(a,b,c). The parameter a corresponds to the fast EMA, b to the slow EMA, and c to the MACD signal EMA. The most common setup, also used in this article, is MACD(12,26,9). Historically, these numbers corresponded to 2 weeks, 1 month and 1.5 weeks based on a 6-day working week.
One thing to remember is that MACD is a lagging indicator, as it is based on moving averages. That is why the MACD is less useful for stocks that do not exhibit a trend or are trading with erratic price action.
The strategy we use in this article can be described by:
buy shares when the MACD crosses the signal line upwards
sell shares when the MACD crosses the signal line downwards
As before, to counter the warm-up period we need to ascertain that we have 34 observations to calculate the MACD.
Below we plot the MACD and the signal lines, where the crossovers indicate buy/sell signals. Additionally, one could plot the MACD divergence in the form of a barplot (it is commonly referred to as the MACD histogram).
RSI stands for the Relative Strength Index, which is another technical indicator we can use to create trading strategies. The RSI is classified as a momentum oscillator and it measures the velocity and magnitude of directional price movements. Momentum describes the rate at which the price of the asset rises or falls.
Without going into too many technical details, the RSI measures momentum as the ratio of higher closes to lower closes. Assets with more/stronger positive changes have higher RSI than assets with more/stronger negative changes.
The output of the RSI is a number on a scale from 0 to 100 and it is typically calculated on a 14-day basis. To generate the trading signals, it is common to specify the low and high levels of the RSI at 30 and 70, respectively. The interpretation of the thresholds is that the lower one indicates that the asset is oversold, and the upper one that the asset is overbought.
Sometimes, a medium level (halfway between low and high) is also specified, for example in case of strategies which also allow for short-selling. We can also select more extreme thresholds such as 20 and 80, which would then indicate stronger momentum. However, this should be specified using domain knowledge or by running backtests.
The strategy we consider can be described as:
when the RSI crosses the lower threshold (30) — buy the asset
when the RSI crosses the upper threshold (70) — sell the asset
Below we plot the RSI together with the upper and lower threshold.
The last step involves putting all the performance metrics into one DataFrame and inspecting the results. We can see that in the case of our backtest, the strategy based on the simple moving average performed best in terms of generated returns. It also had the highest Sharpe ratio — the highest excess return (in this case return, as we do not consider a risk-free asset) per unit of risk. The second-best strategy turned out to be the one based on the MACD. It is also good to notice that only these two performed better than the benchmark buy and hold strategy.
perf_df = pd.DataFrame({'Buy and Hold': buy_and_hold_perf, 'Simple Moving Average': sma_perf, 'Moving Average Crossover': mac_perf, 'MACD': macd_perf, 'RSI': rsi_perf})perf_df.transpose()
In this short article, I showed how to combine zipline with talib in order to backtest trading strategies based on popular technical indicators such as moving averages, the MACD, the RSI, etc. But this was only the beginning, as it is possible to create much more sophisticated strategies.
Some of the possible future directions:
include multiple assets into the strategies
allow for short-selling
mix the indicators
backtest different parameters for each strategy to find the best-performing ones
We must also remember that the fact that the strategy performed well in the past is no guarantee that this will happen again in the future.
As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. You can find the code used for this article on my GitHub.
Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!
Below you can find the other articles in the series:
building algorithmic trading strategies based on the mean-variance analysis (link)
I recently published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packt’s website.
|
[
{
"code": null,
"e": 314,
"s": 171,
"text": "This is the fourth part of a series of articles on backtesting trading strategies in Python. The previous ones described the following topics:"
},
{
"code": null,
"e": 399,
"s": 314,
"text": "introducing the zipline framework and presenting how to test basic strategies (link)"
},
{
"code": null,
"e": 448,
"s": 399,
"text": "importing custom data to use with zipline (link)"
},
{
"code": null,
"e": 504,
"s": 448,
"text": "evaluating the performance of trading strategies (link)"
},
{
"code": null,
"e": 791,
"s": 504,
"text": "This time, the goal of the article is to show how to create trading strategies based on Technical Analysis (TA in short). Quoting Wikipedia, technical analysis is a “methodology for forecasting the direction of prices through the study of past market data, primarily price, and volume”."
},
{
"code": null,
"e": 1042,
"s": 791,
"text": "In this article, I show how to use a popular Python library for calculating TA indicators — TA-Lib — together with the zipline backtesting framework. I will create 5 strategies and then investigate which one performs best over the investment horizon."
},
{
"code": null,
"e": 1090,
"s": 1042,
"text": "For this article I use the following libraries:"
},
{
"code": null,
"e": 1205,
"s": 1090,
"text": "pyfolio 0.9.2numpy 1.14.6matplotlib 3.0.0pandas 0.22.0json 2.0.9empyrical 0.5.0zipline 1.3.0"
},
{
"code": null,
"e": 1362,
"s": 1205,
"text": "Before creating the strategies, I define a few helper functions (here I only describe one of them, as it is the most important one affecting the backtests)."
},
{
"code": null,
"e": 1976,
"s": 1362,
"text": "The function is used for getting the modified start date of the backtest. That is because I would like all the strategies to start working on the same day — the first day of 2016. However, some strategies based on technical indicators require a certain number of past observations — the so-called “warm-up period”. That is why using this function I calculate the date the backtest should start so that on the first day of the investment horizon I already have enough past observations to calculate the indicators. Please bear in mind that no trading decision can happen before the true start date of the backtest!"
},
{
"code": null,
"e": 2244,
"s": 1976,
"text": "UPDATE: Actually there is no explicit need to use this approach. When we specify the bar_count in the data.history, zipline will automatically take the previous number of bars available, even when they are from a period before the backtest. I used this approach here."
},
{
"code": null,
"e": 2298,
"s": 2244,
"text": "In this article we use the following problem setting:"
},
{
"code": null,
"e": 2335,
"s": 2298,
"text": "the investor has a capital of 10000$"
},
{
"code": null,
"e": 2381,
"s": 2335,
"text": "the investment horizon covers years 2016–2017"
},
{
"code": null,
"e": 2427,
"s": 2381,
"text": "the investor can only invest in Tesla’s stock"
},
{
"code": null,
"e": 2485,
"s": 2427,
"text": "we assume no transactions costs — zero-commission trading"
},
{
"code": null,
"e": 2567,
"s": 2485,
"text": "there is no short selling (the investor can only sell what he/she currently owns)"
},
{
"code": null,
"e": 2700,
"s": 2567,
"text": "when the investor opens a position (buys the stock), the investor goes “all in” — allocates all available resources for the purchase"
},
{
"code": null,
"e": 2997,
"s": 2700,
"text": "One of the reasons for selecting this range of dates is the fact that from mid-2018 the Quandl dataset was not updated and we want to keep the code as simple as possible. For details on how to load custom data (including the latest stock prices) into zipline, please refer to my previous article."
},
{
"code": null,
"e": 3272,
"s": 2997,
"text": "We start with the most basic strategy — Buy and Hold. The idea is that we buy a certain asset and do not do anything for the entire duration of the investment horizon. So at the first possible date, we buy as much Tesla stock as we can with our capital and do nothing later."
},
{
"code": null,
"e": 3515,
"s": 3272,
"text": "This simple strategy can also be considered a benchmark for more advanced ones — because there is no point in using a very complex strategy that generates less money (in general or due to transaction costs) than buying once and doing nothing."
},
{
"code": null,
"e": 3550,
"s": 3515,
"text": "We load the performance DataFrame:"
},
{
"code": null,
"e": 3608,
"s": 3550,
"text": "buy_and_hold_results = pd.read_pickle('buy_and_hold.pkl')"
},
{
"code": null,
"e": 4396,
"s": 3608,
"text": "What can happen here (it did not, but it is good to be aware of the possibility) is the sudden appearance of negative ending_cash. The reason for that could be the fact that the amount of shares we want to buy is calculated at the end of the day, using that day’s (closing) price. However, the order is executed on the next day, and the price can change significantly. In zipline the order is not rejected due to insufficient funds, but we can end up with a negative balance. This can happen mostly with strategies that go “all-in”. We could come up with some ways to avoid it — for example manually calculating the number of shares we can buy the next day and also including some markup to prevent such a situation from occurring, however, for simplicity we accept that this can happen."
},
{
"code": null,
"e": 4572,
"s": 4396,
"text": "We use a helper function to visualize some details of the strategy: the evolution of the portfolio’s value, the transactions on top of the price series, and the daily returns."
},
{
"code": null,
"e": 4644,
"s": 4572,
"text": "visualize_results(buy_and_hold_results, 'Buy and Hold Strategy - TSLA')"
},
{
"code": null,
"e": 4756,
"s": 4644,
"text": "We also create the performance summary (using another helper function), which will be used in the last section:"
},
{
"code": null,
"e": 4830,
"s": 4756,
"text": "buy_and_hold_perf = get_performance_summary(buy_and_hold_results.returns)"
},
{
"code": null,
"e": 5026,
"s": 4830,
"text": "For brevity, we will not show all these steps (such as loading the performance DataFrame or getting the performance summary) for each strategy, because they are done in the same manner each time."
},
{
"code": null,
"e": 5165,
"s": 5026,
"text": "The second strategy we consider is based on the simple moving average (SMA). The logic of the strategy can be summarized by the following:"
},
{
"code": null,
"e": 5224,
"s": 5165,
"text": "when the price crosses the 20-day SMA upwards — buy shares"
},
{
"code": null,
"e": 5294,
"s": 5224,
"text": "when the price crosses the 20-day SMA downwards — sell all the shares"
},
{
"code": null,
"e": 5395,
"s": 5294,
"text": "the moving average uses 19 prior days and the current day — the trading decision is for the next day"
},
{
"code": null,
"e": 5604,
"s": 5395,
"text": "This is the first time we need to use the previously defined helper function to calculate the adjusted starting date, which will enable the investor to make trading decisions on the first trading day of 2016."
},
{
"code": null,
"e": 5659,
"s": 5604,
"text": "get_start_date('TSLA', '2016-01-04', 19)# '2015-12-04'"
},
{
"code": null,
"e": 5726,
"s": 5659,
"text": "In the strategy below, we use the adjusted date as the start date."
},
{
"code": null,
"e": 5805,
"s": 5726,
"text": "Note: data.current(context.asset, ‘price’) is equivalent to price_history[-1]."
},
{
"code": null,
"e": 5839,
"s": 5805,
"text": "Below we illustrate the strategy:"
},
{
"code": null,
"e": 6033,
"s": 5839,
"text": "The plot below shows the price series together with the 20-day moving average. We have additionally marked the orders, which are executed on the next trading day after the signal was generated."
},
{
"code": null,
"e": 6341,
"s": 6033,
"text": "This strategy can be considered an extension of the previous one — instead of a single moving average, we use two averages of different window sizes. The 100-day moving average is the one that takes longer to adjust to sudden price changes, while the 20-day one is much faster to account for sudden changes."
},
{
"code": null,
"e": 6382,
"s": 6341,
"text": "The logic of the strategy is as follows:"
},
{
"code": null,
"e": 6446,
"s": 6382,
"text": "when the fast MA crosses the slow one upwards, we buy the asset"
},
{
"code": null,
"e": 6511,
"s": 6446,
"text": "when the slow MA crosses the fast one upwards, we sell the asset"
},
{
"code": null,
"e": 6639,
"s": 6511,
"text": "Bear in mind that many different window-lengths combinations defining the fast and slow MA can be considered for this strategy."
},
{
"code": null,
"e": 6746,
"s": 6639,
"text": "For this strategy, we need to additionally take 100 days of data in order to counter the “warm-up period”."
},
{
"code": null,
"e": 6896,
"s": 6746,
"text": "Below we plotted the two moving averages on top of the price series. We see that the strategy generated much fewer signals than the one based on SMA."
},
{
"code": null,
"e": 7025,
"s": 6896,
"text": "MACD stands for Moving Average Convergence/Divergence and is an indicator/oscillator used in technical analysis of stock prices."
},
{
"code": null,
"e": 7109,
"s": 7025,
"text": "MACD is a collection of three time-series calculated using historical close prices:"
},
{
"code": null,
"e": 7229,
"s": 7109,
"text": "the MACD series — the difference between the fast (shorter period) and slow (longer period) exponential moving averages"
},
{
"code": null,
"e": 7265,
"s": 7229,
"text": "the signal — EMA on the MACD series"
},
{
"code": null,
"e": 7336,
"s": 7265,
"text": "the divergence — the difference between the MACD series and the signal"
},
{
"code": null,
"e": 7706,
"s": 7336,
"text": "MACD is parametrized by the number of days used to calculate the three moving averages — MACD(a,b,c). The parameter a corresponds to the fast EMA, b to the slow EMA, and c to the MACD signal EMA. The most common setup, also used in this article, is MACD(12,26,9). Historically, these numbers corresponded to 2 weeks, 1 month and 1.5 weeks based on a 6-day working week."
},
{
"code": null,
"e": 7917,
"s": 7706,
"text": "One thing to remember is that MACD is a lagging indicator, as it is based on moving averages. That is why the MACD is less useful for stocks that do not exhibit a trend or are trading with erratic price action."
},
{
"code": null,
"e": 7974,
"s": 7917,
"text": "The strategy we use in this article can be described by:"
},
{
"code": null,
"e": 8031,
"s": 7974,
"text": "buy shares when the MACD crosses the signal line upwards"
},
{
"code": null,
"e": 8091,
"s": 8031,
"text": "sell shares when the MACD crosses the signal line downwards"
},
{
"code": null,
"e": 8205,
"s": 8091,
"text": "As before, to counter the warm-up period we need to ascertain that we have 34 observations to calculate the MACD."
},
{
"code": null,
"e": 8424,
"s": 8205,
"text": "Below we plot the MACD and the signal lines, where the crossovers indicate buy/sell signals. Additionally, one could plot the MACD divergence in the form of a barplot (it is commonly referred to as the MACD histogram)."
},
{
"code": null,
"e": 8744,
"s": 8424,
"text": "RSI stands for the Relative Strength Index, which is another technical indicator we can use to create trading strategies. The RSI is classified as a momentum oscillator and it measures the velocity and magnitude of directional price movements. Momentum describes the rate at which the price of the asset rises or falls."
},
{
"code": null,
"e": 8972,
"s": 8744,
"text": "Without going into too many technical details, the RSI measures momentum as the ratio of higher closes to lower closes. Assets with more/stronger positive changes have higher RSI than assets with more/stronger negative changes."
},
{
"code": null,
"e": 9346,
"s": 8972,
"text": "The output of the RSI is a number on a scale from 0 to 100 and it is typically calculated on a 14-day basis. To generate the trading signals, it is common to specify the low and high levels of the RSI at 30 and 70, respectively. The interpretation of the thresholds is that the lower one indicates that the asset is oversold, and the upper one that the asset is overbought."
},
{
"code": null,
"e": 9681,
"s": 9346,
"text": "Sometimes, a medium level (halfway between low and high) is also specified, for example in case of strategies which also allow for short-selling. We can also select more extreme thresholds such as 20 and 80, which would then indicate stronger momentum. However, this should be specified using domain knowledge or by running backtests."
},
{
"code": null,
"e": 9727,
"s": 9681,
"text": "The strategy we consider can be described as:"
},
{
"code": null,
"e": 9789,
"s": 9727,
"text": "when the RSI crosses the lower threshold (30) — buy the asset"
},
{
"code": null,
"e": 9852,
"s": 9789,
"text": "when the RSI crosses the upper threshold (70) — sell the asset"
},
{
"code": null,
"e": 9919,
"s": 9852,
"text": "Below we plot the RSI together with the upper and lower threshold."
},
{
"code": null,
"e": 10484,
"s": 9919,
"text": "The last step involves putting all the performance metrics into one DataFrame and inspecting the results. We can see that in the case of our backtest, the strategy based on the simple moving average performed best in terms of generated returns. It also had the highest Sharpe ratio — the highest excess return (in this case return, as we do not consider a risk-free asset) per unit of risk. The second-best strategy turned out to be the one based on the MACD. It is also good to notice that only these two performed better than the benchmark buy and hold strategy."
},
{
"code": null,
"e": 10764,
"s": 10484,
"text": "perf_df = pd.DataFrame({'Buy and Hold': buy_and_hold_perf, 'Simple Moving Average': sma_perf, 'Moving Average Crossover': mac_perf, 'MACD': macd_perf, 'RSI': rsi_perf})perf_df.transpose()"
},
{
"code": null,
"e": 11054,
"s": 10764,
"text": "In this short article, I showed how to combine zipline with talib in order to backtest trading strategies based on popular technical indicators such as moving averages, the MACD, the RSI, etc. But this was only the beginning, as it is possible to create much more sophisticated strategies."
},
{
"code": null,
"e": 11094,
"s": 11054,
"text": "Some of the possible future directions:"
},
{
"code": null,
"e": 11138,
"s": 11094,
"text": "include multiple assets into the strategies"
},
{
"code": null,
"e": 11162,
"s": 11138,
"text": "allow for short-selling"
},
{
"code": null,
"e": 11181,
"s": 11162,
"text": "mix the indicators"
},
{
"code": null,
"e": 11262,
"s": 11181,
"text": "backtest different parameters for each strategy to find the best-performing ones"
},
{
"code": null,
"e": 11402,
"s": 11262,
"text": "We must also remember that the fact that the strategy performed well in the past is no guarantee that this will happen again in the future."
},
{
"code": null,
"e": 11564,
"s": 11402,
"text": "As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. You can find the code used for this article on my GitHub."
},
{
"code": null,
"e": 11778,
"s": 11564,
"text": "Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!"
},
{
"code": null,
"e": 11831,
"s": 11778,
"text": "Below you can find the other articles in the series:"
},
{
"code": null,
"e": 11914,
"s": 11831,
"text": "building algorithmic trading strategies based on the mean-variance analysis (link)"
}
] |
Java Program to split a string using Regular Expression
|
Let’s say we have the following string.
String str = "{Java is a programming language} {James Gosling developed it.}";
Above, the string is enclosed with parentheses. We can split a string with these parentheses using the split() method.
String[] strSplit = str.split("[{}]");
The following is an example.
Live Demo
public class Demo {
public static void main(String[] args) throws Exception {
String str = "{Java is a programming language} {James Gosling developed it.}";
String[] strSplit = str.split("[{}]");
System.out.println("Splitting String...");
for (int i = 0; i < strSplit.length; i++)
System.out.println(strSplit[i]);
}
}
Splitting String...
Java is a programming language
James Gosling developed it.
|
[
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Let’s say we have the following string."
},
{
"code": null,
"e": 1181,
"s": 1102,
"text": "String str = \"{Java is a programming language} {James Gosling developed it.}\";"
},
{
"code": null,
"e": 1300,
"s": 1181,
"text": "Above, the string is enclosed with parentheses. We can split a string with these parentheses using the split() method."
},
{
"code": null,
"e": 1339,
"s": 1300,
"text": "String[] strSplit = str.split(\"[{}]\");"
},
{
"code": null,
"e": 1368,
"s": 1339,
"text": "The following is an example."
},
{
"code": null,
"e": 1379,
"s": 1368,
"text": " Live Demo"
},
{
"code": null,
"e": 1733,
"s": 1379,
"text": "public class Demo {\n public static void main(String[] args) throws Exception {\n String str = \"{Java is a programming language} {James Gosling developed it.}\";\n String[] strSplit = str.split(\"[{}]\");\n System.out.println(\"Splitting String...\");\n for (int i = 0; i < strSplit.length; i++)\n System.out.println(strSplit[i]);\n }\n}"
},
{
"code": null,
"e": 1812,
"s": 1733,
"text": "Splitting String...\nJava is a programming language\nJames Gosling developed it."
}
] |
Create Copy-Move GUI using Tkinter in Python - GeeksforGeeks
|
05 Oct, 2021
Everyone reading this post is well aware of the importance of Copying the file or moving the file from one specific location to another. In this post, we have tried to explain not only the program but added some exciting pieces of Interface. Up to now, many of you may get about what we are talking about. Yes, you are right, We are going to use “Tkinter” and “shutil” for this project. So we will start it by Installing Packages.
shutil : Python shutil module enables us to operate with file objects easily and without diving into file objects a lot. It takes care of low-level semantics like creating file objects, closing the files once they are copied, and allows us to focus on the business logic of our program. shutil is the native library, you don’t need to install it externally, just import, while you use it.
tkinter :Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit or in simple words Tkinter is used as a python Graphical User interface. Tkinter is also the native library, you don’t need to install it externally, just import, while you use it.
The GUI would look like the below image:
Below is the implementation:
Python3
# Importing necessary packagesimport shutilimport tkinter as tkfrom tkinter import *from tkinter import messagebox, filedialog # Defining CreateWidgets() function to# create necessary tkinter widgetsdef CreateWidgets(): link_Label = Label(root, text ="Select The File To Copy : ", bg = "#E8D579") link_Label.grid(row = 1, column = 0, pady = 5, padx = 5) root.sourceText = Entry(root, width = 50, textvariable = sourceLocation) root.sourceText.grid(row = 1, column = 1, pady = 5, padx = 5, columnspan = 2) source_browseButton = Button(root, text ="Browse", command = SourceBrowse, width = 15) source_browseButton.grid(row = 1, column = 3, pady = 5, padx = 5) destinationLabel = Label(root, text ="Select The Destination : ", bg ="#E8D579") destinationLabel.grid(row = 2, column = 0, pady = 5, padx = 5) root.destinationText = Entry(root, width = 50, textvariable = destinationLocation) root.destinationText.grid(row = 2, column = 1, pady = 5, padx = 5, columnspan = 2) dest_browseButton = Button(root, text ="Browse", command = DestinationBrowse, width = 15) dest_browseButton.grid(row = 2, column = 3, pady = 5, padx = 5) copyButton = Button(root, text ="Copy File", command = CopyFile, width = 15) copyButton.grid(row = 3, column = 1, pady = 5, padx = 5) moveButton = Button(root, text ="Move File", command = MoveFile, width = 15) moveButton.grid(row = 3, column = 2, pady = 5, padx = 5) def SourceBrowse(): # Opening the file-dialog directory prompting # the user to select files to copy using # filedialog.askopenfilenames() method. Setting # initialdir argument is optional Since multiple # files may be selected, converting the selection # to list using list() root.files_list = list(filedialog.askopenfilenames(initialdir ="C:/Users/AKASH / Desktop / Lockdown Certificate / Geek For Geek")) # Displaying the selected files in the root.sourceText # Entry using root.sourceText.insert() root.sourceText.insert('1', root.files_list) def DestinationBrowse(): # Opening the file-dialog directory prompting # the user to select destination folder to # which files are to be copied using the # filedialog.askopendirectory() method. # Setting initialdir argument is optional destinationdirectory = filedialog.askdirectory(initialdir ="C:/Users/AKASH / Desktop / Lockdown Certificate / Geek For Geek") # Displaying the selected directory in the # root.destinationText Entry using # root.destinationText.insert() root.destinationText.insert('1', destinationdirectory) def CopyFile(): # Retrieving the source file selected by the # user in the SourceBrowse() and storing it in a # variable named files_list files_list = root.files_list # Retrieving the destination location from the # textvariable using destinationLocation.get() and # storing in destination_location destination_location = destinationLocation.get() # Looping through the files present in the list for f in files_list: # Copying the file to the destination using # the copy() of shutil module copy take the # source file and the destination folder as # the arguments shutil.copy(f, destination_location) messagebox.showinfo("SUCCESSFUL") def MoveFile(): # Retrieving the source file selected by the # user in the SourceBrowse() and storing it in a # variable named files_list''' files_list = root.files_list # Retrieving the destination location from the # textvariable using destinationLocation.get() and # storing in destination_location destination_location = destinationLocation.get() # Looping through the files present in the list for f in files_list: # Moving the file to the destination using # the move() of shutil module copy take the # source file and the destination folder as # the arguments shutil.move(f, destination_location) messagebox.showinfo("SUCCESSFUL") # Creating object of tk classroot = tk.Tk() # Setting the title and background color# disabling the resizing propertyroot.geometry("830x120")root.title("Copy-Move GUI")root.config(background = "black") # Creating tkinter variablesourceLocation = StringVar()destinationLocation = StringVar() # Calling the CreateWidgets() functionCreateWidgets() # Defining infinite looproot.mainloop()
Output:
abhigoya
gabaa406
anikakapoor
Python Tkinter-exercises
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 24360,
"s": 23927,
"text": "Everyone reading this post is well aware of the importance of Copying the file or moving the file from one specific location to another. In this post, we have tried to explain not only the program but added some exciting pieces of Interface. Up to now, many of you may get about what we are talking about. Yes, you are right, We are going to use “Tkinter” and “shutil” for this project. So we will start it by Installing Packages. "
},
{
"code": null,
"e": 24749,
"s": 24360,
"text": "shutil : Python shutil module enables us to operate with file objects easily and without diving into file objects a lot. It takes care of low-level semantics like creating file objects, closing the files once they are copied, and allows us to focus on the business logic of our program. shutil is the native library, you don’t need to install it externally, just import, while you use it."
},
{
"code": null,
"e": 25048,
"s": 24749,
"text": "tkinter :Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit or in simple words Tkinter is used as a python Graphical User interface. Tkinter is also the native library, you don’t need to install it externally, just import, while you use it."
},
{
"code": null,
"e": 25089,
"s": 25048,
"text": "The GUI would look like the below image:"
},
{
"code": null,
"e": 25119,
"s": 25089,
"text": "Below is the implementation: "
},
{
"code": null,
"e": 25127,
"s": 25119,
"text": "Python3"
},
{
"code": "# Importing necessary packagesimport shutilimport tkinter as tkfrom tkinter import *from tkinter import messagebox, filedialog # Defining CreateWidgets() function to# create necessary tkinter widgetsdef CreateWidgets(): link_Label = Label(root, text =\"Select The File To Copy : \", bg = \"#E8D579\") link_Label.grid(row = 1, column = 0, pady = 5, padx = 5) root.sourceText = Entry(root, width = 50, textvariable = sourceLocation) root.sourceText.grid(row = 1, column = 1, pady = 5, padx = 5, columnspan = 2) source_browseButton = Button(root, text =\"Browse\", command = SourceBrowse, width = 15) source_browseButton.grid(row = 1, column = 3, pady = 5, padx = 5) destinationLabel = Label(root, text =\"Select The Destination : \", bg =\"#E8D579\") destinationLabel.grid(row = 2, column = 0, pady = 5, padx = 5) root.destinationText = Entry(root, width = 50, textvariable = destinationLocation) root.destinationText.grid(row = 2, column = 1, pady = 5, padx = 5, columnspan = 2) dest_browseButton = Button(root, text =\"Browse\", command = DestinationBrowse, width = 15) dest_browseButton.grid(row = 2, column = 3, pady = 5, padx = 5) copyButton = Button(root, text =\"Copy File\", command = CopyFile, width = 15) copyButton.grid(row = 3, column = 1, pady = 5, padx = 5) moveButton = Button(root, text =\"Move File\", command = MoveFile, width = 15) moveButton.grid(row = 3, column = 2, pady = 5, padx = 5) def SourceBrowse(): # Opening the file-dialog directory prompting # the user to select files to copy using # filedialog.askopenfilenames() method. Setting # initialdir argument is optional Since multiple # files may be selected, converting the selection # to list using list() root.files_list = list(filedialog.askopenfilenames(initialdir =\"C:/Users/AKASH / Desktop / Lockdown Certificate / Geek For Geek\")) # Displaying the selected files in the root.sourceText # Entry using root.sourceText.insert() root.sourceText.insert('1', root.files_list) def DestinationBrowse(): # Opening the file-dialog directory prompting # the user to select destination folder to # which files are to be copied using the # filedialog.askopendirectory() method. # Setting initialdir argument is optional destinationdirectory = filedialog.askdirectory(initialdir =\"C:/Users/AKASH / Desktop / Lockdown Certificate / Geek For Geek\") # Displaying the selected directory in the # root.destinationText Entry using # root.destinationText.insert() root.destinationText.insert('1', destinationdirectory) def CopyFile(): # Retrieving the source file selected by the # user in the SourceBrowse() and storing it in a # variable named files_list files_list = root.files_list # Retrieving the destination location from the # textvariable using destinationLocation.get() and # storing in destination_location destination_location = destinationLocation.get() # Looping through the files present in the list for f in files_list: # Copying the file to the destination using # the copy() of shutil module copy take the # source file and the destination folder as # the arguments shutil.copy(f, destination_location) messagebox.showinfo(\"SUCCESSFUL\") def MoveFile(): # Retrieving the source file selected by the # user in the SourceBrowse() and storing it in a # variable named files_list''' files_list = root.files_list # Retrieving the destination location from the # textvariable using destinationLocation.get() and # storing in destination_location destination_location = destinationLocation.get() # Looping through the files present in the list for f in files_list: # Moving the file to the destination using # the move() of shutil module copy take the # source file and the destination folder as # the arguments shutil.move(f, destination_location) messagebox.showinfo(\"SUCCESSFUL\") # Creating object of tk classroot = tk.Tk() # Setting the title and background color# disabling the resizing propertyroot.geometry(\"830x120\")root.title(\"Copy-Move GUI\")root.config(background = \"black\") # Creating tkinter variablesourceLocation = StringVar()destinationLocation = StringVar() # Calling the CreateWidgets() functionCreateWidgets() # Defining infinite looproot.mainloop()",
"e": 30041,
"s": 25127,
"text": null
},
{
"code": null,
"e": 30049,
"s": 30041,
"text": "Output:"
},
{
"code": null,
"e": 30058,
"s": 30049,
"text": "abhigoya"
},
{
"code": null,
"e": 30067,
"s": 30058,
"text": "gabaa406"
},
{
"code": null,
"e": 30079,
"s": 30067,
"text": "anikakapoor"
},
{
"code": null,
"e": 30104,
"s": 30079,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 30115,
"s": 30104,
"text": "Python-gui"
},
{
"code": null,
"e": 30130,
"s": 30115,
"text": "Python-tkinter"
},
{
"code": null,
"e": 30137,
"s": 30130,
"text": "Python"
},
{
"code": null,
"e": 30235,
"s": 30137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30244,
"s": 30235,
"text": "Comments"
},
{
"code": null,
"e": 30257,
"s": 30244,
"text": "Old Comments"
},
{
"code": null,
"e": 30289,
"s": 30257,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30345,
"s": 30289,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30387,
"s": 30345,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30429,
"s": 30387,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30465,
"s": 30429,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 30504,
"s": 30465,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30535,
"s": 30504,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30557,
"s": 30535,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30584,
"s": 30557,
"text": "Python Classes and Objects"
}
] |
MFC - Windows Fundamentals
|
In this chapter, we will be covering the fundamentals of Windows. To create a program, also called an application, you derive a class from the MFC's CWinApp. CWinApp stands for Class for a Windows Application.
Let us look into a simple example by creating a new Win32 project.
Step 1 − Open the Visual studio and click on the File → New → Project menu option.
Step 2 − You can now see the New Project dialog box.
Step 3 − From the left pane, select Templates → Visual C++ → Win32.
Step 4 − In the middle pane, select Win32 Project.
Step 5 − Enter the project name ‘MFCWindowDemo’ in the Name field and click OK to continue. You will see the following dialog box.
Step 6 − Click Next.
Step 7 − Select the options as shown in the dialog box given above and click Finish.
Step 8 − An empty project is created.
Step 9 − To make it an MFC project, right-click on the project and select Properties.
Step 10 − In the left section, click Configuration Properties → General.
Step 11 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK.
Step 12 − Add a new source file.
Step 13 − Right-click on your Project and select Add → New Item...
Step 14 − In the Templates section, click C++ File (.cpp).
Step 15 − Set the Name as Example and click Add.
Any application has two main sections −
Class
Frame or Window
Let us create a window using the following steps −
Step 1 − To create an application, we need to derive a class from the MFC's CWinApp.
#include
class CExample : public CWinApp {
BOOL InitInstance() {
return TRUE;
}
};
Step 2 − We also need a frame/window to show the content of our application.
Step 3 − For this, we need to add another class and derive it from the MFC's CFrameWnd class and implement its constructor and a call the Create() method, which will create a frame/window as shown in the following code.
class CMyFrame : public CFrameWnd {
public:
CMyFrame() {
Create(NULL, _T("MFC Application Tutorial"));
}
};
Step 4 − As you can see that Create() method needs two parameters, the name of the class, which should be passed as NULL, and the name of the window, which is the string that will be shown on the title bar.
After creating a window, to let the application use it, you can use a pointer to show the class used to create the window. In this case, the pointer would be CFrameWnd. To use the frame window, assign its pointer to the CWinThread::m_pMainWnd member variable. This is done in the InitInstance() implementation of your application.
Step 1 − Here is the implementation of InitInstance() in CExample class.
class CExample : public CWinApp {
BOOL InitInstance() {
CMyFrame *Frame = new CMyFrame(); m_pMainWnd = Frame;
Frame->ShowWindow(SW_NORMAL);
Frame->UpdateWindow();
return TRUE;
}
};
Step 2 − Following is the complete implementation of Example.cpp file.
#include <afxwin.h>
class CMyFrame : public CFrameWnd {
public:
CMyFrame() {
Create(NULL, _T("MFC Application Tutorial"));
}
};
class CExample : public CWinApp {
BOOL InitInstance() {
CMyFrame *Frame = new CMyFrame();
m_pMainWnd = Frame;
Frame->ShowWindow(SW_NORMAL);
Frame->UpdateWindow();
return TRUE;
}
};
CExample theApp;
Step 3 − When we run the above application, the following window is created.
Windows styles are characteristics that control features such as window appearance, borders, minimized or maximized state, or other resizing states, etc.
WS_BORDER
Creates a window that has a border.
WS_CAPTION
Creates a window that has a title bar (implies the WS_BORDER style). Cannot be used with the WS_DLGFRAME style.
WS_CHILD
Creates a child window. Cannot be used with the WS_POPUP style.
WS_CHILDWINDOW
Same as the WS_CHILD style.
WS_CLIPCHILDREN
Excludes the area occupied by child windows when you draw within the parent window. Used when you create the parent window.
WS_CLIPSIBLINGS
Clips child windows relative to each other; that is, when a particular child window receives a paint message, the WS_CLIPSIBLINGS style clips all other overlapped child windows out of the region of the child window to be updated. (If WS_CLIPSIBLINGS is not given and child windows overlap, when you draw within the client area of a child window, it is possible to draw within the client area of a neighboring child window.) For use with the WS_CHILD style only.
WS_DISABLED
Creates a window that is initially disabled.
WS_DLGFRAME
Creates a window with a double border but no title.
WS_GROUP
Specifies the first control of a group of controls in which the user can move from one control to the next with the arrow keys. All controls defined with the WS_GROUP style FALSE after the first control belong to the same group. The next control with the WS_GROUP style starts the next group (that is, one group ends where the next begins).
WS_HSCROLL
Creates a window that has a horizontal scroll bar.
WS_ICONIC
Creates a window that is initially minimized. Same as the WS_MINIMIZE style.
WS_MAXIMIZE
Creates a window of maximum size.
WS_MAXIMIZEBOX
Creates a window that has a Maximize button.
WS_MINIMIZE
Creates a window that is initially minimized. For use with the WS_OVERLAPPED style only.
WS_MINIMIZEBOX
Creates a window that has a Minimize button.
WS_OVERLAPPED
Creates an overlapped window. An overlapped window usually has a caption and a border.
WS_OVERLAPPED WINDOW
Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles.
WS_POPUP
Creates a pop-up window. Cannot be used with the WS_CHILD style.
WS_POPUPWINDOW
Creates a pop-up window with the WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION style must be combined with the WS_POPUPWINDOW style to make the Control menu visible.
WS_SIZEBOX
Creates a window that has a sizing border. Same as the WS_THICKFRAME style.
WS_SYSMENU
Creates a window that has a Control-menu box in its title bar. Used only for windows with title bars.
WS_TABSTOP
Specifies one of any number of controls through which the user can move by using the TAB key. The TAB key moves the user to the next control specified by the WS_TABSTOP style.
WS_THICKFRAME
Creates a window with a thick frame that can be used to size the window.
WS_TILED
Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_OVERLAPPED style.
WS_TILEDWINDOW
Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_OVERLAPPEDWINDOW style.
WS_VISIBLE
Creates a window that is initially visible.
WS_VSCROLL
Creates a window that has a vertical scroll bar.
Step 1 − Let us look into a simple example in which we will add some styling. After creating a window, to display it to the user, we can apply the WS_VISIBLE style to it and additionally, we will also add WS_OVERLAPPED style. Here is an implementation −
class CMyFrame : public CFrameWnd {
public:
CMyFrame() {
Create(NULL, _T("MFC Application Tutorial"), WS_VISIBLE | WS_OVERLAPPED);
}
};
Step 2 − When you run this application, the following window is created.
You can now see that the minimize, maximize, and close options do not appear anymore.
To locate things displayed on the monitor, the computer uses a coordinate system similar to the Cartesian's, but the origin is located on the top left corner of the screen. Using this coordinate system, any point can be located by its distance from the top left corner of the screen of the horizontal and the vertical axes.
The Win32 library provides a structure called POINT defined as follows −
typedef struct tagPOINT {
LONG x;
LONG y;
} POINT;
The ‘x’ member variable is the distance from the left border of the screen to the point.
The ‘x’ member variable is the distance from the left border of the screen to the point.
The ‘y’ variable represents the distance from the top border of the screen to the point.
The ‘y’ variable represents the distance from the top border of the screen to the point.
Besides the Win32's POINT structure, the Microsoft Foundation Class (MFC) library provides the CPoint class.
Besides the Win32's POINT structure, the Microsoft Foundation Class (MFC) library provides the CPoint class.
This provides the same functionality as the POINT structure. As a C++ class, it adds more functionality needed to locate a point. It provides two constructors.
This provides the same functionality as the POINT structure. As a C++ class, it adds more functionality needed to locate a point. It provides two constructors.
CPoint();
CPoint(int X, int Y);
While a point is used to locate an object on the screen, each window has a size. The size provides two measures related to an object.
The width of an object.
The height of an object.
The Win32 library uses the SIZE structure defined as follows −
typedef struct tagSIZE {
int cx;
int cy;
} SIZE;
Besides the Win32's SIZE structure, the MFC provides the CSize class. This class has the same functionality as SIZE but adds features of a C++ class. It provides five constructors that allow you to create a size variable in any way of your choice.
CSize();
CSize(int initCX, int initCY);
CSize(SIZE initSize);
CSize(POINT initPt);
CSize(DWORD dwSize);
When a Window displays, it can be identified on the screen by its location with regards to the borders of the monitor. A Window can also be identified by its width and height. These characteristics are specified or controlled by the rect argument of the Create() method. This argument is a rectangle that can be created through the Win32 RECT structure.
typedef struct _RECT {
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT, *PRECT;
Besides the Win32's RECT structure, the MFC provides the CRect class which has the following constructors −
CRect();
CRect(int l, int t, int r, int b);
CRect(const RECT& srcRect);
CRect(LPCRECT lpSrcRect);
CRect(POINT point, SIZE size);
CRect(POINT topLeft, POINT bottomRight);
Let us look into a simple example in which we will specify the location and the size of the window
class CMyFrame : public CFrameWnd {
public:
CMyFrame() {
Create(NULL, _T("MFC Application Tutorial"), WS_SYSMENU, CRect(90, 120,
550, 480));
}
};
When you run this application, the following window is created on the top left corner of your screen as specified in CRect constructor in the first two parameters. The last two parameters are the size of the Window.
In the real world, many applications are made of different Windows. When an application uses various Windows, most of the objects depend on a particular one. It could be the first Window that was created or another window that you designated. Such a Window is referred to as the Parent Window. All the other windows depend on it directly or indirectly.
If the Window you are creating is dependent of another, you can specify that it has a parent.
If the Window you are creating is dependent of another, you can specify that it has a parent.
This is done with the pParentWnd argument of the CFrameWnd::Create() method.
This is done with the pParentWnd argument of the CFrameWnd::Create() method.
If the Window does not have a parent, pass the argument with a NULL value.
If the Window does not have a parent, pass the argument with a NULL value.
Let us look into an example which has only one Window, and there is no parent Window available, so we will pass the argument with NULL value as shown in the following code −
class CMyFrame : public CFrameWnd {
public:
CMyFrame() {
Create(NULL, _T("MFC Application Tutorial"), WS_SYSMENU,
CRect(90, 120, 550, 480), NULL);
}
};
When you run the above application, you see the same output.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2277,
"s": 2067,
"text": "In this chapter, we will be covering the fundamentals of Windows. To create a program, also called an application, you derive a class from the MFC's CWinApp. CWinApp stands for Class for a Windows Application."
},
{
"code": null,
"e": 2344,
"s": 2277,
"text": "Let us look into a simple example by creating a new Win32 project."
},
{
"code": null,
"e": 2427,
"s": 2344,
"text": "Step 1 − Open the Visual studio and click on the File → New → Project menu option."
},
{
"code": null,
"e": 2480,
"s": 2427,
"text": "Step 2 − You can now see the New Project dialog box."
},
{
"code": null,
"e": 2548,
"s": 2480,
"text": "Step 3 − From the left pane, select Templates → Visual C++ → Win32."
},
{
"code": null,
"e": 2599,
"s": 2548,
"text": "Step 4 − In the middle pane, select Win32 Project."
},
{
"code": null,
"e": 2730,
"s": 2599,
"text": "Step 5 − Enter the project name ‘MFCWindowDemo’ in the Name field and click OK to continue. You will see the following dialog box."
},
{
"code": null,
"e": 2751,
"s": 2730,
"text": "Step 6 − Click Next."
},
{
"code": null,
"e": 2836,
"s": 2751,
"text": "Step 7 − Select the options as shown in the dialog box given above and click Finish."
},
{
"code": null,
"e": 2874,
"s": 2836,
"text": "Step 8 − An empty project is created."
},
{
"code": null,
"e": 2960,
"s": 2874,
"text": "Step 9 − To make it an MFC project, right-click on the project and select Properties."
},
{
"code": null,
"e": 3033,
"s": 2960,
"text": "Step 10 − In the left section, click Configuration Properties → General."
},
{
"code": null,
"e": 3125,
"s": 3033,
"text": "Step 11 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK."
},
{
"code": null,
"e": 3158,
"s": 3125,
"text": "Step 12 − Add a new source file."
},
{
"code": null,
"e": 3226,
"s": 3158,
"text": "Step 13 − Right-click on your Project and select Add → New Item..."
},
{
"code": null,
"e": 3285,
"s": 3226,
"text": "Step 14 − In the Templates section, click C++ File (.cpp)."
},
{
"code": null,
"e": 3334,
"s": 3285,
"text": "Step 15 − Set the Name as Example and click Add."
},
{
"code": null,
"e": 3374,
"s": 3334,
"text": "Any application has two main sections −"
},
{
"code": null,
"e": 3380,
"s": 3374,
"text": "Class"
},
{
"code": null,
"e": 3396,
"s": 3380,
"text": "Frame or Window"
},
{
"code": null,
"e": 3447,
"s": 3396,
"text": "Let us create a window using the following steps −"
},
{
"code": null,
"e": 3532,
"s": 3447,
"text": "Step 1 − To create an application, we need to derive a class from the MFC's CWinApp."
},
{
"code": null,
"e": 3627,
"s": 3532,
"text": "#include\nclass CExample : public CWinApp {\n BOOL InitInstance() {\n return TRUE;\n }\n};"
},
{
"code": null,
"e": 3704,
"s": 3627,
"text": "Step 2 − We also need a frame/window to show the content of our application."
},
{
"code": null,
"e": 3924,
"s": 3704,
"text": "Step 3 − For this, we need to add another class and derive it from the MFC's CFrameWnd class and implement its constructor and a call the Create() method, which will create a frame/window as shown in the following code."
},
{
"code": null,
"e": 4056,
"s": 3924,
"text": "class CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"));\n }\n};"
},
{
"code": null,
"e": 4263,
"s": 4056,
"text": "Step 4 − As you can see that Create() method needs two parameters, the name of the class, which should be passed as NULL, and the name of the window, which is the string that will be shown on the title bar."
},
{
"code": null,
"e": 4594,
"s": 4263,
"text": "After creating a window, to let the application use it, you can use a pointer to show the class used to create the window. In this case, the pointer would be CFrameWnd. To use the frame window, assign its pointer to the CWinThread::m_pMainWnd member variable. This is done in the InitInstance() implementation of your application."
},
{
"code": null,
"e": 4667,
"s": 4594,
"text": "Step 1 − Here is the implementation of InitInstance() in CExample class."
},
{
"code": null,
"e": 4893,
"s": 4667,
"text": "class CExample : public CWinApp {\n BOOL InitInstance() {\n CMyFrame *Frame = new CMyFrame(); m_pMainWnd = Frame;\n \n Frame->ShowWindow(SW_NORMAL);\n Frame->UpdateWindow();\n \n return TRUE;\n }\n};"
},
{
"code": null,
"e": 4964,
"s": 4893,
"text": "Step 2 − Following is the complete implementation of Example.cpp file."
},
{
"code": null,
"e": 5367,
"s": 4964,
"text": "#include <afxwin.h>\n\nclass CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"));\n }\n};\n\nclass CExample : public CWinApp {\n BOOL InitInstance() {\n CMyFrame *Frame = new CMyFrame();\n m_pMainWnd = Frame;\n \n Frame->ShowWindow(SW_NORMAL);\n Frame->UpdateWindow();\n \n return TRUE;\n }\n};\n\nCExample theApp;"
},
{
"code": null,
"e": 5444,
"s": 5367,
"text": "Step 3 − When we run the above application, the following window is created."
},
{
"code": null,
"e": 5599,
"s": 5444,
"text": "Windows styles are characteristics that control features such as window appearance, borders, minimized or maximized state, or other resizing states, etc. "
},
{
"code": null,
"e": 5609,
"s": 5599,
"text": "WS_BORDER"
},
{
"code": null,
"e": 5645,
"s": 5609,
"text": "Creates a window that has a border."
},
{
"code": null,
"e": 5656,
"s": 5645,
"text": "WS_CAPTION"
},
{
"code": null,
"e": 5768,
"s": 5656,
"text": "Creates a window that has a title bar (implies the WS_BORDER style). Cannot be used with the WS_DLGFRAME style."
},
{
"code": null,
"e": 5777,
"s": 5768,
"text": "WS_CHILD"
},
{
"code": null,
"e": 5841,
"s": 5777,
"text": "Creates a child window. Cannot be used with the WS_POPUP style."
},
{
"code": null,
"e": 5856,
"s": 5841,
"text": "WS_CHILDWINDOW"
},
{
"code": null,
"e": 5884,
"s": 5856,
"text": "Same as the WS_CHILD style."
},
{
"code": null,
"e": 5900,
"s": 5884,
"text": "WS_CLIPCHILDREN"
},
{
"code": null,
"e": 6024,
"s": 5900,
"text": "Excludes the area occupied by child windows when you draw within the parent window. Used when you create the parent window."
},
{
"code": null,
"e": 6040,
"s": 6024,
"text": "WS_CLIPSIBLINGS"
},
{
"code": null,
"e": 6502,
"s": 6040,
"text": "Clips child windows relative to each other; that is, when a particular child window receives a paint message, the WS_CLIPSIBLINGS style clips all other overlapped child windows out of the region of the child window to be updated. (If WS_CLIPSIBLINGS is not given and child windows overlap, when you draw within the client area of a child window, it is possible to draw within the client area of a neighboring child window.) For use with the WS_CHILD style only."
},
{
"code": null,
"e": 6514,
"s": 6502,
"text": "WS_DISABLED"
},
{
"code": null,
"e": 6559,
"s": 6514,
"text": "Creates a window that is initially disabled."
},
{
"code": null,
"e": 6571,
"s": 6559,
"text": "WS_DLGFRAME"
},
{
"code": null,
"e": 6623,
"s": 6571,
"text": "Creates a window with a double border but no title."
},
{
"code": null,
"e": 6632,
"s": 6623,
"text": "WS_GROUP"
},
{
"code": null,
"e": 6973,
"s": 6632,
"text": "Specifies the first control of a group of controls in which the user can move from one control to the next with the arrow keys. All controls defined with the WS_GROUP style FALSE after the first control belong to the same group. The next control with the WS_GROUP style starts the next group (that is, one group ends where the next begins)."
},
{
"code": null,
"e": 6984,
"s": 6973,
"text": "WS_HSCROLL"
},
{
"code": null,
"e": 7035,
"s": 6984,
"text": "Creates a window that has a horizontal scroll bar."
},
{
"code": null,
"e": 7045,
"s": 7035,
"text": "WS_ICONIC"
},
{
"code": null,
"e": 7122,
"s": 7045,
"text": "Creates a window that is initially minimized. Same as the WS_MINIMIZE style."
},
{
"code": null,
"e": 7134,
"s": 7122,
"text": "WS_MAXIMIZE"
},
{
"code": null,
"e": 7168,
"s": 7134,
"text": "Creates a window of maximum size."
},
{
"code": null,
"e": 7183,
"s": 7168,
"text": "WS_MAXIMIZEBOX"
},
{
"code": null,
"e": 7228,
"s": 7183,
"text": "Creates a window that has a Maximize button."
},
{
"code": null,
"e": 7240,
"s": 7228,
"text": "WS_MINIMIZE"
},
{
"code": null,
"e": 7329,
"s": 7240,
"text": "Creates a window that is initially minimized. For use with the WS_OVERLAPPED style only."
},
{
"code": null,
"e": 7344,
"s": 7329,
"text": "WS_MINIMIZEBOX"
},
{
"code": null,
"e": 7389,
"s": 7344,
"text": "Creates a window that has a Minimize button."
},
{
"code": null,
"e": 7403,
"s": 7389,
"text": "WS_OVERLAPPED"
},
{
"code": null,
"e": 7490,
"s": 7403,
"text": "Creates an overlapped window. An overlapped window usually has a caption and a border."
},
{
"code": null,
"e": 7511,
"s": 7490,
"text": "WS_OVERLAPPED WINDOW"
},
{
"code": null,
"e": 7646,
"s": 7511,
"text": "Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles."
},
{
"code": null,
"e": 7655,
"s": 7646,
"text": "WS_POPUP"
},
{
"code": null,
"e": 7720,
"s": 7655,
"text": "Creates a pop-up window. Cannot be used with the WS_CHILD style."
},
{
"code": null,
"e": 7735,
"s": 7720,
"text": "WS_POPUPWINDOW"
},
{
"code": null,
"e": 7914,
"s": 7735,
"text": "Creates a pop-up window with the WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION style must be combined with the WS_POPUPWINDOW style to make the Control menu visible."
},
{
"code": null,
"e": 7925,
"s": 7914,
"text": "WS_SIZEBOX"
},
{
"code": null,
"e": 8001,
"s": 7925,
"text": "Creates a window that has a sizing border. Same as the WS_THICKFRAME style."
},
{
"code": null,
"e": 8012,
"s": 8001,
"text": "WS_SYSMENU"
},
{
"code": null,
"e": 8114,
"s": 8012,
"text": "Creates a window that has a Control-menu box in its title bar. Used only for windows with title bars."
},
{
"code": null,
"e": 8125,
"s": 8114,
"text": "WS_TABSTOP"
},
{
"code": null,
"e": 8301,
"s": 8125,
"text": "Specifies one of any number of controls through which the user can move by using the TAB key. The TAB key moves the user to the next control specified by the WS_TABSTOP style."
},
{
"code": null,
"e": 8315,
"s": 8301,
"text": "WS_THICKFRAME"
},
{
"code": null,
"e": 8388,
"s": 8315,
"text": "Creates a window with a thick frame that can be used to size the window."
},
{
"code": null,
"e": 8397,
"s": 8388,
"text": "WS_TILED"
},
{
"code": null,
"e": 8511,
"s": 8397,
"text": "Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_OVERLAPPED style."
},
{
"code": null,
"e": 8526,
"s": 8511,
"text": "WS_TILEDWINDOW"
},
{
"code": null,
"e": 8700,
"s": 8526,
"text": "Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_OVERLAPPEDWINDOW style."
},
{
"code": null,
"e": 8711,
"s": 8700,
"text": "WS_VISIBLE"
},
{
"code": null,
"e": 8755,
"s": 8711,
"text": "Creates a window that is initially visible."
},
{
"code": null,
"e": 8766,
"s": 8755,
"text": "WS_VSCROLL"
},
{
"code": null,
"e": 8815,
"s": 8766,
"text": "Creates a window that has a vertical scroll bar."
},
{
"code": null,
"e": 9069,
"s": 8815,
"text": "Step 1 − Let us look into a simple example in which we will add some styling. After creating a window, to display it to the user, we can apply the WS_VISIBLE style to it and additionally, we will also add WS_OVERLAPPED style. Here is an implementation −"
},
{
"code": null,
"e": 9229,
"s": 9069,
"text": "class CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"), WS_VISIBLE | WS_OVERLAPPED);\n }\n};"
},
{
"code": null,
"e": 9302,
"s": 9229,
"text": "Step 2 − When you run this application, the following window is created."
},
{
"code": null,
"e": 9388,
"s": 9302,
"text": "You can now see that the minimize, maximize, and close options do not appear anymore."
},
{
"code": null,
"e": 9712,
"s": 9388,
"text": "To locate things displayed on the monitor, the computer uses a coordinate system similar to the Cartesian's, but the origin is located on the top left corner of the screen. Using this coordinate system, any point can be located by its distance from the top left corner of the screen of the horizontal and the vertical axes."
},
{
"code": null,
"e": 9785,
"s": 9712,
"text": "The Win32 library provides a structure called POINT defined as follows −"
},
{
"code": null,
"e": 9842,
"s": 9785,
"text": "typedef struct tagPOINT {\n LONG x;\n LONG y;\n} POINT;"
},
{
"code": null,
"e": 9931,
"s": 9842,
"text": "The ‘x’ member variable is the distance from the left border of the screen to the point."
},
{
"code": null,
"e": 10020,
"s": 9931,
"text": "The ‘x’ member variable is the distance from the left border of the screen to the point."
},
{
"code": null,
"e": 10109,
"s": 10020,
"text": "The ‘y’ variable represents the distance from the top border of the screen to the point."
},
{
"code": null,
"e": 10198,
"s": 10109,
"text": "The ‘y’ variable represents the distance from the top border of the screen to the point."
},
{
"code": null,
"e": 10307,
"s": 10198,
"text": "Besides the Win32's POINT structure, the Microsoft Foundation Class (MFC) library provides the CPoint class."
},
{
"code": null,
"e": 10416,
"s": 10307,
"text": "Besides the Win32's POINT structure, the Microsoft Foundation Class (MFC) library provides the CPoint class."
},
{
"code": null,
"e": 10576,
"s": 10416,
"text": "This provides the same functionality as the POINT structure. As a C++ class, it adds more functionality needed to locate a point. It provides two constructors."
},
{
"code": null,
"e": 10736,
"s": 10576,
"text": "This provides the same functionality as the POINT structure. As a C++ class, it adds more functionality needed to locate a point. It provides two constructors."
},
{
"code": null,
"e": 10768,
"s": 10736,
"text": "CPoint();\nCPoint(int X, int Y);"
},
{
"code": null,
"e": 10902,
"s": 10768,
"text": "While a point is used to locate an object on the screen, each window has a size. The size provides two measures related to an object."
},
{
"code": null,
"e": 10926,
"s": 10902,
"text": "The width of an object."
},
{
"code": null,
"e": 10951,
"s": 10926,
"text": "The height of an object."
},
{
"code": null,
"e": 11014,
"s": 10951,
"text": "The Win32 library uses the SIZE structure defined as follows −"
},
{
"code": null,
"e": 11069,
"s": 11014,
"text": "typedef struct tagSIZE {\n int cx;\n int cy;\n} SIZE;"
},
{
"code": null,
"e": 11317,
"s": 11069,
"text": "Besides the Win32's SIZE structure, the MFC provides the CSize class. This class has the same functionality as SIZE but adds features of a C++ class. It provides five constructors that allow you to create a size variable in any way of your choice."
},
{
"code": null,
"e": 11421,
"s": 11317,
"text": "CSize();\nCSize(int initCX, int initCY);\nCSize(SIZE initSize);\nCSize(POINT initPt);\nCSize(DWORD dwSize);"
},
{
"code": null,
"e": 11775,
"s": 11421,
"text": "When a Window displays, it can be identified on the screen by its location with regards to the borders of the monitor. A Window can also be identified by its width and height. These characteristics are specified or controlled by the rect argument of the Create() method. This argument is a rectangle that can be created through the Win32 RECT structure."
},
{
"code": null,
"e": 11872,
"s": 11775,
"text": "typedef struct _RECT {\n LONG left;\n LONG top;\n LONG right;\n LONG bottom;\n} RECT, *PRECT;"
},
{
"code": null,
"e": 11981,
"s": 11872,
"text": "Besides the Win32's RECT structure, the MFC provides the CRect class which has the following constructors − "
},
{
"code": null,
"e": 12151,
"s": 11981,
"text": "CRect();\nCRect(int l, int t, int r, int b);\nCRect(const RECT& srcRect);\nCRect(LPCRECT lpSrcRect);\nCRect(POINT point, SIZE size);\nCRect(POINT topLeft, POINT bottomRight);"
},
{
"code": null,
"e": 12250,
"s": 12151,
"text": "Let us look into a simple example in which we will specify the location and the size of the window"
},
{
"code": null,
"e": 12433,
"s": 12250,
"text": "class CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"), WS_SYSMENU, CRect(90, 120, \n 550, 480));\n }\n};"
},
{
"code": null,
"e": 12649,
"s": 12433,
"text": "When you run this application, the following window is created on the top left corner of your screen as specified in CRect constructor in the first two parameters. The last two parameters are the size of the Window."
},
{
"code": null,
"e": 13002,
"s": 12649,
"text": "In the real world, many applications are made of different Windows. When an application uses various Windows, most of the objects depend on a particular one. It could be the first Window that was created or another window that you designated. Such a Window is referred to as the Parent Window. All the other windows depend on it directly or indirectly."
},
{
"code": null,
"e": 13096,
"s": 13002,
"text": "If the Window you are creating is dependent of another, you can specify that it has a parent."
},
{
"code": null,
"e": 13190,
"s": 13096,
"text": "If the Window you are creating is dependent of another, you can specify that it has a parent."
},
{
"code": null,
"e": 13267,
"s": 13190,
"text": "This is done with the pParentWnd argument of the CFrameWnd::Create() method."
},
{
"code": null,
"e": 13344,
"s": 13267,
"text": "This is done with the pParentWnd argument of the CFrameWnd::Create() method."
},
{
"code": null,
"e": 13419,
"s": 13344,
"text": "If the Window does not have a parent, pass the argument with a NULL value."
},
{
"code": null,
"e": 13494,
"s": 13419,
"text": "If the Window does not have a parent, pass the argument with a NULL value."
},
{
"code": null,
"e": 13668,
"s": 13494,
"text": "Let us look into an example which has only one Window, and there is no parent Window available, so we will pass the argument with NULL value as shown in the following code −"
},
{
"code": null,
"e": 13857,
"s": 13668,
"text": "class CMyFrame : public CFrameWnd {\n public:\n CMyFrame() {\n Create(NULL, _T(\"MFC Application Tutorial\"), WS_SYSMENU, \n CRect(90, 120, 550, 480), NULL);\n }\n};"
},
{
"code": null,
"e": 13918,
"s": 13857,
"text": "When you run the above application, you see the same output."
},
{
"code": null,
"e": 13925,
"s": 13918,
"text": " Print"
},
{
"code": null,
"e": 13936,
"s": 13925,
"text": " Add Notes"
}
] |
PyQt - QStatusBar Widget
|
QMainWindow object reserves a horizontal bar at the bottom as the status bar. It is used to display either permanent or contextual status information.
There are three types of status indicators −
Temporary − Briefly occupies most of the status bar. For example, used to explain tool tip texts or menu entries.
Temporary − Briefly occupies most of the status bar. For example, used to explain tool tip texts or menu entries.
Normal − Occupies part of the status bar and may be hidden by temporary messages. For example, used to display the page and line number in a word processor.
Normal − Occupies part of the status bar and may be hidden by temporary messages. For example, used to display the page and line number in a word processor.
Permanent − It is never hidden. Used for important mode indications. For example, some applications put a Caps Lock indicator in the status bar.
Permanent − It is never hidden. Used for important mode indications. For example, some applications put a Caps Lock indicator in the status bar.
Status bar of QMainWindow is retrieved by statusBar() function. setStatusBar() function activates it.
self.statusBar = QStatusBar()
self.setStatusBar(self.statusBar)
addWidget()
Adds the given widget object in the status bar
addPermanentWidget()
Adds the given widget object in the status bar permanently
showMessage()
Displays a temporary message in the status bar for a specified time interval
clearMessage()
Removes any temporary message being shown
removeWidget()
Removes specified widget from the status bar
In the following example, a top level QMainWindow has a menu bar and a QTextEdit object as its central widget.
Window’s status bar is activated as explained above.
Menu’s triggered signal is passed to processtrigger() slot function. If ‘show’ action is triggered, it displays a temporary message in the status bar as −
if (q.text() == "show"):
self.statusBar.showMessage(q.text()+" is clicked",2000)
The message will be erased after 2000 milliseconds (2 sec). If ‘add’ action is triggered, a button widget is added.
if q.text() == "add":
self.statusBar.addWidget(self.b)
Remove action will remove the button from the status bar.
if q.text() == "remove":
self.statusBar.removeWidget(self.b)
self.statusBar.show()
The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class statusdemo(QMainWindow):
def __init__(self, parent = None):
super(statusdemo, self).__init__(parent)
bar = self.menuBar()
file = bar.addMenu("File")
file.addAction("show")
file.addAction("add")
file.addAction("remove")
file.triggered[QAction].connect(self.processtrigger)
self.setCentralWidget(QTextEdit())
self.statusBar = QStatusBar()
self.b = QPushButton("click here")
self.setWindowTitle("QStatusBar Example")
self.setStatusBar(self.statusBar)
def processtrigger(self,q):
if (q.text() == "show"):
self.statusBar.showMessage(q.text()+" is clicked",2000)
if q.text() == "add":
self.statusBar.addWidget(self.b)
if q.text() == "remove":
self.statusBar.removeWidget(self.b)
self.statusBar.show()
def main():
app = QApplication(sys.argv)
ex = statusdemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The above code produces the following output −
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2077,
"s": 1926,
"text": "QMainWindow object reserves a horizontal bar at the bottom as the status bar. It is used to display either permanent or contextual status information."
},
{
"code": null,
"e": 2122,
"s": 2077,
"text": "There are three types of status indicators −"
},
{
"code": null,
"e": 2236,
"s": 2122,
"text": "Temporary − Briefly occupies most of the status bar. For example, used to explain tool tip texts or menu entries."
},
{
"code": null,
"e": 2350,
"s": 2236,
"text": "Temporary − Briefly occupies most of the status bar. For example, used to explain tool tip texts or menu entries."
},
{
"code": null,
"e": 2507,
"s": 2350,
"text": "Normal − Occupies part of the status bar and may be hidden by temporary messages. For example, used to display the page and line number in a word processor."
},
{
"code": null,
"e": 2664,
"s": 2507,
"text": "Normal − Occupies part of the status bar and may be hidden by temporary messages. For example, used to display the page and line number in a word processor."
},
{
"code": null,
"e": 2809,
"s": 2664,
"text": "Permanent − It is never hidden. Used for important mode indications. For example, some applications put a Caps Lock indicator in the status bar."
},
{
"code": null,
"e": 2954,
"s": 2809,
"text": "Permanent − It is never hidden. Used for important mode indications. For example, some applications put a Caps Lock indicator in the status bar."
},
{
"code": null,
"e": 3056,
"s": 2954,
"text": "Status bar of QMainWindow is retrieved by statusBar() function. setStatusBar() function activates it."
},
{
"code": null,
"e": 3121,
"s": 3056,
"text": "self.statusBar = QStatusBar()\nself.setStatusBar(self.statusBar)\n"
},
{
"code": null,
"e": 3133,
"s": 3121,
"text": "addWidget()"
},
{
"code": null,
"e": 3180,
"s": 3133,
"text": "Adds the given widget object in the status bar"
},
{
"code": null,
"e": 3201,
"s": 3180,
"text": "addPermanentWidget()"
},
{
"code": null,
"e": 3260,
"s": 3201,
"text": "Adds the given widget object in the status bar permanently"
},
{
"code": null,
"e": 3274,
"s": 3260,
"text": "showMessage()"
},
{
"code": null,
"e": 3351,
"s": 3274,
"text": "Displays a temporary message in the status bar for a specified time interval"
},
{
"code": null,
"e": 3366,
"s": 3351,
"text": "clearMessage()"
},
{
"code": null,
"e": 3408,
"s": 3366,
"text": "Removes any temporary message being shown"
},
{
"code": null,
"e": 3423,
"s": 3408,
"text": "removeWidget()"
},
{
"code": null,
"e": 3468,
"s": 3423,
"text": "Removes specified widget from the status bar"
},
{
"code": null,
"e": 3579,
"s": 3468,
"text": "In the following example, a top level QMainWindow has a menu bar and a QTextEdit object as its central widget."
},
{
"code": null,
"e": 3632,
"s": 3579,
"text": "Window’s status bar is activated as explained above."
},
{
"code": null,
"e": 3787,
"s": 3632,
"text": "Menu’s triggered signal is passed to processtrigger() slot function. If ‘show’ action is triggered, it displays a temporary message in the status bar as −"
},
{
"code": null,
"e": 3871,
"s": 3787,
"text": "if (q.text() == \"show\"):\n self.statusBar.showMessage(q.text()+\" is clicked\",2000)"
},
{
"code": null,
"e": 3987,
"s": 3871,
"text": "The message will be erased after 2000 milliseconds (2 sec). If ‘add’ action is triggered, a button widget is added."
},
{
"code": null,
"e": 4045,
"s": 3987,
"text": "if q.text() == \"add\":\n self.statusBar.addWidget(self.b)"
},
{
"code": null,
"e": 4103,
"s": 4045,
"text": "Remove action will remove the button from the status bar."
},
{
"code": null,
"e": 4192,
"s": 4103,
"text": "if q.text() == \"remove\":\n self.statusBar.removeWidget(self.b)\n self.statusBar.show()"
},
{
"code": null,
"e": 4226,
"s": 4192,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 5289,
"s": 4226,
"text": "import sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass statusdemo(QMainWindow):\n def __init__(self, parent = None):\n super(statusdemo, self).__init__(parent)\n\t\t\n bar = self.menuBar()\n file = bar.addMenu(\"File\")\n file.addAction(\"show\")\n file.addAction(\"add\")\n file.addAction(\"remove\")\n file.triggered[QAction].connect(self.processtrigger)\n self.setCentralWidget(QTextEdit())\n\t\t\n self.statusBar = QStatusBar()\n self.b = QPushButton(\"click here\")\n self.setWindowTitle(\"QStatusBar Example\")\n self.setStatusBar(self.statusBar)\n\t\t\n def processtrigger(self,q):\n\t\n if (q.text() == \"show\"):\n self.statusBar.showMessage(q.text()+\" is clicked\",2000)\n\t\t\t\n if q.text() == \"add\":\n self.statusBar.addWidget(self.b)\n\t\t\t\n if q.text() == \"remove\":\n self.statusBar.removeWidget(self.b)\n self.statusBar.show()\n\t\t\t\ndef main():\n app = QApplication(sys.argv)\n ex = statusdemo()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 5336,
"s": 5289,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 5373,
"s": 5336,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 5383,
"s": 5373,
"text": " ALAA EID"
},
{
"code": null,
"e": 5390,
"s": 5383,
"text": " Print"
},
{
"code": null,
"e": 5401,
"s": 5390,
"text": " Add Notes"
}
] |
How to sum up elements of a C++ vector?
|
Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.
Begin
Declare v of vector type.
Initialize some values into v vector in array pattern.
Print “Sum of all the elements are:”.
Call accumulate(v.begin(),v.end(),0) to calculate the sum of all
values of v vector.
Print the result of sum.
End.
Live Demo
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
vector<int> v = {2,7,6,10};
cout<<"Sum of all the elements are:"<<endl;
cout<<accumulate(v.begin(),v.end(),0);
}
Sum of all the elements are:
25
|
[
{
"code": null,
"e": 1271,
"s": 1062,
"text": "Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum."
},
{
"code": null,
"e": 1544,
"s": 1271,
"text": "Begin\n Declare v of vector type.\n Initialize some values into v vector in array pattern.\n Print “Sum of all the elements are:”.\n Call accumulate(v.begin(),v.end(),0) to calculate the sum of all\n values of v vector.\n Print the result of sum.\nEnd."
},
{
"code": null,
"e": 1555,
"s": 1544,
"text": " Live Demo"
},
{
"code": null,
"e": 1765,
"s": 1555,
"text": "#include<iostream>\n#include<vector>\n#include<numeric>\nusing namespace std;\nint main() {\n vector<int> v = {2,7,6,10};\n cout<<\"Sum of all the elements are:\"<<endl;\n cout<<accumulate(v.begin(),v.end(),0);\n}"
},
{
"code": null,
"e": 1797,
"s": 1765,
"text": "Sum of all the elements are:\n25"
}
] |
CSS3 Diagonal Gradient
|
Diagonal starts at top left and right button. You can try to run the following code to implement diagonal gradients in CSS3 −
Live Demo
<html>
<head>
<style>
#grad1 {
height: 100px;
background: -webkit-linear-gradient(left top, red , blue);
background: -o-linear-gradient(bottom right, red, blue);
background: -moz-linear-gradient(bottom right, red, blue);
background: linear-gradient(to bottom right, red , blue);
}
</style>
</head>
<body>
<div id = "grad1"></div>
</body>
</html>
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "Diagonal starts at top left and right button. You can try to run the following code to implement diagonal gradients in CSS3 −"
},
{
"code": null,
"e": 1198,
"s": 1188,
"text": "Live Demo"
},
{
"code": null,
"e": 1652,
"s": 1198,
"text": "<html>\n <head>\n <style>\n #grad1 {\n height: 100px;\n background: -webkit-linear-gradient(left top, red , blue);\n background: -o-linear-gradient(bottom right, red, blue);\n background: -moz-linear-gradient(bottom right, red, blue);\n background: linear-gradient(to bottom right, red , blue);\n }\n </style>\n </head>\n <body>\n <div id = \"grad1\"></div>\n </body>\n</html>"
}
] |
Python program to check if binary representation is palindrome?
|
Here we use different python inbuilt function. First we use bin() for converting number into it’s binary for, then reverse the binary form of string and compare with originals, if match then palindrome otherwise not.
Input: 5
Output: palindrome
Binary representation of 5 is 101
Reverse it and result is 101, then compare and its match with originals.
So its palindrome
Palindromenumber(n)
/* n is the number */
Step 1: input n
Step 2: convert n into binary form.
Step 3: skip the first two characters of a string.
Step 4: them reverse the binary string and compare with originals.
Step 5: if its match with originals then print Palindrome, otherwise not a palindrome.
# To check if binary representation of a number is pallindrome or not
defpalindromenumber(n):
# convert number into binary bn_number = bin(n)
# skip first two characters of string
# Because bin function appends '0b' as
# prefix in binary
#representation of a number bn_number = bn_number[2:]
# now reverse binary string and compare it with original
if(bn_number == bn_number[-1::-1]):
print(n," IS A PALINDROME NUMBER")
else:
print(n, "IS NOT A PALINDROME NUMBER")
# Driver program
if __name__ == "__main__":
n=int(input("Enter Number ::>"))
palindromenumber(n)
Enter Number ::>10
10 IS NOT A PALINDROME NUMBER
Enter Number ::>9
9 IS A PALINDROME NUMBER
|
[
{
"code": null,
"e": 1279,
"s": 1062,
"text": "Here we use different python inbuilt function. First we use bin() for converting number into it’s binary for, then reverse the binary form of string and compare with originals, if match then palindrome otherwise not."
},
{
"code": null,
"e": 1308,
"s": 1279,
"text": "Input: 5\nOutput: palindrome\n"
},
{
"code": null,
"e": 1342,
"s": 1308,
"text": "Binary representation of 5 is 101"
},
{
"code": null,
"e": 1415,
"s": 1342,
"text": "Reverse it and result is 101, then compare and its match with originals."
},
{
"code": null,
"e": 1433,
"s": 1415,
"text": "So its palindrome"
},
{
"code": null,
"e": 1733,
"s": 1433,
"text": "Palindromenumber(n)\n/* n is the number */\nStep 1: input n\nStep 2: convert n into binary form.\nStep 3: skip the first two characters of a string.\nStep 4: them reverse the binary string and compare with originals.\nStep 5: if its match with originals then print Palindrome, otherwise not a palindrome.\n"
},
{
"code": null,
"e": 2346,
"s": 1733,
"text": "# To check if binary representation of a number is pallindrome or not\ndefpalindromenumber(n): \n # convert number into binary bn_number = bin(n) \n # skip first two characters of string\n # Because bin function appends '0b' as \n # prefix in binary \n #representation of a number bn_number = bn_number[2:]\n # now reverse binary string and compare it with original\n if(bn_number == bn_number[-1::-1]):\n print(n,\" IS A PALINDROME NUMBER\")\n else:\n print(n, \"IS NOT A PALINDROME NUMBER\")\n# Driver program\nif __name__ == \"__main__\":\n n=int(input(\"Enter Number ::>\"))\n palindromenumber(n)"
},
{
"code": null,
"e": 2439,
"s": 2346,
"text": "Enter Number ::>10\n10 IS NOT A PALINDROME NUMBER\nEnter Number ::>9\n9 IS A PALINDROME NUMBER\n"
}
] |
C program to Calculate Body Mass Index (BMI)
|
Given with the weight and height of a person and the task is to find the BMI i.e. body mass index of his body and display it.
For calculating the body mass index we require two things −
Weight
Height
BMI can be calculated using the formula given below −
BMI = (mass or weight) / (height*height)
Where weight is in kg and height is in meters
Input 1-: weight = 60.00
Height = 5.1
Output -: BMI index is : 23.53
Input 2-: weight = 54.00
Height = 5.4
Output -: BMI index is : 9.3
Approach used below is as follows −
Input weight(kg) and height(meter) in float variables
Apply the formula to compute the body mass index
Print the BMI
Start
Step 1-> Declare function to calculate BMI
float BMI(float weight, float height)
return weight/height*2
step 2-> In main()
Set float weight=60.00
Set float height=5.1
Set float bmi = BMI(weight,height)
Print BMI
Stop
Live Demo
#include<stdio.h>
//function to calculate BMI index
float BMI(float weight, float height) {
return weight/height*2;
}
int main() {
float weight=60.00;
float height=5.1;
float bmi = BMI(weight,height);
printf("BMI index is : %.2f ",bmi);
return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
BMI index is : 23.53
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "Given with the weight and height of a person and the task is to find the BMI i.e. body mass index of his body and display it."
},
{
"code": null,
"e": 1248,
"s": 1188,
"text": "For calculating the body mass index we require two things −"
},
{
"code": null,
"e": 1255,
"s": 1248,
"text": "Weight"
},
{
"code": null,
"e": 1262,
"s": 1255,
"text": "Height"
},
{
"code": null,
"e": 1316,
"s": 1262,
"text": "BMI can be calculated using the formula given below −"
},
{
"code": null,
"e": 1357,
"s": 1316,
"text": "BMI = (mass or weight) / (height*height)"
},
{
"code": null,
"e": 1403,
"s": 1357,
"text": "Where weight is in kg and height is in meters"
},
{
"code": null,
"e": 1545,
"s": 1403,
"text": "Input 1-: weight = 60.00\n Height = 5.1\nOutput -: BMI index is : 23.53\nInput 2-: weight = 54.00\n Height = 5.4\nOutput -: BMI index is : 9.3"
},
{
"code": null,
"e": 1581,
"s": 1545,
"text": "Approach used below is as follows −"
},
{
"code": null,
"e": 1635,
"s": 1581,
"text": "Input weight(kg) and height(meter) in float variables"
},
{
"code": null,
"e": 1684,
"s": 1635,
"text": "Apply the formula to compute the body mass index"
},
{
"code": null,
"e": 1698,
"s": 1684,
"text": "Print the BMI"
},
{
"code": null,
"e": 1942,
"s": 1698,
"text": "Start\nStep 1-> Declare function to calculate BMI\n float BMI(float weight, float height)\n return weight/height*2\nstep 2-> In main()\n Set float weight=60.00\n Set float height=5.1\n Set float bmi = BMI(weight,height)\n Print BMI\nStop"
},
{
"code": null,
"e": 1953,
"s": 1942,
"text": " Live Demo"
},
{
"code": null,
"e": 2220,
"s": 1953,
"text": "#include<stdio.h>\n//function to calculate BMI index\nfloat BMI(float weight, float height) {\n return weight/height*2;\n}\nint main() {\n float weight=60.00;\n float height=5.1;\n float bmi = BMI(weight,height);\n printf(\"BMI index is : %.2f \",bmi);\n return 0;\n}"
},
{
"code": null,
"e": 2279,
"s": 2220,
"text": "IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT"
},
{
"code": null,
"e": 2300,
"s": 2279,
"text": "BMI index is : 23.53"
}
] |
Command line arguments in C/C++
|
It is possible to pass some values from the command line to your C programs when
they are executed. These values are called command line arguments and many
times they are important for your program especially when you want to control your
program from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where
argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program. Following is a simple example which
checks if there is any argument supplied from the command line and take action
accordingly −
Live Demo
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
$./a.out testing
The argument supplied is testing
$./a.out testing1 testing2
Too many arguments supplied.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a
pointer to the first command line argument supplied, and *argv[n] is the last
argument. If no arguments are supplied, argc will be one, and if you pass one
argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument
itself has a space then you can pass such arguments by putting them inside double
quotes "" or single quotes ''. Let us re-write above example once again where we will
print program name and we also pass a command line argument by putting inside
double quotes −
Live Demo
#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
$./a.out "testing1 testing2"
Progranm name ./a.out
The argument supplied is testing1 testing2
|
[
{
"code": null,
"e": 1375,
"s": 1062,
"text": "It is possible to pass some values from the command line to your C programs when\nthey are executed. These values are called command line arguments and many\ntimes they are important for your program especially when you want to control your\nprogram from outside instead of hard coding those values inside the code."
},
{
"code": null,
"e": 1711,
"s": 1375,
"text": "The command line arguments are handled using main() function arguments where\nargc refers to the number of arguments passed, and argv[] is a pointer array which\npoints to each argument passed to the program. Following is a simple example which\nchecks if there is any argument supplied from the command line and take action\naccordingly −"
},
{
"code": null,
"e": 1722,
"s": 1711,
"text": " Live Demo"
},
{
"code": null,
"e": 1997,
"s": 1722,
"text": "#include <stdio.h>\nint main( int argc, char *argv[] ) {\n if( argc == 2 ) {\n printf(\"The argument supplied is %s\\n\", argv[1]);\n }\n else if( argc > 2 ) {\n printf(\"Too many arguments supplied.\\n\");\n }\n else {\n printf(\"One argument expected.\\n\");\n }\n}"
},
{
"code": null,
"e": 2047,
"s": 1997,
"text": "$./a.out testing\nThe argument supplied is testing"
},
{
"code": null,
"e": 2103,
"s": 2047,
"text": "$./a.out testing1 testing2\nToo many arguments supplied."
},
{
"code": null,
"e": 2134,
"s": 2103,
"text": "$./a.out\nOne argument expected"
},
{
"code": null,
"e": 2408,
"s": 2134,
"text": "It should be noted that argv[0] holds the name of the program itself and argv[1] is a\npointer to the first command line argument supplied, and *argv[n] is the last\nargument. If no arguments are supplied, argc will be one, and if you pass one\nargument then argc is set at 2."
},
{
"code": null,
"e": 2748,
"s": 2408,
"text": "You pass all the command line arguments separated by a space, but if argument\nitself has a space then you can pass such arguments by putting them inside double\nquotes \"\" or single quotes ''. Let us re-write above example once again where we will\nprint program name and we also pass a command line argument by putting inside\ndouble quotes −"
},
{
"code": null,
"e": 2759,
"s": 2748,
"text": " Live Demo"
},
{
"code": null,
"e": 3075,
"s": 2759,
"text": "#include <stdio.h>\nint main( int argc, char *argv[] ) {\n printf(\"Program name %s\\n\", argv[0]);\n if( argc == 2 ) {\n printf(\"The argument supplied is %s\\n\", argv[1]);\n }\n else if( argc > 2 ) {\n printf(\"Too many arguments supplied.\\n\");\n }\n else {\n printf(\"One argument expected.\\n\");\n }\n}"
},
{
"code": null,
"e": 3169,
"s": 3075,
"text": "$./a.out \"testing1 testing2\"\nProgranm name ./a.out\nThe argument supplied is testing1 testing2"
}
] |
Python Generators. A tutorial on developing python... | by Anuradha Wickramarachchi | Towards Data Science
|
In simple terms, Python generators facilitate functionality to maintain persistent states. This enables incremental computations and iterations. Furthermore, generators can be used in place of arrays to save memory. This is because generators do not store the values, but rather the computation logic with the state of the function, similar to an unevaluated function instance ready to be fired.
Generator expressions can be used in place of array create operations. Unlike an array, the generator will generate numbers at runtime.
>>> import sys>>> a = [x for x in range(1000000)]>>> b = (x for x in range(1000000))>>> sys.getsizeof(a)8697472>>> sys.getsizeof(b)128>>> a[0, 1, ... 999999]>>> b<generator object <genexpr> at 0x1020de6d0>
We can see that in the above scenario, we are saving quite a lot of memory by having the generator in place of the array.
Let us consider a simple example where you want to generate an arbitrary number of prime numbers. The following are the functions to check if a number is prime and the generator that will yield us infinitely many prime numbers.
def isPrime(n): if n < 2 or n % 1 > 0: return False elif n == 2 or n == 3: return True for x in range(2, int(n**0.5) + 1): if n % x == 0: return False return Truedef getPrimes(): value = 0 while True: if isPrime(value): yield value value += 1
As you can see in the second function we iterate in a while loop and yield the numbers that are prime. Let’s see how we can use the above generator.
primes = getPrimes()>>> next(primes)2>>> next(primes)3>>> next(primes)5
First, we call the function and get the generator instance. Although this can emulate an infinite array, there is no element to be found yet. If you call list(primes), your program could crash with a MemoryError. However, for prime numbers, it will not go there since the prime number space is sparse for computations to reach the memory limit in a finite time. However, for generators, you will not know the length beforehand. If you call len(primes) you’ll get the following error for the very same reason that the numbers are only generated at the run time.
----------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-33-a6773446b45c> in <module>----> 1 len(primes)TypeError: object of type 'generator' has no len()
Although our prime number example has an infinite iteration space, in most day-to-day scenarios we face with finite computations. Therefore, let’s have a look at an example that we can use to read a file containing text data and the semantic score of the sentence in the next line.
Imagine the file is 1TB and the corpus of words is 500000. It would not fit in memory. A simple solution is to read 2 lines at once, compute a dictionary of words per line and return it with the semantic score in the next line. The file would look like below.
The product is well packed5Edges of the packaging was damaged and print was faded.3Avoid this product. Never going to buy anything from ShopX.1Shipping took a very long time2
It is a clear fact that we do not need to open the file at once. Furthermore, the lines must be vectorized and possibly saved into another file that can be parsed straightaway to train a machine learning model. So the option that will give us a clean code is to use a generator that will read two lines at once and give us the data and semantic score as a tuple.
Assume that we have the above text document in a file named test.txt. We will be using the following generator function to read the file.
def readData(path): with open(path) as f: sentiment = "" line = "" for n, d in enumerate(f): if n % 2 == 0: line = d.strip() else: sentiment = int(d.strip()) yield line, sentiment
We can use the above function in a for loop as follows.
>>> data = readData("test.txt")>>> for l, s in data: print(l, s)The product is well packed 5Edges of the packaging was damaged and print was faded. 3Avoid this product. Never going to buy anything from ShopX. 1Shipping took a very long time 2
In a normal for loop, the iteration is stopped when no more yielding is performed by the generator. However, this can be observed by us manually calling next() on the generator instance. Calling the next() beyond the iteration limit will raise the following exception.
----------------------------------------------------------------StopIteration Traceback (most recent call last)<ipython-input-41-cddec6aa1599> in <module>---> 28 print(next(data))StopIteration:
Let's recall our prime numbers example. Imagine we want to reset our generator function’s value to 100 to start yielding values above 100 if they’re prime. We can use send() method on a generator instance to push a value into the generator as below.
>>> primes = getPrimes()>>> next(primes)2>>> primes.send(10)11>>> primes.send(100)101
Note that we must call next() at least once before we call send(). Let’s see how we must modify our function to fit the purpose. Because the function should know how to assign the received value.
def getPrimes(): value = 0 while True: if isPrime(value): i = yield value if i is not None: value = i value += 1
We store the yielded value in the variable i. If that’s not None type, we assign it to the value variable. None check is essential as the first next() will have no value in value variable to yield.
Imagine you want to end the iteration at a value above 10 to avoid overflow or timeouts (hypothetically). The throw() function can be used to prompt the generator to halt raising an exception.
primes = getPrimes()for x in primes: if x > 10: primes.throw(ValueError, "Too large") print(x)
This technique is useful to validate inputs. The logic lies upon the user of the generator. This will result in the following output.
2357----------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-113-37adca265503> in <module> 12 for x in primes: 13 if x > 10:---> 14 primes.throw(ValueError, "Too large") 15 print(x)<ipython-input-113-37adca265503> in getPrimes() 3 while True: 4 if isPrime(value):----> 5 i = yield value 6 if i is not None: 7 value = iValueError: Too large
It is often elegant to handle the closure without an exception in hand. In such scenarios, theclose() function can be used to effectively close the iterator.
primes = getPrimes()for x in primes: if x > 10: primes.close() print(x)
This will give us the following output.
235711
Note that we have value 11 which is the last computed value greater than 11. This simulates the behaviour of a do while loop in C/C++.
I believe this article would help you to make better software and research programs in future. Thanks for reading.
|
[
{
"code": null,
"e": 568,
"s": 172,
"text": "In simple terms, Python generators facilitate functionality to maintain persistent states. This enables incremental computations and iterations. Furthermore, generators can be used in place of arrays to save memory. This is because generators do not store the values, but rather the computation logic with the state of the function, similar to an unevaluated function instance ready to be fired."
},
{
"code": null,
"e": 704,
"s": 568,
"text": "Generator expressions can be used in place of array create operations. Unlike an array, the generator will generate numbers at runtime."
},
{
"code": null,
"e": 910,
"s": 704,
"text": ">>> import sys>>> a = [x for x in range(1000000)]>>> b = (x for x in range(1000000))>>> sys.getsizeof(a)8697472>>> sys.getsizeof(b)128>>> a[0, 1, ... 999999]>>> b<generator object <genexpr> at 0x1020de6d0>"
},
{
"code": null,
"e": 1032,
"s": 910,
"text": "We can see that in the above scenario, we are saving quite a lot of memory by having the generator in place of the array."
},
{
"code": null,
"e": 1260,
"s": 1032,
"text": "Let us consider a simple example where you want to generate an arbitrary number of prime numbers. The following are the functions to check if a number is prime and the generator that will yield us infinitely many prime numbers."
},
{
"code": null,
"e": 1578,
"s": 1260,
"text": "def isPrime(n): if n < 2 or n % 1 > 0: return False elif n == 2 or n == 3: return True for x in range(2, int(n**0.5) + 1): if n % x == 0: return False return Truedef getPrimes(): value = 0 while True: if isPrime(value): yield value value += 1"
},
{
"code": null,
"e": 1727,
"s": 1578,
"text": "As you can see in the second function we iterate in a while loop and yield the numbers that are prime. Let’s see how we can use the above generator."
},
{
"code": null,
"e": 1799,
"s": 1727,
"text": "primes = getPrimes()>>> next(primes)2>>> next(primes)3>>> next(primes)5"
},
{
"code": null,
"e": 2360,
"s": 1799,
"text": "First, we call the function and get the generator instance. Although this can emulate an infinite array, there is no element to be found yet. If you call list(primes), your program could crash with a MemoryError. However, for prime numbers, it will not go there since the prime number space is sparse for computations to reach the memory limit in a finite time. However, for generators, you will not know the length beforehand. If you call len(primes) you’ll get the following error for the very same reason that the numbers are only generated at the run time."
},
{
"code": null,
"e": 2601,
"s": 2360,
"text": "----------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-33-a6773446b45c> in <module>----> 1 len(primes)TypeError: object of type 'generator' has no len()"
},
{
"code": null,
"e": 2883,
"s": 2601,
"text": "Although our prime number example has an infinite iteration space, in most day-to-day scenarios we face with finite computations. Therefore, let’s have a look at an example that we can use to read a file containing text data and the semantic score of the sentence in the next line."
},
{
"code": null,
"e": 3143,
"s": 2883,
"text": "Imagine the file is 1TB and the corpus of words is 500000. It would not fit in memory. A simple solution is to read 2 lines at once, compute a dictionary of words per line and return it with the semantic score in the next line. The file would look like below."
},
{
"code": null,
"e": 3318,
"s": 3143,
"text": "The product is well packed5Edges of the packaging was damaged and print was faded.3Avoid this product. Never going to buy anything from ShopX.1Shipping took a very long time2"
},
{
"code": null,
"e": 3681,
"s": 3318,
"text": "It is a clear fact that we do not need to open the file at once. Furthermore, the lines must be vectorized and possibly saved into another file that can be parsed straightaway to train a machine learning model. So the option that will give us a clean code is to use a generator that will read two lines at once and give us the data and semantic score as a tuple."
},
{
"code": null,
"e": 3819,
"s": 3681,
"text": "Assume that we have the above text document in a file named test.txt. We will be using the following generator function to read the file."
},
{
"code": null,
"e": 4090,
"s": 3819,
"text": "def readData(path): with open(path) as f: sentiment = \"\" line = \"\" for n, d in enumerate(f): if n % 2 == 0: line = d.strip() else: sentiment = int(d.strip()) yield line, sentiment"
},
{
"code": null,
"e": 4146,
"s": 4090,
"text": "We can use the above function in a for loop as follows."
},
{
"code": null,
"e": 4389,
"s": 4146,
"text": ">>> data = readData(\"test.txt\")>>> for l, s in data: print(l, s)The product is well packed 5Edges of the packaging was damaged and print was faded. 3Avoid this product. Never going to buy anything from ShopX. 1Shipping took a very long time 2"
},
{
"code": null,
"e": 4658,
"s": 4389,
"text": "In a normal for loop, the iteration is stopped when no more yielding is performed by the generator. However, this can be observed by us manually calling next() on the generator instance. Calling the next() beyond the iteration limit will raise the following exception."
},
{
"code": null,
"e": 4869,
"s": 4658,
"text": "----------------------------------------------------------------StopIteration Traceback (most recent call last)<ipython-input-41-cddec6aa1599> in <module>---> 28 print(next(data))StopIteration:"
},
{
"code": null,
"e": 5119,
"s": 4869,
"text": "Let's recall our prime numbers example. Imagine we want to reset our generator function’s value to 100 to start yielding values above 100 if they’re prime. We can use send() method on a generator instance to push a value into the generator as below."
},
{
"code": null,
"e": 5205,
"s": 5119,
"text": ">>> primes = getPrimes()>>> next(primes)2>>> primes.send(10)11>>> primes.send(100)101"
},
{
"code": null,
"e": 5401,
"s": 5205,
"text": "Note that we must call next() at least once before we call send(). Let’s see how we must modify our function to fit the purpose. Because the function should know how to assign the received value."
},
{
"code": null,
"e": 5571,
"s": 5401,
"text": "def getPrimes(): value = 0 while True: if isPrime(value): i = yield value if i is not None: value = i value += 1"
},
{
"code": null,
"e": 5769,
"s": 5571,
"text": "We store the yielded value in the variable i. If that’s not None type, we assign it to the value variable. None check is essential as the first next() will have no value in value variable to yield."
},
{
"code": null,
"e": 5962,
"s": 5769,
"text": "Imagine you want to end the iteration at a value above 10 to avoid overflow or timeouts (hypothetically). The throw() function can be used to prompt the generator to halt raising an exception."
},
{
"code": null,
"e": 6070,
"s": 5962,
"text": "primes = getPrimes()for x in primes: if x > 10: primes.throw(ValueError, \"Too large\") print(x)"
},
{
"code": null,
"e": 6204,
"s": 6070,
"text": "This technique is useful to validate inputs. The logic lies upon the user of the generator. This will result in the following output."
},
{
"code": null,
"e": 6730,
"s": 6204,
"text": "2357----------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-113-37adca265503> in <module> 12 for x in primes: 13 if x > 10:---> 14 primes.throw(ValueError, \"Too large\") 15 print(x)<ipython-input-113-37adca265503> in getPrimes() 3 while True: 4 if isPrime(value):----> 5 i = yield value 6 if i is not None: 7 value = iValueError: Too large"
},
{
"code": null,
"e": 6888,
"s": 6730,
"text": "It is often elegant to handle the closure without an exception in hand. In such scenarios, theclose() function can be used to effectively close the iterator."
},
{
"code": null,
"e": 6973,
"s": 6888,
"text": "primes = getPrimes()for x in primes: if x > 10: primes.close() print(x)"
},
{
"code": null,
"e": 7013,
"s": 6973,
"text": "This will give us the following output."
},
{
"code": null,
"e": 7020,
"s": 7013,
"text": "235711"
},
{
"code": null,
"e": 7155,
"s": 7020,
"text": "Note that we have value 11 which is the last computed value greater than 11. This simulates the behaviour of a do while loop in C/C++."
}
] |
Going from R to Python — Linear Regression Diagnostic Plots | by Jason Sadowski | Towards Data Science
|
As a long time R user that has transitioned into Python, one of the things that I miss most about R is easily generating diagnostic plots for a linear regression. There are some great resources on how to conduct linear regression analyses in Python (see here for example), but I haven’t found an intuitive resource on generating the diagnostic plots that I know and love from R.
I decided to build some wrapper functions for the four plots that come up when you use the plot(lm) command in R. Those plots are:
Residuals vs. Fitted ValuesNormal Q-Q PlotStandardized Residuals vs. Fitted ValuesStandardized Residuals vs. Leverage
Residuals vs. Fitted Values
Normal Q-Q Plot
Standardized Residuals vs. Fitted Values
Standardized Residuals vs. Leverage
The first step is to conduct the regression. Because this post is all about R-nostalgia I decided to use a classic R dataset: mtcars. It’s relatively small, has interesting dynamics, and has categorical both continuous data. You can import this dataset into python pretty easily by installing the pydataset module. While this module hasn’t been updated since 2016, the mtcars dataset is from 1974, so the data we want are available. Here are the modules I’ll be using in this post:
Now let’s import the mtcars dataframe and take a look at it.
The documentation for this dataset can be accessed via the command:
data('mtcars', show_doc = True)
In particular I’m interested in predicting miles per gallon (mpg) using the number of cylinders (cyl) and the weight of the car (wt). I hypothesize that mpg will decrease with cyl and wt. The statsmodels formula API uses the same formula interface as an R lm function. Note that in python you first need to create a model, then fit the model rather than the one-step process of creating and fitting a model in R. This two-step process is pretty standard across multiple python modules.
Importantly, the statsmodels formula API automatically includes an intercept into the regression. The raw statsmodels interface does not do this so adjust your code accordingly.
The amount of variance explained by the model is pretty high (R^2 = 0.83), and both cyl and wt are negative and significant, supporting my initial hypothesis. There is plenty to unpack in this OLS output, but for this post I’m not going to explore all of the outputs nor discuss statistical significance/non-significance. This post is all about constructing the outlier detection and assumption check plots so common in base R.
Do the data fit the assumptions of a OLS model? Let’s get to plotting!
First, let’s check if there is structure in the residuals relative to the fitted values. This plot is relatively straightforward to create. The plan here is to extract the residuals and fitted values from the fitted model, calculate a lowess smoothed line through those points, then plot. The annotations are the top three indices of the greatest absolute value of the residual.
In this case there may be a slight nonlinear structure in the residuals, and probably worth testing other models. The Fiat 128, Toyota Corolla, and Toyota Corona could be outliers in the dataset, but it’s worth further exploration.
Do the residuals follow a normal distribution? To test this we need the second plot, a quantile - quantile (Q-Q) plot with theoretical quantiles created by the normal distribution. Statsmodels has a qqplot function, but it’s difficult to annotate and customize into a base R-style graph. Not to worry, constructing a Q-Q plot is relatively straightforward.
We can extract the theoretical quantiles from the stats.probplot() function. I used the internally studentized residuals here since they’ll be needed for the third and fourth graph, but you can use the raw residuals if you prefer. Then we’ll plot the studentized residuals against the theoretical quantiles and add a 1:1 line for visual comparison. The annotations are the three points with the greatest absolute value in studentized residual.
Here we can see that the residuals all generally follow the 1:1 line indicating that they probably come from a normal distribution. While difficult to read (just like in base R, ah the memories) Fiat 128, Toyota Corolla, and Chrysler Imperial stand out as both the largest magnitude in studentized residuals as and also appear to deviate from the theoretical quantile line.
Now we can test the assumption of homoskedasticity using the scale-location plot. Base R plots the square root of the “standardized residuals” against the fitted values. “Standardized residuals” is a bit vague so after searching online, it turns out “standardized residuals” are actually the internally studentized residuals. As I showed above, extracting the internally studentized residuals from the fitted model is straightforward. After that we’ll take the square root of their absolute value, then plot the transformed residuals against the fitted values. If the scatter in the plots is consistent across the entire range of fitted values, then we can safely assume that the data fit the assumption of homoskedasticity. I’ve annotated for the three largest values of the square root transformed studentized residuals.
In this case there appears to be an upward trend in the lowess smoother. This could be indicative of heteroskedasticity. This heteroskedasticity would probably be worse if I removed the Chrysler Imperial point, so this assumption could be violated in our model.
Finally, I constructed the residuals vs. leverage plot. The response variable is again the internally studentized residuals. The x-axis here is the leverage, as determined via the diagonal of the OLS hat matrix. The tricky part here is adding in the lines for the Cook’s Distance (see here on how to construct these plots in seaborn). The annotations are the top three studentized residuals with the largest absolute value.
There is some evidence in this plot that the Chrysler Imperial has an unusually large effect on the model. Which makes sense given that it’s an outlier at the minimum edge of the possible range of fitted-values.
If you are interested in creating these diagnostic plots yourself, I created a simple module (OLSplots.py) that replicates the plots shown above. I’ve hosted this module as well as the Jupyter notebook for conducting this analysis on my github repository.
Some guidelines:
If you are using a test-train split for your regressions, then you should run the diagnostic plots on the trained regression model before testing the model.The current module cannot handle a regression done in sklearn, but they should be relatively easy to incorporate at a later stage.The OLSplots.py module currently has no error messages built in, so you’ll need to debug on your own. That being said, if you pass a fitted OLS model from statsmodel into any function, it should work fine.The text annotations are the index values for the pandas dataframe used to construct the OLS model, so they will work for numeric values as well.
If you are using a test-train split for your regressions, then you should run the diagnostic plots on the trained regression model before testing the model.
The current module cannot handle a regression done in sklearn, but they should be relatively easy to incorporate at a later stage.
The OLSplots.py module currently has no error messages built in, so you’ll need to debug on your own. That being said, if you pass a fitted OLS model from statsmodel into any function, it should work fine.
The text annotations are the index values for the pandas dataframe used to construct the OLS model, so they will work for numeric values as well.
Thanks for reading. That’s all for now!
|
[
{
"code": null,
"e": 551,
"s": 172,
"text": "As a long time R user that has transitioned into Python, one of the things that I miss most about R is easily generating diagnostic plots for a linear regression. There are some great resources on how to conduct linear regression analyses in Python (see here for example), but I haven’t found an intuitive resource on generating the diagnostic plots that I know and love from R."
},
{
"code": null,
"e": 682,
"s": 551,
"text": "I decided to build some wrapper functions for the four plots that come up when you use the plot(lm) command in R. Those plots are:"
},
{
"code": null,
"e": 800,
"s": 682,
"text": "Residuals vs. Fitted ValuesNormal Q-Q PlotStandardized Residuals vs. Fitted ValuesStandardized Residuals vs. Leverage"
},
{
"code": null,
"e": 828,
"s": 800,
"text": "Residuals vs. Fitted Values"
},
{
"code": null,
"e": 844,
"s": 828,
"text": "Normal Q-Q Plot"
},
{
"code": null,
"e": 885,
"s": 844,
"text": "Standardized Residuals vs. Fitted Values"
},
{
"code": null,
"e": 921,
"s": 885,
"text": "Standardized Residuals vs. Leverage"
},
{
"code": null,
"e": 1403,
"s": 921,
"text": "The first step is to conduct the regression. Because this post is all about R-nostalgia I decided to use a classic R dataset: mtcars. It’s relatively small, has interesting dynamics, and has categorical both continuous data. You can import this dataset into python pretty easily by installing the pydataset module. While this module hasn’t been updated since 2016, the mtcars dataset is from 1974, so the data we want are available. Here are the modules I’ll be using in this post:"
},
{
"code": null,
"e": 1464,
"s": 1403,
"text": "Now let’s import the mtcars dataframe and take a look at it."
},
{
"code": null,
"e": 1532,
"s": 1464,
"text": "The documentation for this dataset can be accessed via the command:"
},
{
"code": null,
"e": 1564,
"s": 1532,
"text": "data('mtcars', show_doc = True)"
},
{
"code": null,
"e": 2050,
"s": 1564,
"text": "In particular I’m interested in predicting miles per gallon (mpg) using the number of cylinders (cyl) and the weight of the car (wt). I hypothesize that mpg will decrease with cyl and wt. The statsmodels formula API uses the same formula interface as an R lm function. Note that in python you first need to create a model, then fit the model rather than the one-step process of creating and fitting a model in R. This two-step process is pretty standard across multiple python modules."
},
{
"code": null,
"e": 2228,
"s": 2050,
"text": "Importantly, the statsmodels formula API automatically includes an intercept into the regression. The raw statsmodels interface does not do this so adjust your code accordingly."
},
{
"code": null,
"e": 2656,
"s": 2228,
"text": "The amount of variance explained by the model is pretty high (R^2 = 0.83), and both cyl and wt are negative and significant, supporting my initial hypothesis. There is plenty to unpack in this OLS output, but for this post I’m not going to explore all of the outputs nor discuss statistical significance/non-significance. This post is all about constructing the outlier detection and assumption check plots so common in base R."
},
{
"code": null,
"e": 2727,
"s": 2656,
"text": "Do the data fit the assumptions of a OLS model? Let’s get to plotting!"
},
{
"code": null,
"e": 3106,
"s": 2727,
"text": "First, let’s check if there is structure in the residuals relative to the fitted values. This plot is relatively straightforward to create. The plan here is to extract the residuals and fitted values from the fitted model, calculate a lowess smoothed line through those points, then plot. The annotations are the top three indices of the greatest absolute value of the residual."
},
{
"code": null,
"e": 3338,
"s": 3106,
"text": "In this case there may be a slight nonlinear structure in the residuals, and probably worth testing other models. The Fiat 128, Toyota Corolla, and Toyota Corona could be outliers in the dataset, but it’s worth further exploration."
},
{
"code": null,
"e": 3695,
"s": 3338,
"text": "Do the residuals follow a normal distribution? To test this we need the second plot, a quantile - quantile (Q-Q) plot with theoretical quantiles created by the normal distribution. Statsmodels has a qqplot function, but it’s difficult to annotate and customize into a base R-style graph. Not to worry, constructing a Q-Q plot is relatively straightforward."
},
{
"code": null,
"e": 4139,
"s": 3695,
"text": "We can extract the theoretical quantiles from the stats.probplot() function. I used the internally studentized residuals here since they’ll be needed for the third and fourth graph, but you can use the raw residuals if you prefer. Then we’ll plot the studentized residuals against the theoretical quantiles and add a 1:1 line for visual comparison. The annotations are the three points with the greatest absolute value in studentized residual."
},
{
"code": null,
"e": 4513,
"s": 4139,
"text": "Here we can see that the residuals all generally follow the 1:1 line indicating that they probably come from a normal distribution. While difficult to read (just like in base R, ah the memories) Fiat 128, Toyota Corolla, and Chrysler Imperial stand out as both the largest magnitude in studentized residuals as and also appear to deviate from the theoretical quantile line."
},
{
"code": null,
"e": 5336,
"s": 4513,
"text": "Now we can test the assumption of homoskedasticity using the scale-location plot. Base R plots the square root of the “standardized residuals” against the fitted values. “Standardized residuals” is a bit vague so after searching online, it turns out “standardized residuals” are actually the internally studentized residuals. As I showed above, extracting the internally studentized residuals from the fitted model is straightforward. After that we’ll take the square root of their absolute value, then plot the transformed residuals against the fitted values. If the scatter in the plots is consistent across the entire range of fitted values, then we can safely assume that the data fit the assumption of homoskedasticity. I’ve annotated for the three largest values of the square root transformed studentized residuals."
},
{
"code": null,
"e": 5598,
"s": 5336,
"text": "In this case there appears to be an upward trend in the lowess smoother. This could be indicative of heteroskedasticity. This heteroskedasticity would probably be worse if I removed the Chrysler Imperial point, so this assumption could be violated in our model."
},
{
"code": null,
"e": 6022,
"s": 5598,
"text": "Finally, I constructed the residuals vs. leverage plot. The response variable is again the internally studentized residuals. The x-axis here is the leverage, as determined via the diagonal of the OLS hat matrix. The tricky part here is adding in the lines for the Cook’s Distance (see here on how to construct these plots in seaborn). The annotations are the top three studentized residuals with the largest absolute value."
},
{
"code": null,
"e": 6234,
"s": 6022,
"text": "There is some evidence in this plot that the Chrysler Imperial has an unusually large effect on the model. Which makes sense given that it’s an outlier at the minimum edge of the possible range of fitted-values."
},
{
"code": null,
"e": 6490,
"s": 6234,
"text": "If you are interested in creating these diagnostic plots yourself, I created a simple module (OLSplots.py) that replicates the plots shown above. I’ve hosted this module as well as the Jupyter notebook for conducting this analysis on my github repository."
},
{
"code": null,
"e": 6507,
"s": 6490,
"text": "Some guidelines:"
},
{
"code": null,
"e": 7144,
"s": 6507,
"text": "If you are using a test-train split for your regressions, then you should run the diagnostic plots on the trained regression model before testing the model.The current module cannot handle a regression done in sklearn, but they should be relatively easy to incorporate at a later stage.The OLSplots.py module currently has no error messages built in, so you’ll need to debug on your own. That being said, if you pass a fitted OLS model from statsmodel into any function, it should work fine.The text annotations are the index values for the pandas dataframe used to construct the OLS model, so they will work for numeric values as well."
},
{
"code": null,
"e": 7301,
"s": 7144,
"text": "If you are using a test-train split for your regressions, then you should run the diagnostic plots on the trained regression model before testing the model."
},
{
"code": null,
"e": 7432,
"s": 7301,
"text": "The current module cannot handle a regression done in sklearn, but they should be relatively easy to incorporate at a later stage."
},
{
"code": null,
"e": 7638,
"s": 7432,
"text": "The OLSplots.py module currently has no error messages built in, so you’ll need to debug on your own. That being said, if you pass a fitted OLS model from statsmodel into any function, it should work fine."
},
{
"code": null,
"e": 7784,
"s": 7638,
"text": "The text annotations are the index values for the pandas dataframe used to construct the OLS model, so they will work for numeric values as well."
}
] |
How to catch all JavaScript errors?
|
To catch all JavaScript errors, use onerror() method. The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page.
The onerror event handler provides three pieces of information to identify the exact nature of the error −
Error message − The same message that the browser would display for the given error
URL − The file in which the error occurred
Line number− The line number in the given URL that caused the error
Live Demo
You can try to run the following code to catch JavaScript errors −
<html>
<head>
<script>
<!--
window.onerror = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1296,
"s": 1062,
"text": "To catch all JavaScript errors, use onerror() method. The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page."
},
{
"code": null,
"e": 1403,
"s": 1296,
"text": "The onerror event handler provides three pieces of information to identify the exact nature of the error −"
},
{
"code": null,
"e": 1487,
"s": 1403,
"text": "Error message − The same message that the browser would display for the given error"
},
{
"code": null,
"e": 1530,
"s": 1487,
"text": "URL − The file in which the error occurred"
},
{
"code": null,
"e": 1598,
"s": 1530,
"text": "Line number− The line number in the given URL that caused the error"
},
{
"code": null,
"e": 1609,
"s": 1598,
"text": " Live Demo"
},
{
"code": null,
"e": 1676,
"s": 1609,
"text": "You can try to run the following code to catch JavaScript errors −"
},
{
"code": null,
"e": 2150,
"s": 1676,
"text": "<html>\n <head>\n <script>\n <!--\n window.onerror = function (msg, url, line) {\n alert(\"Message : \" + msg );\n alert(\"url : \" + url );\n alert(\"Line number : \" + line );\n }\n //-->\n </script>\n </head>\n <body>\n <p>Click the following to see the result:</p>\n\n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"myFunc();\" />\n </form>\n </body>\n</html>"
}
] |
Prediction using Bayesian State Space Model | by Sarit Maitra | Towards Data Science
|
Time series observations are assumed to depend linearly on a state vector that is unobserved and is generated by a stochastic and dynamic process in a state space analysis. The observations are further assumed to be subject to measurement error and independent of the state vector. Therefore, two main components which make up state space models are an observed data and the unobserved states.
A time-series is described probabilistic by a stochastic process (Yt; t = 1, 2, . . .), that is, by an ordered sequence of random vectors with the index t (time). For simplicity, we will think of equally spaced time points (daily data, monthly data, and so on). The target is to make forecasts about the value of the next observation [yn+1 having observed data up to time n, (y1 = y1, . . . , yn)].
barChart(NG)
This series looks clearly non-stationary and in fact quite irregular and volatile. The data is on daily level since 2007 till date. We can see that, price drooped significantly from nearly $20 to close to $1 during 2008/2009, before being going up till around $15 during 2010/2011; however, a highly volatile state since can be seen all across as on date and last price recorded as $8.61.
We can see from this time series that there is certainly some seasonal variation in the price; there is a peak every winter, and a low turning point almost every winter.
Again the it seems like this could be described using an additive model, as the seasonal fluctuations are roughly constant in size over time and do not seem to depend on the level of the time series, and the random fluctuations seem constant over time.
We will do a uni-variate analysis; so, let us extract the monthly “Close” prices from the data-set. Monthly data was taken for computational ease. Depending on available computational power, data can be taken on hourly, daily or weekly as well.
Following data processing are important to convert the data to data-frame and further time -series for future analysis.
Here, our data-set is now processed and we are ready to perform further analysis.
Most statistical models rely on a normal distribution, a distribution that is symmetric and has a characteristic bell shape. Probability distributions are usually (not entirely) represented in charts whose abscissa axis represents the possible values of the variable and whose ordinal axis represents the probability of occurrence.
The distribution plot comprising density and normal Q-Q plot above clearly shows that data distribution is not normal and reflects non-Gaussian characteristics.
Output from the above stationarity tests show non-stationary characteristics of data.
We normalize the data in the stock prediction scenario because of the values of random behavior. Here, min-max normalization is not advised because the stock values are not limited to a certain price range; the prices having brownian motion and can change dramatically. Therefore, advisable to normalize the stock prices with elementary standardization function:
z = (x — mean(X))/ std(X)
We see here that:
the stationary signal has very few lags exceeding the CI of the ACF .
The trend resulted in almost all lags exceeding the confidence interval.
Therefore, it can be concluded that the ACF signal is stationary. But, the trend signal is not stationary. The stationary series has a better variance around the mean level, and the peaks are evidence of the interventions in the original series. We will further decompose the time series which involves a combination of level, trend, seasonality, and noise components. Decomposition helps to provide a better understanding of problems during analysis and forecasting.
Decomposing a time series means separating it into its constituent components, which are often a trend component and a random component, and if the data is seasonal, a seasonal component.
Non-seasonal time series consist of a trend component and a random component. Decomposing the time series involves tying to separate the time series into these individual components. A seasonal time series, in addition to the trend and random components, also has a seasonal component. Decomposing a seasonal time series means separating the time series into these three components. Let's estimate the trend, seasonal, and random components of the Natural Gas TS.
plot(decompose(df1), yax.flip=TRUE) # Decompose time-series
The above plot clearly shows that trend is non-stationary which we can see from the trend signal plot in the normalization section. The seasonal component exists for a brief period of time every year most likely during the winter session. Overall, the price is highly volatile with random walk movement.
Unfortunately, there is no universally accepted notation for state space models. However, the most commonly used notations in statistical and econometric applications can be found in the work of Harrison & Stevens (1976) and West & Harrison (1997). The main focus is on Bayesian analysis is maximum likelihood (ML) estimation of unknown parameter. We will start with a local level model to introduce the methodology.
We will develop the prediction with a Base Level Model followed by ARIMA and Dynamic Linear Model to compare the prediction output.
State-space models are based on the idea that the time series (Yt) is an incomplete and noisy function of some underlying un-observable process (θt, t = 1, 2, . . .), called the state process.
A structural approach to time-series analysis is facilitated by the state space framework. In this approach, different unobserved components responsible for the dynamics of the series. These are trend, seasonal, cycle, and the effects of explanatory and intervention variables are identified separately before being put together in a state space model. Let us understand the mathematical intuition for local level model.
A time series is normally considered a set of observation y1,......, yn ordered in time. Here, the base model for representing the time series is additive model. The formula can be written as:
μt is a slowly varying component called the trend;
Υt is a periodic component of fixed period and called as seasonal;
εt is random noise or irregular component called error;
To develop suitable models and μt and Υt, we need the concept of random walk. We can consider a simple form of model in which μt = αt, where αt is random walk, no seasonal is present and all random variables are normally distributed. We assume that εt has constant variance σ2ε. This gives the model:
for t = 1,.....,n, where εt’s and ηt’s are mutually independent and independent on α1. There are two parameters, and σ2η. It is an ARIMA(0,1,1) model, but with restrictions on the parameter set. This is called local level model and provides the basis for our analysis. It exhibits the characteristics structure of state space models where there is a series of unobserved values α1,....,αn, which are states and represents the development over time of the system under study together with a set of observations y1,....,yn, which are related to the αt’s by the state space model. This is suitable for both Classical and Bayesian analysis. Where εt’s and ηt’s are not normally distributed we obtain equivalent results from the standpoint of minimum variance linear unbiased estimation.
Initially we assume that, α1 ~ N(α1, P1), where α1 and P1 are known and that σ2ε and σ2η are known. Since, random walk are non-stationary, the model is non-stationary and the distribution of random variables yt and αt depend on time t.
The local linear trend model, type = “trend”, has the same measurement equation, but with a time-varying slope in the dynamics. The basic structural model, type = “BSM”, is a local trend model with an additional seasonal component.
Call:StructTS(x = df1, type = "level")Variances: level epsilon 1.26 0.00
All significance tests in linear Gaussian state space models — and the construction of confidence intervals — are based on assumptions concerning the residuals of the analysis. The residuals should satisfy independence, homoscedasticity, and normality. The independence and normality of the residuals can be diagnosed using the Box-Ljung test statistic. Homoscedasticity can be checked by testing the variance of the standardized prediction errors.
Below plot shows the predicted Close price data for 12 months, together with 50% and 90% probability intervals.
plot(forecast::forecast(fit_level, level = c(50, 90), h = 12), xlim = c(2016, 2021))
pred <- predict(fit_level, n.ahead = 12)
Auto-regressive integrated moving average (ARIMA) model can be put into state space form.
In auto arima is able to decide whether to use or not a seasonal arima (SARIMA) model.
auto.arima(df1, trace = T, stepwise = F, approximation = F)
# Arima arima <- Arima(df1, order = c(0,1,0))checkresiduals(arima)
We can see from the first and last graphs that, the residuals don’t appear to be white noise. The ACF plot shows no significant correlation exists among the residuals.
# Forecast of 12 monthspred_arima <- forecast::forecast(arima, h=12)plot(pred_arima)
This prediction is similar to structural time series. However, we will check further Dynamic Linear Model in below section.
Dynamic linear models are a special case of state space models where the errors of the state and observed components are normally distributed. DLM can be specified by means of two equations
here, Gt and Ft are known matrices and the (vt) & (wt) are two independent white noise sequences (i.e., they are independent, both between them and within each of them), with mean zero and known co-variance matrices Vt and Wt respectively.
The general state space model for a uni-variate time series (Yt, t = 1, 2, . . .) is the so-called random walk plus noise model, defined by:
with arbitrary functions gt and ht which is more flexible. The error sequences (vt) and (wt) are independent. The linear state space models specify gt and ht as linear functions, and Gaussian linear models add the assumptions of Gaussian distributions.
A polynomial DLM (a local level model is a polynomial DLM of order 1) , a local linear trend is a polynomial DLM of order 2). You may find more details of dlm model here.
The arguments dV and dW are used to specify the diagonal of the observation and evolution covariance matrices respectively.
The main purpose of the Kalman filter is to obtain optimal estimates of the state at time point t, only considering the observations {y1, y2, . . . , yt−1}. The key property of the predicted state and its related estimates is therefore that they are only based on the historical values of the series. The objective of filtering is to update our knowledge of the system each time a new observation yt is brought in.
# applying kalman filtermodel_filter <- dlmFilter(df1, modelfit)plot(residuals(model_filter, sd = FALSE), type = “o”, ylab = “Standardized prediction error”)abline(h = 0)
The Kalman smoother allows to compute the densities of θt|DT , starting from t = T−1, in which case θT|DT ~ N(sT = mT , ST = CT ), and then proceeding backward for computing the densities of θt|DT for t = T−2, t = T−3, etc.
forecast$f
Here, we can see from the above plot that, the model has been able capture the trend quite well. Filtered and smoothed lines are moving together in the series and do not differ much from each other. The lines of forecast series for next 12 months has been picked up from where the original series ends
If we compare the three predicted results, we find that, DLM model has been able to capture the trend better than other two.
Similar approach can be applied to analyze and forecast for both uni-variate and multi-variate time-series. Here, the structural time series computes the maximum likelihood estimates of the variance parameters and the filtered means of the state vectors for a basic structural model, i.e., a constant DLM consisting of a random walk plus noise, a local linear trend. we have used the same data-set in all three models to maintain consistency. Interestingly ARIMA & Structural Models are not been able to pick up on the seasonal component like the dlm model. We have not considered the seasonal component in case of dlm modeling. However, the seasonal component can also be added for better prediction.
DLM is quite an interesting package and I would like to further use it for multi-variate analysis in future.
I can be reached here.
Notice: The programs described here are experimental and should be used with caution. All such use at your own risk.
References:
Petris, G., Petrone, S., & Campagnoli, P. (2009). Dynamic linear models. In Dynamic Linear Models with R (pp. 31–84). Springer, New York, NY.Giovanni Petris (2010). An R Package for Dynamic Linear Models. Journal of Statistical Software, 36(12), 1–16.Durbin J, Koopman SJ (2001). Time Series Analysis by State Space Methods. Oxford University Press, Oxford.Harrison PJ, Stevens CF (1976). “Bayesian Forecasting.” Journal of the Royal Statistical Society B, 38, 205–247.
Petris, G., Petrone, S., & Campagnoli, P. (2009). Dynamic linear models. In Dynamic Linear Models with R (pp. 31–84). Springer, New York, NY.
Giovanni Petris (2010). An R Package for Dynamic Linear Models. Journal of Statistical Software, 36(12), 1–16.
Durbin J, Koopman SJ (2001). Time Series Analysis by State Space Methods. Oxford University Press, Oxford.
Harrison PJ, Stevens CF (1976). “Bayesian Forecasting.” Journal of the Royal Statistical Society B, 38, 205–247.
|
[
{
"code": null,
"e": 565,
"s": 171,
"text": "Time series observations are assumed to depend linearly on a state vector that is unobserved and is generated by a stochastic and dynamic process in a state space analysis. The observations are further assumed to be subject to measurement error and independent of the state vector. Therefore, two main components which make up state space models are an observed data and the unobserved states."
},
{
"code": null,
"e": 964,
"s": 565,
"text": "A time-series is described probabilistic by a stochastic process (Yt; t = 1, 2, . . .), that is, by an ordered sequence of random vectors with the index t (time). For simplicity, we will think of equally spaced time points (daily data, monthly data, and so on). The target is to make forecasts about the value of the next observation [yn+1 having observed data up to time n, (y1 = y1, . . . , yn)]."
},
{
"code": null,
"e": 977,
"s": 964,
"text": "barChart(NG)"
},
{
"code": null,
"e": 1366,
"s": 977,
"text": "This series looks clearly non-stationary and in fact quite irregular and volatile. The data is on daily level since 2007 till date. We can see that, price drooped significantly from nearly $20 to close to $1 during 2008/2009, before being going up till around $15 during 2010/2011; however, a highly volatile state since can be seen all across as on date and last price recorded as $8.61."
},
{
"code": null,
"e": 1536,
"s": 1366,
"text": "We can see from this time series that there is certainly some seasonal variation in the price; there is a peak every winter, and a low turning point almost every winter."
},
{
"code": null,
"e": 1789,
"s": 1536,
"text": "Again the it seems like this could be described using an additive model, as the seasonal fluctuations are roughly constant in size over time and do not seem to depend on the level of the time series, and the random fluctuations seem constant over time."
},
{
"code": null,
"e": 2034,
"s": 1789,
"text": "We will do a uni-variate analysis; so, let us extract the monthly “Close” prices from the data-set. Monthly data was taken for computational ease. Depending on available computational power, data can be taken on hourly, daily or weekly as well."
},
{
"code": null,
"e": 2154,
"s": 2034,
"text": "Following data processing are important to convert the data to data-frame and further time -series for future analysis."
},
{
"code": null,
"e": 2236,
"s": 2154,
"text": "Here, our data-set is now processed and we are ready to perform further analysis."
},
{
"code": null,
"e": 2568,
"s": 2236,
"text": "Most statistical models rely on a normal distribution, a distribution that is symmetric and has a characteristic bell shape. Probability distributions are usually (not entirely) represented in charts whose abscissa axis represents the possible values of the variable and whose ordinal axis represents the probability of occurrence."
},
{
"code": null,
"e": 2729,
"s": 2568,
"text": "The distribution plot comprising density and normal Q-Q plot above clearly shows that data distribution is not normal and reflects non-Gaussian characteristics."
},
{
"code": null,
"e": 2815,
"s": 2729,
"text": "Output from the above stationarity tests show non-stationary characteristics of data."
},
{
"code": null,
"e": 3178,
"s": 2815,
"text": "We normalize the data in the stock prediction scenario because of the values of random behavior. Here, min-max normalization is not advised because the stock values are not limited to a certain price range; the prices having brownian motion and can change dramatically. Therefore, advisable to normalize the stock prices with elementary standardization function:"
},
{
"code": null,
"e": 3204,
"s": 3178,
"text": "z = (x — mean(X))/ std(X)"
},
{
"code": null,
"e": 3222,
"s": 3204,
"text": "We see here that:"
},
{
"code": null,
"e": 3292,
"s": 3222,
"text": "the stationary signal has very few lags exceeding the CI of the ACF ."
},
{
"code": null,
"e": 3365,
"s": 3292,
"text": "The trend resulted in almost all lags exceeding the confidence interval."
},
{
"code": null,
"e": 3833,
"s": 3365,
"text": "Therefore, it can be concluded that the ACF signal is stationary. But, the trend signal is not stationary. The stationary series has a better variance around the mean level, and the peaks are evidence of the interventions in the original series. We will further decompose the time series which involves a combination of level, trend, seasonality, and noise components. Decomposition helps to provide a better understanding of problems during analysis and forecasting."
},
{
"code": null,
"e": 4021,
"s": 3833,
"text": "Decomposing a time series means separating it into its constituent components, which are often a trend component and a random component, and if the data is seasonal, a seasonal component."
},
{
"code": null,
"e": 4485,
"s": 4021,
"text": "Non-seasonal time series consist of a trend component and a random component. Decomposing the time series involves tying to separate the time series into these individual components. A seasonal time series, in addition to the trend and random components, also has a seasonal component. Decomposing a seasonal time series means separating the time series into these three components. Let's estimate the trend, seasonal, and random components of the Natural Gas TS."
},
{
"code": null,
"e": 4545,
"s": 4485,
"text": "plot(decompose(df1), yax.flip=TRUE) # Decompose time-series"
},
{
"code": null,
"e": 4849,
"s": 4545,
"text": "The above plot clearly shows that trend is non-stationary which we can see from the trend signal plot in the normalization section. The seasonal component exists for a brief period of time every year most likely during the winter session. Overall, the price is highly volatile with random walk movement."
},
{
"code": null,
"e": 5266,
"s": 4849,
"text": "Unfortunately, there is no universally accepted notation for state space models. However, the most commonly used notations in statistical and econometric applications can be found in the work of Harrison & Stevens (1976) and West & Harrison (1997). The main focus is on Bayesian analysis is maximum likelihood (ML) estimation of unknown parameter. We will start with a local level model to introduce the methodology."
},
{
"code": null,
"e": 5398,
"s": 5266,
"text": "We will develop the prediction with a Base Level Model followed by ARIMA and Dynamic Linear Model to compare the prediction output."
},
{
"code": null,
"e": 5591,
"s": 5398,
"text": "State-space models are based on the idea that the time series (Yt) is an incomplete and noisy function of some underlying un-observable process (θt, t = 1, 2, . . .), called the state process."
},
{
"code": null,
"e": 6012,
"s": 5591,
"text": "A structural approach to time-series analysis is facilitated by the state space framework. In this approach, different unobserved components responsible for the dynamics of the series. These are trend, seasonal, cycle, and the effects of explanatory and intervention variables are identified separately before being put together in a state space model. Let us understand the mathematical intuition for local level model."
},
{
"code": null,
"e": 6205,
"s": 6012,
"text": "A time series is normally considered a set of observation y1,......, yn ordered in time. Here, the base model for representing the time series is additive model. The formula can be written as:"
},
{
"code": null,
"e": 6256,
"s": 6205,
"text": "μt is a slowly varying component called the trend;"
},
{
"code": null,
"e": 6323,
"s": 6256,
"text": "Υt is a periodic component of fixed period and called as seasonal;"
},
{
"code": null,
"e": 6379,
"s": 6323,
"text": "εt is random noise or irregular component called error;"
},
{
"code": null,
"e": 6680,
"s": 6379,
"text": "To develop suitable models and μt and Υt, we need the concept of random walk. We can consider a simple form of model in which μt = αt, where αt is random walk, no seasonal is present and all random variables are normally distributed. We assume that εt has constant variance σ2ε. This gives the model:"
},
{
"code": null,
"e": 7463,
"s": 6680,
"text": "for t = 1,.....,n, where εt’s and ηt’s are mutually independent and independent on α1. There are two parameters, and σ2η. It is an ARIMA(0,1,1) model, but with restrictions on the parameter set. This is called local level model and provides the basis for our analysis. It exhibits the characteristics structure of state space models where there is a series of unobserved values α1,....,αn, which are states and represents the development over time of the system under study together with a set of observations y1,....,yn, which are related to the αt’s by the state space model. This is suitable for both Classical and Bayesian analysis. Where εt’s and ηt’s are not normally distributed we obtain equivalent results from the standpoint of minimum variance linear unbiased estimation."
},
{
"code": null,
"e": 7699,
"s": 7463,
"text": "Initially we assume that, α1 ~ N(α1, P1), where α1 and P1 are known and that σ2ε and σ2η are known. Since, random walk are non-stationary, the model is non-stationary and the distribution of random variables yt and αt depend on time t."
},
{
"code": null,
"e": 7931,
"s": 7699,
"text": "The local linear trend model, type = “trend”, has the same measurement equation, but with a time-varying slope in the dynamics. The basic structural model, type = “BSM”, is a local trend model with an additional seasonal component."
},
{
"code": null,
"e": 8014,
"s": 7931,
"text": "Call:StructTS(x = df1, type = \"level\")Variances: level epsilon 1.26 0.00"
},
{
"code": null,
"e": 8463,
"s": 8014,
"text": "All significance tests in linear Gaussian state space models — and the construction of confidence intervals — are based on assumptions concerning the residuals of the analysis. The residuals should satisfy independence, homoscedasticity, and normality. The independence and normality of the residuals can be diagnosed using the Box-Ljung test statistic. Homoscedasticity can be checked by testing the variance of the standardized prediction errors."
},
{
"code": null,
"e": 8575,
"s": 8463,
"text": "Below plot shows the predicted Close price data for 12 months, together with 50% and 90% probability intervals."
},
{
"code": null,
"e": 8660,
"s": 8575,
"text": "plot(forecast::forecast(fit_level, level = c(50, 90), h = 12), xlim = c(2016, 2021))"
},
{
"code": null,
"e": 8701,
"s": 8660,
"text": "pred <- predict(fit_level, n.ahead = 12)"
},
{
"code": null,
"e": 8791,
"s": 8701,
"text": "Auto-regressive integrated moving average (ARIMA) model can be put into state space form."
},
{
"code": null,
"e": 8878,
"s": 8791,
"text": "In auto arima is able to decide whether to use or not a seasonal arima (SARIMA) model."
},
{
"code": null,
"e": 8938,
"s": 8878,
"text": "auto.arima(df1, trace = T, stepwise = F, approximation = F)"
},
{
"code": null,
"e": 9005,
"s": 8938,
"text": "# Arima arima <- Arima(df1, order = c(0,1,0))checkresiduals(arima)"
},
{
"code": null,
"e": 9173,
"s": 9005,
"text": "We can see from the first and last graphs that, the residuals don’t appear to be white noise. The ACF plot shows no significant correlation exists among the residuals."
},
{
"code": null,
"e": 9258,
"s": 9173,
"text": "# Forecast of 12 monthspred_arima <- forecast::forecast(arima, h=12)plot(pred_arima)"
},
{
"code": null,
"e": 9382,
"s": 9258,
"text": "This prediction is similar to structural time series. However, we will check further Dynamic Linear Model in below section."
},
{
"code": null,
"e": 9572,
"s": 9382,
"text": "Dynamic linear models are a special case of state space models where the errors of the state and observed components are normally distributed. DLM can be specified by means of two equations"
},
{
"code": null,
"e": 9812,
"s": 9572,
"text": "here, Gt and Ft are known matrices and the (vt) & (wt) are two independent white noise sequences (i.e., they are independent, both between them and within each of them), with mean zero and known co-variance matrices Vt and Wt respectively."
},
{
"code": null,
"e": 9953,
"s": 9812,
"text": "The general state space model for a uni-variate time series (Yt, t = 1, 2, . . .) is the so-called random walk plus noise model, defined by:"
},
{
"code": null,
"e": 10206,
"s": 9953,
"text": "with arbitrary functions gt and ht which is more flexible. The error sequences (vt) and (wt) are independent. The linear state space models specify gt and ht as linear functions, and Gaussian linear models add the assumptions of Gaussian distributions."
},
{
"code": null,
"e": 10377,
"s": 10206,
"text": "A polynomial DLM (a local level model is a polynomial DLM of order 1) , a local linear trend is a polynomial DLM of order 2). You may find more details of dlm model here."
},
{
"code": null,
"e": 10501,
"s": 10377,
"text": "The arguments dV and dW are used to specify the diagonal of the observation and evolution covariance matrices respectively."
},
{
"code": null,
"e": 10916,
"s": 10501,
"text": "The main purpose of the Kalman filter is to obtain optimal estimates of the state at time point t, only considering the observations {y1, y2, . . . , yt−1}. The key property of the predicted state and its related estimates is therefore that they are only based on the historical values of the series. The objective of filtering is to update our knowledge of the system each time a new observation yt is brought in."
},
{
"code": null,
"e": 11087,
"s": 10916,
"text": "# applying kalman filtermodel_filter <- dlmFilter(df1, modelfit)plot(residuals(model_filter, sd = FALSE), type = “o”, ylab = “Standardized prediction error”)abline(h = 0)"
},
{
"code": null,
"e": 11311,
"s": 11087,
"text": "The Kalman smoother allows to compute the densities of θt|DT , starting from t = T−1, in which case θT|DT ~ N(sT = mT , ST = CT ), and then proceeding backward for computing the densities of θt|DT for t = T−2, t = T−3, etc."
},
{
"code": null,
"e": 11322,
"s": 11311,
"text": "forecast$f"
},
{
"code": null,
"e": 11624,
"s": 11322,
"text": "Here, we can see from the above plot that, the model has been able capture the trend quite well. Filtered and smoothed lines are moving together in the series and do not differ much from each other. The lines of forecast series for next 12 months has been picked up from where the original series ends"
},
{
"code": null,
"e": 11749,
"s": 11624,
"text": "If we compare the three predicted results, we find that, DLM model has been able to capture the trend better than other two."
},
{
"code": null,
"e": 12451,
"s": 11749,
"text": "Similar approach can be applied to analyze and forecast for both uni-variate and multi-variate time-series. Here, the structural time series computes the maximum likelihood estimates of the variance parameters and the filtered means of the state vectors for a basic structural model, i.e., a constant DLM consisting of a random walk plus noise, a local linear trend. we have used the same data-set in all three models to maintain consistency. Interestingly ARIMA & Structural Models are not been able to pick up on the seasonal component like the dlm model. We have not considered the seasonal component in case of dlm modeling. However, the seasonal component can also be added for better prediction."
},
{
"code": null,
"e": 12560,
"s": 12451,
"text": "DLM is quite an interesting package and I would like to further use it for multi-variate analysis in future."
},
{
"code": null,
"e": 12583,
"s": 12560,
"text": "I can be reached here."
},
{
"code": null,
"e": 12700,
"s": 12583,
"text": "Notice: The programs described here are experimental and should be used with caution. All such use at your own risk."
},
{
"code": null,
"e": 12712,
"s": 12700,
"text": "References:"
},
{
"code": null,
"e": 13182,
"s": 12712,
"text": "Petris, G., Petrone, S., & Campagnoli, P. (2009). Dynamic linear models. In Dynamic Linear Models with R (pp. 31–84). Springer, New York, NY.Giovanni Petris (2010). An R Package for Dynamic Linear Models. Journal of Statistical Software, 36(12), 1–16.Durbin J, Koopman SJ (2001). Time Series Analysis by State Space Methods. Oxford University Press, Oxford.Harrison PJ, Stevens CF (1976). “Bayesian Forecasting.” Journal of the Royal Statistical Society B, 38, 205–247."
},
{
"code": null,
"e": 13324,
"s": 13182,
"text": "Petris, G., Petrone, S., & Campagnoli, P. (2009). Dynamic linear models. In Dynamic Linear Models with R (pp. 31–84). Springer, New York, NY."
},
{
"code": null,
"e": 13435,
"s": 13324,
"text": "Giovanni Petris (2010). An R Package for Dynamic Linear Models. Journal of Statistical Software, 36(12), 1–16."
},
{
"code": null,
"e": 13542,
"s": 13435,
"text": "Durbin J, Koopman SJ (2001). Time Series Analysis by State Space Methods. Oxford University Press, Oxford."
}
] |
React Native - WebView
|
In this chapter, we will learn how to use WebView. It is used when you want to render web page to your mobile app inline.
The HomeContainer will be a container component.
import React, { Component } from 'react'
import WebViewExample from './web_view_example.js'
const App = () => {
return (
<WebViewExample/>
)
}
export default App;
Let us create a new file called WebViewExample.js inside the src/components/home folder.
import React, { Component } from 'react'
import { View, WebView, StyleSheet }
from 'react-native'
const WebViewExample = () => {
return (
<View style = {styles.container}>
<WebView
source = {{ uri:
'https://www.google.com/?gws_rd=cr,ssl&ei=SICcV9_EFqqk6ASA3ZaABA#q=tutorialspoint' }}
/>
</View>
)
}
export default WebViewExample;
const styles = StyleSheet.create({
container: {
height: 350,
}
})
The above program will generate the following output.
20 Lectures
1.5 hours
Anadi Sharma
61 Lectures
6.5 hours
A To Z Mentor
40 Lectures
4.5 hours
Eduonix Learning Solutions
56 Lectures
12.5 hours
Eduonix Learning Solutions
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2466,
"s": 2344,
"text": "In this chapter, we will learn how to use WebView. It is used when you want to render web page to your mobile app inline."
},
{
"code": null,
"e": 2515,
"s": 2466,
"text": "The HomeContainer will be a container component."
},
{
"code": null,
"e": 2691,
"s": 2515,
"text": "import React, { Component } from 'react'\nimport WebViewExample from './web_view_example.js'\n\nconst App = () => {\n return (\n <WebViewExample/>\n )\n}\nexport default App;"
},
{
"code": null,
"e": 2780,
"s": 2691,
"text": "Let us create a new file called WebViewExample.js inside the src/components/home folder."
},
{
"code": null,
"e": 3244,
"s": 2780,
"text": "import React, { Component } from 'react'\nimport { View, WebView, StyleSheet }\n\nfrom 'react-native'\nconst WebViewExample = () => {\n return (\n <View style = {styles.container}>\n <WebView\n source = {{ uri:\n 'https://www.google.com/?gws_rd=cr,ssl&ei=SICcV9_EFqqk6ASA3ZaABA#q=tutorialspoint' }}\n />\n </View>\n )\n}\nexport default WebViewExample;\n\nconst styles = StyleSheet.create({\n container: {\n height: 350,\n }\n})"
},
{
"code": null,
"e": 3298,
"s": 3244,
"text": "The above program will generate the following output."
},
{
"code": null,
"e": 3333,
"s": 3298,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3347,
"s": 3333,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3382,
"s": 3347,
"text": "\n 61 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3397,
"s": 3382,
"text": " A To Z Mentor"
},
{
"code": null,
"e": 3432,
"s": 3397,
"text": "\n 40 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3460,
"s": 3432,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3496,
"s": 3460,
"text": "\n 56 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3524,
"s": 3496,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3559,
"s": 3524,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3571,
"s": 3559,
"text": " Senol Atac"
},
{
"code": null,
"e": 3606,
"s": 3571,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3618,
"s": 3606,
"text": " Senol Atac"
},
{
"code": null,
"e": 3625,
"s": 3618,
"text": " Print"
},
{
"code": null,
"e": 3636,
"s": 3625,
"text": " Add Notes"
}
] |
Function call by reference in C
|
The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.
To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.
/* function definition to swap the values */
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us now call the function swap() by passing values by reference as in the following example −
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value of x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us put the above code in a single C file, compile and execute it, to produce the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
It shows that the change has reflected outside the function as well, unlike call by value where the changes do not reflect outside the function.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2369,
"s": 2084,
"text": "The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument."
},
{
"code": null,
"e": 2673,
"s": 2369,
"text": "To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments."
},
{
"code": null,
"e": 2903,
"s": 2673,
"text": "/* function definition to swap the values */\nvoid swap(int *x, int *y) {\n\n int temp;\n temp = *x; /* save the value at address x */\n *x = *y; /* put y into x */\n *y = temp; /* put temp into y */\n \n return;\n}\n"
},
{
"code": null,
"e": 3000,
"s": 2903,
"text": "Let us now call the function swap() by passing values by reference as in the following example −"
},
{
"code": null,
"e": 3552,
"s": 3000,
"text": "#include <stdio.h>\n\nint main () {\n\n /* local variable definition */\n int a = 100;\n int b = 200;\n \n printf(\"Before swap, value of a : %d\\n\", a );\n printf(\"Before swap, value of b : %d\\n\", b );\n \n /* calling a function to swap the values */\n swap(&a, &b);\n \n printf(\"After swap, value of a : %d\\n\", a );\n printf(\"After swap, value of b : %d\\n\", b );\n \n return 0;\n}\nvoid swap(int *x, int *y) {\n\n int temp;\n\n temp = *x; /* save the value of x */\n *x = *y; /* put y into x */\n *y = temp; /* put temp into y */\n \n return;\n}"
},
{
"code": null,
"e": 3656,
"s": 3552,
"text": "Let us put the above code in a single C file, compile and execute it, to produce the following result −"
},
{
"code": null,
"e": 3775,
"s": 3656,
"text": "Before swap, value of a : 100\nBefore swap, value of b : 200\nAfter swap, value of a : 200\nAfter swap, value of b : 100\n"
},
{
"code": null,
"e": 3920,
"s": 3775,
"text": "It shows that the change has reflected outside the function as well, unlike call by value where the changes do not reflect outside the function."
},
{
"code": null,
"e": 3927,
"s": 3920,
"text": " Print"
},
{
"code": null,
"e": 3938,
"s": 3927,
"text": " Add Notes"
}
] |
Angular Material 7 - Tree
|
The <mat-tree>, an Angular Directive, is used to create a tree with material styling to display hierachical data.
In this chapter, we will showcase the configuration required to draw a tree using Angular Material.
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatTreeModule, MatIconModule, MatButtonModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatTreeModule, MatIconModule, MatButtonModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<mat-tree [dataSource] = "dataSource" [treeControl] = "treeControl">
<mat-tree-node *matTreeNodeDef = "let node" matTreeNodeToggle matTreeNodePadding>
<button mat-icon-button disabled></button>
{{node.filename}} : {{node.type}}
</mat-tree-node>
<mat-tree-node *matTreeNodeDef = "let node;when: hasChild" matTreeNodePadding>
<button mat-icon-button matTreeNodeToggle [attr.aria-label] = "'toggle ' + node.filename">
<mat-icon class = "mat-icon-rtl-mirror">
{{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.filename}}
</mat-tree-node>
</mat-tree>
Following is the content of the modified ts file app.component.ts.
import {FlatTreeControl} from '@angular/cdk/tree';
import {Component, Injectable} from '@angular/core';
import {MatTreeFlatDataSource, MatTreeFlattener} from '@angular/material/tree';
import {BehaviorSubject, Observable, of as observableOf} from 'rxjs';
export class FileNode {
children: FileNode[];
filename: string;
type: any;
}
export class FileFlatNode {
constructor(
public expandable: boolean, public filename: string, public level: number, public type: any) {}
}
const TREE_DATA = JSON.stringify({
Documents: {
angular: {
src: {
compiler: 'ts',
core: 'ts'
}
},
material2: {
src: {
button: 'ts',
checkbox: 'ts',
input: 'ts'
}
}
}
});
@Injectable()
export class FileDatabase {
dataChange = new BehaviorSubject<FileNode[]>([]);
get data(): FileNode[] { return this.dataChange.value; }
constructor() {
this.initialize();
}
initialize() {
const dataObject = JSON.parse(TREE_DATA);
const data = this.buildFileTree(dataObject, 0);
this.dataChange.next(data);
}
buildFileTree(obj: {[key: string]: any}, level: number): FileNode[] {
return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
const value = obj[key];
const node = new FileNode();
node.filename = key;
if (value != null) {
if (typeof value === 'object') {
node.children = this.buildFileTree(value, level + 1);
} else {
node.type = value;
}
}
return accumulator.concat(node);
}, []);
}
}
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
providers: [FileDatabase]
})
export class AppComponent {
treeControl: FlatTreeControl<FileFlatNode>;
treeFlattener: MatTreeFlattener<FileNode, FileFlatNode>;
dataSource: MatTreeFlatDataSource<FileNode, FileFlatNode>;
constructor(database: FileDatabase) {
this.treeFlattener = new MatTreeFlattener(this.transformer, this._getLevel,
this._isExpandable, this._getChildren);
this.treeControl = new FlatTreeControl<FileFlatNode>(this._getLevel, this._isExpandable);
this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
database.dataChange.subscribe(data => this.dataSource.data = data);
}
transformer = (node: FileNode, level: number) => {
return new FileFlatNode(!!node.children, node.filename, level, node.type);
}
private _getLevel = (node: FileFlatNode) => node.level;
private _isExpandable = (node: FileFlatNode) => node.expandable;
private _getChildren = (node: FileNode): Observable<FileNode[]> => observableOf(node.children);
hasChild = (_: number, _nodeData: FileFlatNode) => _nodeData.expandable;
}
Verify the result.
As first, we've created tree using mat-tree and mat-tree-node.
Then, we've created the data source in ts file and bind it with mat-tree.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2869,
"s": 2755,
"text": "The <mat-tree>, an Angular Directive, is used to create a tree with material styling to display hierachical data."
},
{
"code": null,
"e": 2969,
"s": 2869,
"text": "In this chapter, we will showcase the configuration required to draw a tree using Angular Material."
},
{
"code": null,
"e": 3043,
"s": 2969,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3718,
"s": 3043,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatTreeModule, MatIconModule, MatButtonModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatTreeModule, MatIconModule, MatButtonModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3794,
"s": 3718,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 4458,
"s": 3794,
"text": "<mat-tree [dataSource] = \"dataSource\" [treeControl] = \"treeControl\">\n <mat-tree-node *matTreeNodeDef = \"let node\" matTreeNodeToggle matTreeNodePadding>\n <button mat-icon-button disabled></button>\n {{node.filename}} : {{node.type}}\n </mat-tree-node>\n <mat-tree-node *matTreeNodeDef = \"let node;when: hasChild\" matTreeNodePadding>\n <button mat-icon-button matTreeNodeToggle [attr.aria-label] = \"'toggle ' + node.filename\">\n <mat-icon class = \"mat-icon-rtl-mirror\">\n {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}\n </mat-icon>\n </button>\n {{node.filename}}\n </mat-tree-node>\n</mat-tree>"
},
{
"code": null,
"e": 4525,
"s": 4458,
"text": "Following is the content of the modified ts file app.component.ts."
},
{
"code": null,
"e": 7429,
"s": 4525,
"text": "import {FlatTreeControl} from '@angular/cdk/tree';\nimport {Component, Injectable} from '@angular/core';\nimport {MatTreeFlatDataSource, MatTreeFlattener} from '@angular/material/tree';\nimport {BehaviorSubject, Observable, of as observableOf} from 'rxjs';\nexport class FileNode {\n children: FileNode[];\n filename: string;\n type: any;\n}\nexport class FileFlatNode {\n constructor(\n public expandable: boolean, public filename: string, public level: number, public type: any) {}\n}\nconst TREE_DATA = JSON.stringify({\n Documents: {\n angular: {\n src: {\n compiler: 'ts',\n core: 'ts'\n }\n },\n material2: {\n src: {\n button: 'ts',\n checkbox: 'ts',\n input: 'ts'\n }\n }\n }\n});\n@Injectable()\nexport class FileDatabase {\n dataChange = new BehaviorSubject<FileNode[]>([]);\n get data(): FileNode[] { return this.dataChange.value; }\n constructor() {\n this.initialize();\n }\n initialize() {\n const dataObject = JSON.parse(TREE_DATA); \n const data = this.buildFileTree(dataObject, 0);\n this.dataChange.next(data);\n } \n buildFileTree(obj: {[key: string]: any}, level: number): FileNode[] {\n return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {\n const value = obj[key];\n const node = new FileNode();\n node.filename = key;\n if (value != null) {\n if (typeof value === 'object') {\n node.children = this.buildFileTree(value, level + 1);\n } else {\n node.type = value;\n }\n }\n return accumulator.concat(node);\n }, []);\n }\n}\n@Component({\n selector: 'app-root',\n templateUrl: 'app.component.html',\n styleUrls: ['app.component.css'],\n providers: [FileDatabase]\n})\nexport class AppComponent {\n treeControl: FlatTreeControl<FileFlatNode>;\n treeFlattener: MatTreeFlattener<FileNode, FileFlatNode>;\n dataSource: MatTreeFlatDataSource<FileNode, FileFlatNode>;\n constructor(database: FileDatabase) {\n this.treeFlattener = new MatTreeFlattener(this.transformer, this._getLevel,\n this._isExpandable, this._getChildren);\n this.treeControl = new FlatTreeControl<FileFlatNode>(this._getLevel, this._isExpandable);\n this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);\n database.dataChange.subscribe(data => this.dataSource.data = data);\n }\n transformer = (node: FileNode, level: number) => {\n return new FileFlatNode(!!node.children, node.filename, level, node.type);\n }\n private _getLevel = (node: FileFlatNode) => node.level;\n private _isExpandable = (node: FileFlatNode) => node.expandable;\n private _getChildren = (node: FileNode): Observable<FileNode[]> => observableOf(node.children);\n hasChild = (_: number, _nodeData: FileFlatNode) => _nodeData.expandable;\n}"
},
{
"code": null,
"e": 7448,
"s": 7429,
"text": "Verify the result."
},
{
"code": null,
"e": 7511,
"s": 7448,
"text": "As first, we've created tree using mat-tree and mat-tree-node."
},
{
"code": null,
"e": 7585,
"s": 7511,
"text": "Then, we've created the data source in ts file and bind it with mat-tree."
},
{
"code": null,
"e": 7620,
"s": 7585,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7634,
"s": 7620,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7669,
"s": 7634,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7683,
"s": 7669,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7718,
"s": 7683,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7738,
"s": 7718,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7773,
"s": 7738,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7790,
"s": 7773,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7823,
"s": 7790,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7835,
"s": 7823,
"text": " Senol Atac"
},
{
"code": null,
"e": 7870,
"s": 7835,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7882,
"s": 7870,
"text": " Senol Atac"
},
{
"code": null,
"e": 7889,
"s": 7882,
"text": " Print"
},
{
"code": null,
"e": 7900,
"s": 7889,
"text": " Add Notes"
}
] |
How to Annotate and Improve Datasets with CVAT and FiftyOne | Towards Data Science
|
Everyone wants to train great models. The machine learning community has had a model-centric focus for quite a while with everyone trying to create the next best model. Recently, the importance of switching gears to data-centric workflows has become more and more prominent through ideas like Software 2.0. When training a model for your task, you will likely find that the biggest improvements to your model will come from carefully curating and improving the datasets you use to train your models rather than worrying about the specific model architecture you are using.
In the dataset curation and annotation space, FiftyOne and CVAT are two leading open-source tools tackling different parts of the dataset curation and improvement workflows each with tens of thousands of users. Moreover, these tools are now tightly integrated, allowing for faster and more efficient workflows. FiftyOne is a dataset curation and model analysis tool providing a flexible API and intuitive App serving as the open-source “IDE for your datasets.” CVAT is one of the leading open-source annotation tools for images and videos that has been widely adopted due to its broad feature set and easy-to-use interface. The integration between FiftyOne and CVAT allows you to curate and explore datasets in FiftyOne and then send off samples or existing labels for annotation in CVAT with just one line of code.
This post covers two example workflows showing how to use the integration between FiftyOne and CVAT. The first workflow intelligently selects a subset of unlabeled data and sends it to CVAT for annotation. The second workflow evaluates an existing dataset to find annotation mistakes and uses CVAT to improve the quality of the dataset. Both of these examples show how easy it is to work with FiftyOne and CVAT together for annotation workflows, leading to fine-tuned computer vision datasets that are needed to develop better models, faster.
Disclaimer: I am an engineer at Voxel51 working on FiftyOne!
The examples shown in the post can be run directly in your browser through Google Colab. Click this link to check it out!
In order to follow along with the examples in this post, you need to set up FiftyOne and CVAT.
For FiftyOne, you just need to install the open-source Python package:
pip install fiftyone
For CVAT, you need to make an account on cvat.org (or set up CVAT locally). The primary benefits of setting up CVAT locally is to avoid the 10 tasks and 500 Mb limits of cvat.org.
When running the example in this post, FiftyOne will need to connect to your CVAT account. The easiest way to pass your CVAT username and password to FfityOne is to store them in environment variables.
export FIFTYONE_CVAT_USERNAME=<YOUR_USERNAME>export FIFTYONE_CVAT_PASSWORD=<YOUR_PASSWORD>
If you do not want to use these environment variables, check out the alternate ways to provide your CVAT username and password to FiftyOne.
This post also runs some deep models that require TensorFlow:
pip install tensorflow
Check out this post if you have a GPU and/or want to set up Tensorflow or PyTorch with Conda instead.
The basic workflow for using this integration between FiftyOne and CVAT on your own data includes loading your data (and possibly existing labels) into FiftyOne, exploring your dataset to find subsets that need to be reviewed or annotated, uploading those subsets to CVAT, annotating them in CVAT, and loading the updated labels back into FiftyOne.
For most machine learning projects, the first step is to collect a dataset needed for a specific task. For computer vision projects specifically, this will generally result in thousands of images or videos that have been gathered from internet sources like Flickr or captured by new footage from a data acquisition team.
With collections containing thousands or millions of samples, the cost to annotate every single sample can be astronomical. It thus makes sense to ensure that only the most useful and relevant data is being sent to annotation. One measure for how “useful” data is in training a model is how unique the example is with respect to the rest of the dataset. Multiple similar examples will not provide the model with as much new information to learn as visually unique examples.
FiftyOne provides a set of methods to calculate dataset properties like sample hardness, label mistakenness, and, most importantly for this workflow, visual similarity/uniqueness.
We begin by loading a set of unlabeled images into FiftyOne. This can be done in just one line of code. For example, if you are using your own data you can run the following:
However, in this blog, we'll download some images from the Open Images V6 dataset using the built-in FiftyOne Dataset Zoo.
Either way, let’s make the dataset persistent so that we can close out of the Python session and load the dataset back in if we need to.
Now that the data is loaded, let’s visualize it in the FiftyOne App.
Let’s run the compute_similarity() method on the dataset in order to index all samples in the dataset by their visual similarity to all other samples in the dataset. Once this is done, we can then use the index to find the most unique samples based on visual similarity. There are other measures of uniqueness but we focus on this similarity-based measure in this blog.
We can also visualize the exact samples that were selected. By default, this visualization is computed with the dimensionality reduction package umap-learn:
pip install umap-learn
Now let’s create a view into the dataset containing only the unique samples that were selected and visualize them.
Having reduced the number of samples that need to be annotated, the time and cost of annotating this dataset have also been reduced.
Whether you are annotating the data yourself or have a team of annotators, the workflow of uploading data from FiftyOne to CVAT is nearly the same. The annotate() method on a collection of samples lets you specify the name, type, and classes for the labels you are annotating.
For example, if we are annotating segmentation masks for the classes “person,” “vehicle,” and “animal” we can run the following. Assuming you want to annotate these samples yourself, you can automatically launch a browser window with the CVAT editor once the data has been loaded. For this example post, let's only load a few of the samples in our view.
The results object can be used to get the current status of the tasks that were created.
Status for label field 'segmentations': Task 386 (FiftyOne_example_dataset_segmentations): Status: annotation Assignee: None Last updated: 2021-08-20T21:22:37.928988Z URL: http://cvat.org/tasks/386 Job 441: Status: annotation Assignee: None Reviewer: None
Once the annotation is complete and saved in CVAT, we can download the annotations and automatically update our dataset.
If you want to upload the dataset to a team of annotators, you can provide the CVAT usernames of the annotators and reviewers that will be assigned round-robin style. The segment_size parameter is used to define the maximum number of images in each job in your CVAT task.
For larger datasets, the annotation process may take some time. The anno_key that we provided stores the relevant information about this annotation run on the dataset itself. When the annotations are ready to be imported back into FiftyOne, we can easily do so:
In many projects, a dataset already exists and is being used to train models. In such cases, the best use of time is likely to improve the quality of the dataset, which often provides greater performance gains than a similar effort into optimizing the model architecture.
FiftyOne provides a powerful API and App workflows to identify the samples/annotations that need to be updated, and the tight integration with CVAT allows you to take the necessary actions to improve your dataset’s quality.
For this example workflow, let’s load the COCO object detection dataset from the FiftyOne Dataset Zoo.
In this case, we’ll use a model from the FiftyOne Model Zoo, but you can easily add your own model predictions to your dataset as well. To run this specific model, we also need to install the TensorFlow Model Garden with:
eta install models
Note: It is recommended to run this on a machine with a GPU!
Let’s visualize these model predictions.
In order to find specific cases of how this model performed, let’s evaluate the model:
0.3957238101325776
Using FiftyOne’s sophisticated query language, we can construct different views into the dataset. Specifically, let’s find the samples where the model was confident in its prediction but the prediction was labeled incorrect (false positive). This indicates that the model may have been correct but the ground truth annotation was incorrect.
Browsing through some of these results, we can see a pattern emerge. The COCO dataset contains a iscrowd boolean attribute on labels that indicates if the bounding boxes contain a crowd of multiple objects or just a single instance of the object. In many of the situations where the model was incorrect, the iscrowd attribute is incorrectly annotated or missing entirely.
We can tag some of these samples for annotation by clicking selecting the relevant samples and clicking the tag button.
We can now use the annotate() method to upload these samples and labels to CVAT for reannotation. The following code creates a new task in your account on cvat.org containing only the samples with the requires_annotation tag:
After updating the relevant annotations in all of the samples, make sure to hit the save button in CVAT. Now that the reannotation is complete, let’s load the updated labels back into FiftyOne and clean up the tasks that were created in CVAT.
As we can see, the ground_truth labels on the dataset have been updated. Let's evaluate the same model again on these updated labels.
0.3984999388520894
The mAP of the model has improved from 39.57% to 39.85% just by updating a single label in one sample! The next step is to spend more time exploring the dataset in FiftyOne finding more annotation mistakes and sending them to a team of annotators in CVAT for review and re-annotation. Specific users can be assigned to annotate or review the tasks that are created through this API.
This workflow has shown how to improve the validation split of a dataset and the subsequent performance of a model on that split. We never actually retrained the model at this point! The next step is to iterate this workflow over the entire dataset one split at a time until it is refined in its entirety. Then, when it’s time to train the model, other workflows demonstrating integrations with PyTorch dataloaders or PyTorch Lightning Flash are a great place to start.
Building a high-quality dataset is the most surefire way to produce high-performing models. Open-source tools for building and improving datasets are what allow the computer vision community as a whole to develop better models. FiftyOne and CVAT are two open-source tools that are now tightly integrated that you can use to curate and annotate datasets from scratch, as well as explore and re-annotate existing datasets to improve them.
Headquartered in Ann Arbor, Michigan, and founded in 2016 by University of Michigan professor Dr. Jason Corso and Dr. Brian Moore, Voxel51 is an AI software company that is democratizing access to software 2.0 by providing the open core software building blocks that enable computer vision and machine learning engineers to rapidly engineer data-powered workflows.
Learn more at fiftyone.ai!
|
[
{
"code": null,
"e": 745,
"s": 172,
"text": "Everyone wants to train great models. The machine learning community has had a model-centric focus for quite a while with everyone trying to create the next best model. Recently, the importance of switching gears to data-centric workflows has become more and more prominent through ideas like Software 2.0. When training a model for your task, you will likely find that the biggest improvements to your model will come from carefully curating and improving the datasets you use to train your models rather than worrying about the specific model architecture you are using."
},
{
"code": null,
"e": 1561,
"s": 745,
"text": "In the dataset curation and annotation space, FiftyOne and CVAT are two leading open-source tools tackling different parts of the dataset curation and improvement workflows each with tens of thousands of users. Moreover, these tools are now tightly integrated, allowing for faster and more efficient workflows. FiftyOne is a dataset curation and model analysis tool providing a flexible API and intuitive App serving as the open-source “IDE for your datasets.” CVAT is one of the leading open-source annotation tools for images and videos that has been widely adopted due to its broad feature set and easy-to-use interface. The integration between FiftyOne and CVAT allows you to curate and explore datasets in FiftyOne and then send off samples or existing labels for annotation in CVAT with just one line of code."
},
{
"code": null,
"e": 2104,
"s": 1561,
"text": "This post covers two example workflows showing how to use the integration between FiftyOne and CVAT. The first workflow intelligently selects a subset of unlabeled data and sends it to CVAT for annotation. The second workflow evaluates an existing dataset to find annotation mistakes and uses CVAT to improve the quality of the dataset. Both of these examples show how easy it is to work with FiftyOne and CVAT together for annotation workflows, leading to fine-tuned computer vision datasets that are needed to develop better models, faster."
},
{
"code": null,
"e": 2165,
"s": 2104,
"text": "Disclaimer: I am an engineer at Voxel51 working on FiftyOne!"
},
{
"code": null,
"e": 2287,
"s": 2165,
"text": "The examples shown in the post can be run directly in your browser through Google Colab. Click this link to check it out!"
},
{
"code": null,
"e": 2382,
"s": 2287,
"text": "In order to follow along with the examples in this post, you need to set up FiftyOne and CVAT."
},
{
"code": null,
"e": 2453,
"s": 2382,
"text": "For FiftyOne, you just need to install the open-source Python package:"
},
{
"code": null,
"e": 2474,
"s": 2453,
"text": "pip install fiftyone"
},
{
"code": null,
"e": 2654,
"s": 2474,
"text": "For CVAT, you need to make an account on cvat.org (or set up CVAT locally). The primary benefits of setting up CVAT locally is to avoid the 10 tasks and 500 Mb limits of cvat.org."
},
{
"code": null,
"e": 2856,
"s": 2654,
"text": "When running the example in this post, FiftyOne will need to connect to your CVAT account. The easiest way to pass your CVAT username and password to FfityOne is to store them in environment variables."
},
{
"code": null,
"e": 2947,
"s": 2856,
"text": "export FIFTYONE_CVAT_USERNAME=<YOUR_USERNAME>export FIFTYONE_CVAT_PASSWORD=<YOUR_PASSWORD>"
},
{
"code": null,
"e": 3087,
"s": 2947,
"text": "If you do not want to use these environment variables, check out the alternate ways to provide your CVAT username and password to FiftyOne."
},
{
"code": null,
"e": 3149,
"s": 3087,
"text": "This post also runs some deep models that require TensorFlow:"
},
{
"code": null,
"e": 3172,
"s": 3149,
"text": "pip install tensorflow"
},
{
"code": null,
"e": 3274,
"s": 3172,
"text": "Check out this post if you have a GPU and/or want to set up Tensorflow or PyTorch with Conda instead."
},
{
"code": null,
"e": 3623,
"s": 3274,
"text": "The basic workflow for using this integration between FiftyOne and CVAT on your own data includes loading your data (and possibly existing labels) into FiftyOne, exploring your dataset to find subsets that need to be reviewed or annotated, uploading those subsets to CVAT, annotating them in CVAT, and loading the updated labels back into FiftyOne."
},
{
"code": null,
"e": 3944,
"s": 3623,
"text": "For most machine learning projects, the first step is to collect a dataset needed for a specific task. For computer vision projects specifically, this will generally result in thousands of images or videos that have been gathered from internet sources like Flickr or captured by new footage from a data acquisition team."
},
{
"code": null,
"e": 4418,
"s": 3944,
"text": "With collections containing thousands or millions of samples, the cost to annotate every single sample can be astronomical. It thus makes sense to ensure that only the most useful and relevant data is being sent to annotation. One measure for how “useful” data is in training a model is how unique the example is with respect to the rest of the dataset. Multiple similar examples will not provide the model with as much new information to learn as visually unique examples."
},
{
"code": null,
"e": 4598,
"s": 4418,
"text": "FiftyOne provides a set of methods to calculate dataset properties like sample hardness, label mistakenness, and, most importantly for this workflow, visual similarity/uniqueness."
},
{
"code": null,
"e": 4773,
"s": 4598,
"text": "We begin by loading a set of unlabeled images into FiftyOne. This can be done in just one line of code. For example, if you are using your own data you can run the following:"
},
{
"code": null,
"e": 4896,
"s": 4773,
"text": "However, in this blog, we'll download some images from the Open Images V6 dataset using the built-in FiftyOne Dataset Zoo."
},
{
"code": null,
"e": 5033,
"s": 4896,
"text": "Either way, let’s make the dataset persistent so that we can close out of the Python session and load the dataset back in if we need to."
},
{
"code": null,
"e": 5102,
"s": 5033,
"text": "Now that the data is loaded, let’s visualize it in the FiftyOne App."
},
{
"code": null,
"e": 5472,
"s": 5102,
"text": "Let’s run the compute_similarity() method on the dataset in order to index all samples in the dataset by their visual similarity to all other samples in the dataset. Once this is done, we can then use the index to find the most unique samples based on visual similarity. There are other measures of uniqueness but we focus on this similarity-based measure in this blog."
},
{
"code": null,
"e": 5629,
"s": 5472,
"text": "We can also visualize the exact samples that were selected. By default, this visualization is computed with the dimensionality reduction package umap-learn:"
},
{
"code": null,
"e": 5652,
"s": 5629,
"text": "pip install umap-learn"
},
{
"code": null,
"e": 5767,
"s": 5652,
"text": "Now let’s create a view into the dataset containing only the unique samples that were selected and visualize them."
},
{
"code": null,
"e": 5900,
"s": 5767,
"text": "Having reduced the number of samples that need to be annotated, the time and cost of annotating this dataset have also been reduced."
},
{
"code": null,
"e": 6177,
"s": 5900,
"text": "Whether you are annotating the data yourself or have a team of annotators, the workflow of uploading data from FiftyOne to CVAT is nearly the same. The annotate() method on a collection of samples lets you specify the name, type, and classes for the labels you are annotating."
},
{
"code": null,
"e": 6531,
"s": 6177,
"text": "For example, if we are annotating segmentation masks for the classes “person,” “vehicle,” and “animal” we can run the following. Assuming you want to annotate these samples yourself, you can automatically launch a browser window with the CVAT editor once the data has been loaded. For this example post, let's only load a few of the samples in our view."
},
{
"code": null,
"e": 6620,
"s": 6531,
"text": "The results object can be used to get the current status of the tasks that were created."
},
{
"code": null,
"e": 6887,
"s": 6620,
"text": "Status for label field 'segmentations':\tTask 386 (FiftyOne_example_dataset_segmentations):\t\tStatus: annotation\t\tAssignee: None\t\tLast updated: 2021-08-20T21:22:37.928988Z\t\tURL: http://cvat.org/tasks/386\t\tJob 441:\t\t\tStatus: annotation\t\t\tAssignee: None\t\t\tReviewer: None"
},
{
"code": null,
"e": 7008,
"s": 6887,
"text": "Once the annotation is complete and saved in CVAT, we can download the annotations and automatically update our dataset."
},
{
"code": null,
"e": 7280,
"s": 7008,
"text": "If you want to upload the dataset to a team of annotators, you can provide the CVAT usernames of the annotators and reviewers that will be assigned round-robin style. The segment_size parameter is used to define the maximum number of images in each job in your CVAT task."
},
{
"code": null,
"e": 7542,
"s": 7280,
"text": "For larger datasets, the annotation process may take some time. The anno_key that we provided stores the relevant information about this annotation run on the dataset itself. When the annotations are ready to be imported back into FiftyOne, we can easily do so:"
},
{
"code": null,
"e": 7814,
"s": 7542,
"text": "In many projects, a dataset already exists and is being used to train models. In such cases, the best use of time is likely to improve the quality of the dataset, which often provides greater performance gains than a similar effort into optimizing the model architecture."
},
{
"code": null,
"e": 8038,
"s": 7814,
"text": "FiftyOne provides a powerful API and App workflows to identify the samples/annotations that need to be updated, and the tight integration with CVAT allows you to take the necessary actions to improve your dataset’s quality."
},
{
"code": null,
"e": 8141,
"s": 8038,
"text": "For this example workflow, let’s load the COCO object detection dataset from the FiftyOne Dataset Zoo."
},
{
"code": null,
"e": 8363,
"s": 8141,
"text": "In this case, we’ll use a model from the FiftyOne Model Zoo, but you can easily add your own model predictions to your dataset as well. To run this specific model, we also need to install the TensorFlow Model Garden with:"
},
{
"code": null,
"e": 8382,
"s": 8363,
"text": "eta install models"
},
{
"code": null,
"e": 8443,
"s": 8382,
"text": "Note: It is recommended to run this on a machine with a GPU!"
},
{
"code": null,
"e": 8484,
"s": 8443,
"text": "Let’s visualize these model predictions."
},
{
"code": null,
"e": 8571,
"s": 8484,
"text": "In order to find specific cases of how this model performed, let’s evaluate the model:"
},
{
"code": null,
"e": 8590,
"s": 8571,
"text": "0.3957238101325776"
},
{
"code": null,
"e": 8931,
"s": 8590,
"text": "Using FiftyOne’s sophisticated query language, we can construct different views into the dataset. Specifically, let’s find the samples where the model was confident in its prediction but the prediction was labeled incorrect (false positive). This indicates that the model may have been correct but the ground truth annotation was incorrect."
},
{
"code": null,
"e": 9303,
"s": 8931,
"text": "Browsing through some of these results, we can see a pattern emerge. The COCO dataset contains a iscrowd boolean attribute on labels that indicates if the bounding boxes contain a crowd of multiple objects or just a single instance of the object. In many of the situations where the model was incorrect, the iscrowd attribute is incorrectly annotated or missing entirely."
},
{
"code": null,
"e": 9423,
"s": 9303,
"text": "We can tag some of these samples for annotation by clicking selecting the relevant samples and clicking the tag button."
},
{
"code": null,
"e": 9649,
"s": 9423,
"text": "We can now use the annotate() method to upload these samples and labels to CVAT for reannotation. The following code creates a new task in your account on cvat.org containing only the samples with the requires_annotation tag:"
},
{
"code": null,
"e": 9892,
"s": 9649,
"text": "After updating the relevant annotations in all of the samples, make sure to hit the save button in CVAT. Now that the reannotation is complete, let’s load the updated labels back into FiftyOne and clean up the tasks that were created in CVAT."
},
{
"code": null,
"e": 10026,
"s": 9892,
"text": "As we can see, the ground_truth labels on the dataset have been updated. Let's evaluate the same model again on these updated labels."
},
{
"code": null,
"e": 10045,
"s": 10026,
"text": "0.3984999388520894"
},
{
"code": null,
"e": 10428,
"s": 10045,
"text": "The mAP of the model has improved from 39.57% to 39.85% just by updating a single label in one sample! The next step is to spend more time exploring the dataset in FiftyOne finding more annotation mistakes and sending them to a team of annotators in CVAT for review and re-annotation. Specific users can be assigned to annotate or review the tasks that are created through this API."
},
{
"code": null,
"e": 10898,
"s": 10428,
"text": "This workflow has shown how to improve the validation split of a dataset and the subsequent performance of a model on that split. We never actually retrained the model at this point! The next step is to iterate this workflow over the entire dataset one split at a time until it is refined in its entirety. Then, when it’s time to train the model, other workflows demonstrating integrations with PyTorch dataloaders or PyTorch Lightning Flash are a great place to start."
},
{
"code": null,
"e": 11335,
"s": 10898,
"text": "Building a high-quality dataset is the most surefire way to produce high-performing models. Open-source tools for building and improving datasets are what allow the computer vision community as a whole to develop better models. FiftyOne and CVAT are two open-source tools that are now tightly integrated that you can use to curate and annotate datasets from scratch, as well as explore and re-annotate existing datasets to improve them."
},
{
"code": null,
"e": 11700,
"s": 11335,
"text": "Headquartered in Ann Arbor, Michigan, and founded in 2016 by University of Michigan professor Dr. Jason Corso and Dr. Brian Moore, Voxel51 is an AI software company that is democratizing access to software 2.0 by providing the open core software building blocks that enable computer vision and machine learning engineers to rapidly engineer data-powered workflows."
}
] |
Python Pandas - Create a Subset DataFrame using Indexing Operator
|
The indexing operator is the square brackets for creating a subset dataframe. Let us first create a Pandas DataFrame. We have 3 columns in the DataFrame
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
Creating a subset with a single column
dataFrame[['Product']]
Creating a subset with multiple columns
dataFrame[['Opening_Stock','Closing_Stock']]
Following is the complete code
import pandas as pd
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
print"DataFrame...\n",dataFrame
print"\nDisplaying a subset using indexing operator:\n",dataFrame[['Product']]
print"\nDisplaying a subset with multiple columns:\n",dataFrame[['Opening_Stock','Closing_Stock']]
This will produce the following output
DataFrame...
Closing_Stock Opening_Stock Product
0 200 300 SmartTV
1 500 700 ChromeCast
2 1000 1200 Speaker
3 900 1500 Earphone
Displaying a subset using indexing operator:
Product
0 SmartTV
1 ChromeCast
2 Speaker
3 Earphone
Displaying a subset with multiple columns:
Opening_Stock Closing_Stock
0 300 200
1 700 500
2 1200 1000
3 1500 900
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "The indexing operator is the square brackets for creating a subset dataframe. Let us first create a Pandas DataFrame. We have 3 columns in the DataFrame"
},
{
"code": null,
"e": 1382,
"s": 1215,
"text": "dataFrame = pd.DataFrame({\"Product\": [\"SmartTV\", \"ChromeCast\", \"Speaker\", \"Earphone\"],\"Opening_Stock\": [300, 700, 1200, 1500],\"Closing_Stock\": [200, 500, 1000, 900]})"
},
{
"code": null,
"e": 1421,
"s": 1382,
"text": "Creating a subset with a single column"
},
{
"code": null,
"e": 1444,
"s": 1421,
"text": "dataFrame[['Product']]"
},
{
"code": null,
"e": 1484,
"s": 1444,
"text": "Creating a subset with multiple columns"
},
{
"code": null,
"e": 1529,
"s": 1484,
"text": "dataFrame[['Opening_Stock','Closing_Stock']]"
},
{
"code": null,
"e": 1560,
"s": 1529,
"text": "Following is the complete code"
},
{
"code": null,
"e": 1961,
"s": 1560,
"text": "import pandas as pd\n\ndataFrame = pd.DataFrame({\"Product\": [\"SmartTV\", \"ChromeCast\", \"Speaker\", \"Earphone\"],\"Opening_Stock\": [300, 700, 1200, 1500],\"Closing_Stock\": [200, 500, 1000, 900]})\n\nprint\"DataFrame...\\n\",dataFrame\n\nprint\"\\nDisplaying a subset using indexing operator:\\n\",dataFrame[['Product']]\n\nprint\"\\nDisplaying a subset with multiple columns:\\n\",dataFrame[['Opening_Stock','Closing_Stock']]"
},
{
"code": null,
"e": 2000,
"s": 1961,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2554,
"s": 2000,
"text": "DataFrame...\n Closing_Stock Opening_Stock Product\n0 200 300 SmartTV\n1 500 700 ChromeCast\n2 1000 1200 Speaker\n3 900 1500 Earphone\n\nDisplaying a subset using indexing operator:\n Product\n0 SmartTV\n1 ChromeCast\n2 Speaker\n3 Earphone\n\nDisplaying a subset with multiple columns:\n Opening_Stock Closing_Stock\n0 300 200\n1 700 500\n2 1200 1000\n3 1500 900"
}
] |
Decorator Design Pattern in Java with Example - GeeksforGeeks
|
28 Oct, 2021
The decorator design pattern allows us to dynamically add functionality and behavior to an object without affecting the behavior of other existing objects within the same class. We use inheritance to extend the behavior of the class. This takes place at compile-time, and all the instances of that class get the extended behavior.
Decorator patterns allow a user to add new functionality to an existing object without altering its structure. So, there is no change to the original class.
The decorator design pattern is a structural pattern, which provides a wrapper to the existing class.
Decorator design pattern uses abstract classes or interfaces with the composition to implement the wrapper.
Decorator design patterns create decorator classes, which wrap the original class and supply additional functionality by keeping the class methods’ signature unchanged.
Decorator design patterns are most frequently used for applying single responsibility principles since we divide the functionality into classes with unique areas of concern.
The decorator design pattern is structurally almost like the chain of responsibility pattern.
Key points to remember
Decorator design pattern is useful in providing runtime modification abilities and hence more flexible. Its easy to maintain and extend when the amount of choices are more.The disadvantage of decorator design pattern is that it uses plenty of similar kind of objects (decorators)Decorator pattern is used a lot in Java IO classes, like FileReader, BufferedReader, etc.
Decorator design pattern is useful in providing runtime modification abilities and hence more flexible. Its easy to maintain and extend when the amount of choices are more.
The disadvantage of decorator design pattern is that it uses plenty of similar kind of objects (decorators)
Decorator pattern is used a lot in Java IO classes, like FileReader, BufferedReader, etc.
Procedure:
Create an interface.Create concrete classes implementing the same interface.Create an abstract decorator class implementing the above same interface.Create a concrete decorator class extending the above abstract decorator class.Now use the concrete decorator class created above to decorate interface objects.Lastly, verify the output
Create an interface.
Create concrete classes implementing the same interface.
Create an abstract decorator class implementing the above same interface.
Create a concrete decorator class extending the above abstract decorator class.
Now use the concrete decorator class created above to decorate interface objects.
Lastly, verify the output
Implementation:
We’re going to create a Shape interface and concrete classes implementing the Shape interface. We will then create an abstract decorator class ShapeDecorator implementing the Shape interface and having the Shape object as its instance variable.
‘Shape’ is the name of the interface‘Rectangle’ class and ‘Circle’ class will be concrete classes implementing the ‘Shape’ interface.‘ShapeDecorator’ is our abstract decorator class implementing the same ‘Shape’ interface.RedShapeDecorator is a concrete class implementing ShapeDecorator.DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate Shape objects.
‘Shape’ is the name of the interface
‘Rectangle’ class and ‘Circle’ class will be concrete classes implementing the ‘Shape’ interface.
‘ShapeDecorator’ is our abstract decorator class implementing the same ‘Shape’ interface.
RedShapeDecorator is a concrete class implementing ShapeDecorator.
DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate Shape objects.
Step 1: Creating an interface named ‘Shape’
Example
Java
// Interface named Shape// Shape.javapublic interface Shape { void draw();}
Step 2: Create concrete classes implementing the same interface. Rectangle.java and Circle.java are as follows
Example
Java
Java
// Class 1// Class 1 will be implementing the Shape interface // Rectangle.javapublic class Rectangle implements Shape { // Overriding the method @Override public void draw() { // /Print statement to execute when // draw() method of this class is called // later on in the main() method System.out.println("Shape: Rectangle"); }}
// Circle.javapublic class Circle implements Shape { @Override public void draw() { System.out.println("Shape: Circle"); }}
Step 3: Create an abstract decorator class implementing the Shape interface.
Example
Java
// Class 2// Abstract class// ShapeDecorator.javapublic abstract class ShapeDecorator implements Shape { // Protected variable protected Shape decoratedShape; // Method 1 // Abstract class method public ShapeDecorator(Shape decoratedShape) { // This keywordd refers to current object itself this.decoratedShape = decoratedShape; } // Method 2 - draw() // Outside abstract class public void draw() { decoratedShape.draw(); }}
Step 4: Create a concrete decorator class extending the ShapeDecorator class.
Example
Java
// Class 3// Concrete class extending the abstract class// RedShapeDecorator.javapublic class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { decoratedShape.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape) { // Display message whenever function is called System.out.println("Border Color: Red"); }}
Step 5: Using the RedShapeDecorator to decorate Shape objects.
Example
Java
// DecoratorPatternDemo.java // Class// Main classpublic class DecoratorPatternDemo { // Main driver method public static void main(String[] args) { // Creating an object of Shape interface // inside the main() method Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); // Display message System.out.println("Circle with normal border"); // Calling the draw method over the // object calls as created in // above classes // Call 1 circle.draw(); // Display message System.out.println("\nCircle of red border"); // Call 2 redCircle.draw(); // Display message System.out.println("\nRectangle of red border"); // Call 3 redRectangle.draw(); }}
Step 6: Verifying the output
Output:
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Output explanation:
Glancing at the decorator design pattern one can conclude out that this is often a decent choice in the following cases where
When we wish to add, enhance or perhaps remove the behavior or state of objects
When we just want to modify the functionality of a single object of the class and leave others unchanged
surinderdawra388
sagartomar9927
Java-Design-Patterns
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Set in Java
Overriding in Java
|
[
{
"code": null,
"e": 24738,
"s": 24710,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 25069,
"s": 24738,
"text": "The decorator design pattern allows us to dynamically add functionality and behavior to an object without affecting the behavior of other existing objects within the same class. We use inheritance to extend the behavior of the class. This takes place at compile-time, and all the instances of that class get the extended behavior."
},
{
"code": null,
"e": 25226,
"s": 25069,
"text": "Decorator patterns allow a user to add new functionality to an existing object without altering its structure. So, there is no change to the original class."
},
{
"code": null,
"e": 25328,
"s": 25226,
"text": "The decorator design pattern is a structural pattern, which provides a wrapper to the existing class."
},
{
"code": null,
"e": 25436,
"s": 25328,
"text": "Decorator design pattern uses abstract classes or interfaces with the composition to implement the wrapper."
},
{
"code": null,
"e": 25605,
"s": 25436,
"text": "Decorator design patterns create decorator classes, which wrap the original class and supply additional functionality by keeping the class methods’ signature unchanged."
},
{
"code": null,
"e": 25779,
"s": 25605,
"text": "Decorator design patterns are most frequently used for applying single responsibility principles since we divide the functionality into classes with unique areas of concern."
},
{
"code": null,
"e": 25873,
"s": 25779,
"text": "The decorator design pattern is structurally almost like the chain of responsibility pattern."
},
{
"code": null,
"e": 25897,
"s": 25873,
"text": "Key points to remember "
},
{
"code": null,
"e": 26266,
"s": 25897,
"text": "Decorator design pattern is useful in providing runtime modification abilities and hence more flexible. Its easy to maintain and extend when the amount of choices are more.The disadvantage of decorator design pattern is that it uses plenty of similar kind of objects (decorators)Decorator pattern is used a lot in Java IO classes, like FileReader, BufferedReader, etc."
},
{
"code": null,
"e": 26439,
"s": 26266,
"text": "Decorator design pattern is useful in providing runtime modification abilities and hence more flexible. Its easy to maintain and extend when the amount of choices are more."
},
{
"code": null,
"e": 26547,
"s": 26439,
"text": "The disadvantage of decorator design pattern is that it uses plenty of similar kind of objects (decorators)"
},
{
"code": null,
"e": 26637,
"s": 26547,
"text": "Decorator pattern is used a lot in Java IO classes, like FileReader, BufferedReader, etc."
},
{
"code": null,
"e": 26648,
"s": 26637,
"text": "Procedure:"
},
{
"code": null,
"e": 26983,
"s": 26648,
"text": "Create an interface.Create concrete classes implementing the same interface.Create an abstract decorator class implementing the above same interface.Create a concrete decorator class extending the above abstract decorator class.Now use the concrete decorator class created above to decorate interface objects.Lastly, verify the output"
},
{
"code": null,
"e": 27004,
"s": 26983,
"text": "Create an interface."
},
{
"code": null,
"e": 27061,
"s": 27004,
"text": "Create concrete classes implementing the same interface."
},
{
"code": null,
"e": 27135,
"s": 27061,
"text": "Create an abstract decorator class implementing the above same interface."
},
{
"code": null,
"e": 27215,
"s": 27135,
"text": "Create a concrete decorator class extending the above abstract decorator class."
},
{
"code": null,
"e": 27297,
"s": 27215,
"text": "Now use the concrete decorator class created above to decorate interface objects."
},
{
"code": null,
"e": 27323,
"s": 27297,
"text": "Lastly, verify the output"
},
{
"code": null,
"e": 27339,
"s": 27323,
"text": "Implementation:"
},
{
"code": null,
"e": 27584,
"s": 27339,
"text": "We’re going to create a Shape interface and concrete classes implementing the Shape interface. We will then create an abstract decorator class ShapeDecorator implementing the Shape interface and having the Shape object as its instance variable."
},
{
"code": null,
"e": 27963,
"s": 27584,
"text": "‘Shape’ is the name of the interface‘Rectangle’ class and ‘Circle’ class will be concrete classes implementing the ‘Shape’ interface.‘ShapeDecorator’ is our abstract decorator class implementing the same ‘Shape’ interface.RedShapeDecorator is a concrete class implementing ShapeDecorator.DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate Shape objects."
},
{
"code": null,
"e": 28000,
"s": 27963,
"text": "‘Shape’ is the name of the interface"
},
{
"code": null,
"e": 28098,
"s": 28000,
"text": "‘Rectangle’ class and ‘Circle’ class will be concrete classes implementing the ‘Shape’ interface."
},
{
"code": null,
"e": 28188,
"s": 28098,
"text": "‘ShapeDecorator’ is our abstract decorator class implementing the same ‘Shape’ interface."
},
{
"code": null,
"e": 28255,
"s": 28188,
"text": "RedShapeDecorator is a concrete class implementing ShapeDecorator."
},
{
"code": null,
"e": 28346,
"s": 28255,
"text": "DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate Shape objects."
},
{
"code": null,
"e": 28390,
"s": 28346,
"text": "Step 1: Creating an interface named ‘Shape’"
},
{
"code": null,
"e": 28398,
"s": 28390,
"text": "Example"
},
{
"code": null,
"e": 28403,
"s": 28398,
"text": "Java"
},
{
"code": "// Interface named Shape// Shape.javapublic interface Shape { void draw();}",
"e": 28482,
"s": 28403,
"text": null
},
{
"code": null,
"e": 28593,
"s": 28482,
"text": "Step 2: Create concrete classes implementing the same interface. Rectangle.java and Circle.java are as follows"
},
{
"code": null,
"e": 28602,
"s": 28593,
"text": "Example "
},
{
"code": null,
"e": 28607,
"s": 28602,
"text": "Java"
},
{
"code": null,
"e": 28612,
"s": 28607,
"text": "Java"
},
{
"code": "// Class 1// Class 1 will be implementing the Shape interface // Rectangle.javapublic class Rectangle implements Shape { // Overriding the method @Override public void draw() { // /Print statement to execute when // draw() method of this class is called // later on in the main() method System.out.println(\"Shape: Rectangle\"); }}",
"e": 28983,
"s": 28612,
"text": null
},
{
"code": "// Circle.javapublic class Circle implements Shape { @Override public void draw() { System.out.println(\"Shape: Circle\"); }}",
"e": 29127,
"s": 28983,
"text": null
},
{
"code": null,
"e": 29205,
"s": 29127,
"text": " Step 3: Create an abstract decorator class implementing the Shape interface."
},
{
"code": null,
"e": 29214,
"s": 29205,
"text": "Example "
},
{
"code": null,
"e": 29219,
"s": 29214,
"text": "Java"
},
{
"code": "// Class 2// Abstract class// ShapeDecorator.javapublic abstract class ShapeDecorator implements Shape { // Protected variable protected Shape decoratedShape; // Method 1 // Abstract class method public ShapeDecorator(Shape decoratedShape) { // This keywordd refers to current object itself this.decoratedShape = decoratedShape; } // Method 2 - draw() // Outside abstract class public void draw() { decoratedShape.draw(); }}",
"e": 29691,
"s": 29219,
"text": null
},
{
"code": null,
"e": 29770,
"s": 29691,
"text": " Step 4: Create a concrete decorator class extending the ShapeDecorator class."
},
{
"code": null,
"e": 29779,
"s": 29770,
"text": "Example "
},
{
"code": null,
"e": 29784,
"s": 29779,
"text": "Java"
},
{
"code": "// Class 3// Concrete class extending the abstract class// RedShapeDecorator.javapublic class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { decoratedShape.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape) { // Display message whenever function is called System.out.println(\"Border Color: Red\"); }}",
"e": 30285,
"s": 29784,
"text": null
},
{
"code": null,
"e": 30349,
"s": 30285,
"text": " Step 5: Using the RedShapeDecorator to decorate Shape objects."
},
{
"code": null,
"e": 30358,
"s": 30349,
"text": "Example "
},
{
"code": null,
"e": 30363,
"s": 30358,
"text": "Java"
},
{
"code": "// DecoratorPatternDemo.java // Class// Main classpublic class DecoratorPatternDemo { // Main driver method public static void main(String[] args) { // Creating an object of Shape interface // inside the main() method Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); // Display message System.out.println(\"Circle with normal border\"); // Calling the draw method over the // object calls as created in // above classes // Call 1 circle.draw(); // Display message System.out.println(\"\\nCircle of red border\"); // Call 2 redCircle.draw(); // Display message System.out.println(\"\\nRectangle of red border\"); // Call 3 redRectangle.draw(); }}",
"e": 31281,
"s": 30363,
"text": null
},
{
"code": null,
"e": 31311,
"s": 31281,
"text": " Step 6: Verifying the output"
},
{
"code": null,
"e": 31320,
"s": 31311,
"text": "Output: "
},
{
"code": null,
"e": 31456,
"s": 31320,
"text": "Circle with normal border\nShape: Circle\n\nCircle of red border\nShape: Circle\nBorder Color: Red\n\nRectangle of red border\nShape: Rectangle"
},
{
"code": null,
"e": 31478,
"s": 31456,
"text": "Output explanation: "
},
{
"code": null,
"e": 31604,
"s": 31478,
"text": "Glancing at the decorator design pattern one can conclude out that this is often a decent choice in the following cases where"
},
{
"code": null,
"e": 31684,
"s": 31604,
"text": "When we wish to add, enhance or perhaps remove the behavior or state of objects"
},
{
"code": null,
"e": 31789,
"s": 31684,
"text": "When we just want to modify the functionality of a single object of the class and leave others unchanged"
},
{
"code": null,
"e": 31808,
"s": 31791,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31823,
"s": 31808,
"text": "sagartomar9927"
},
{
"code": null,
"e": 31844,
"s": 31823,
"text": "Java-Design-Patterns"
},
{
"code": null,
"e": 31851,
"s": 31844,
"text": "Picked"
},
{
"code": null,
"e": 31875,
"s": 31851,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31880,
"s": 31875,
"text": "Java"
},
{
"code": null,
"e": 31899,
"s": 31880,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31904,
"s": 31899,
"text": "Java"
},
{
"code": null,
"e": 32002,
"s": 31904,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32034,
"s": 32002,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 32064,
"s": 32034,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32083,
"s": 32064,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32114,
"s": 32083,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 32132,
"s": 32114,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 32164,
"s": 32132,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32184,
"s": 32164,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 32199,
"s": 32184,
"text": "Stream In Java"
},
{
"code": null,
"e": 32211,
"s": 32199,
"text": "Set in Java"
}
] |
How to set MySQL default value NONE?
|
To set the default value in MySQL, you need to use the DEFAULT keyword. Let us first create a table −
mysql> create table DemoTable
(
ClientCountryName varchar(100) DEFAULT 'NONE'
);
Query OK, 0 rows affected (0.65 sec)
We have set DEFAULT above for values not entered while insertion. Now, let us insert some records in the table using the insert command. We haven’t inserted values here for some of the rows. The DEFAULT gets set there −
mysql> insert into DemoTable values('US');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('UK');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('AUS');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------------+
| ClientCountryName |
+-------------------+
| US |
| NONE |
| UK |
| NONE |
| AUS |
+-------------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "To set the default value in MySQL, you need to use the DEFAULT keyword. Let us first create a table −"
},
{
"code": null,
"e": 1285,
"s": 1164,
"text": "mysql> create table DemoTable\n(\n ClientCountryName varchar(100) DEFAULT 'NONE'\n);\nQuery OK, 0 rows affected (0.65 sec)"
},
{
"code": null,
"e": 1505,
"s": 1285,
"text": "We have set DEFAULT above for values not entered while insertion. Now, let us insert some records in the table using the insert command. We haven’t inserted values here for some of the rows. The DEFAULT gets set there −"
},
{
"code": null,
"e": 1893,
"s": 1505,
"text": "mysql> insert into DemoTable values('US');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values();\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values('UK');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable values();\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('AUS');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1953,
"s": 1893,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1984,
"s": 1953,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2025,
"s": 1984,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2248,
"s": 2025,
"text": "+-------------------+\n| ClientCountryName |\n+-------------------+\n| US |\n| NONE |\n| UK |\n| NONE |\n| AUS |\n+-------------------+\n5 rows in set (0.00 sec)"
}
] |
How to use title tag in HTML Page?
|
The title is essential in all the HTML Documents. To define the title of a document, use the <title> tag. The title of a document is visible on the web browser toolbar and the search engine results in display title for an HTML page.
Just keep in mind that you should add <title>...</title> tag inside <head>...</head> tag.
You can try the following code to insert a title in an HTML page. The title will be visible on the web browser toolbar
<!DOCTYPE html>
<html>
<head>
<title>HTML Title Tag</title>
</head>
<body>
<p>The content of the documents gets added here.</p>
</body>
</html>
The content of the documents gets added here.
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "The title is essential in all the HTML Documents. To define the title of a document, use the <title> tag. The title of a document is visible on the web browser toolbar and the search engine results in display title for an HTML page."
},
{
"code": null,
"e": 1385,
"s": 1295,
"text": "Just keep in mind that you should add <title>...</title> tag inside <head>...</head> tag."
},
{
"code": null,
"e": 1504,
"s": 1385,
"text": "You can try the following code to insert a title in an HTML page. The title will be visible on the web browser toolbar"
},
{
"code": null,
"e": 1673,
"s": 1504,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Title Tag</title>\n </head>\n\n <body>\n <p>The content of the documents gets added here.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 1719,
"s": 1673,
"text": "The content of the documents gets added here."
}
] |
A Practitioner's Guide to Natural Language Processing (Part I) — Processing & Understanding Text | by Dipanjan (DJ) Sarkar | Towards Data Science
|
Unstructured data, especially text, images and videos contain a wealth of information. However, due to the inherent complexity in processing and analyzing this data, people often refrain from spending extra time and effort in venturing out from structured datasets to analyze these unstructured sources of data, which can be a potential gold mine.
Natural Language Processing (NLP) is all about leveraging tools, techniques and algorithms to process and understand natural language-based data, which is usually unstructured like text, speech and so on. In this series of articles, we will be looking at tried and tested strategies, techniques and workflows which can be leveraged by practitioners and data scientists to extract useful insights from text data. We will also cover some useful and interesting use-cases for NLP. This article will be all about processing and understanding text data with tutorials and hands-on examples.
The nature of this series will be a mix of theoretical concepts but with a focus on hands-on techniques and strategies covering a wide variety of NLP problems. Some of the major areas that we will be covering in this series of articles include the following.
Processing & Understanding TextFeature Engineering & Text RepresentationSupervised Learning Models for Text DataUnsupervised Learning Models for Text DataAdvanced Topics
Processing & Understanding Text
Feature Engineering & Text Representation
Supervised Learning Models for Text Data
Unsupervised Learning Models for Text Data
Advanced Topics
Feel free to suggest more ideas as this series progresses, and I will be glad to cover something I might have missed out on. A lot of these articles will showcase tips and strategies which have worked well in real-world scenarios.
This article will be covering the following aspects of NLP in detail with hands-on examples.
Data Retrieval with Web ScrapingText wrangling and pre-processingParts of Speech TaggingShallow ParsingConstituency and Dependency ParsingNamed Entity RecognitionEmotion and Sentiment Analysis
Data Retrieval with Web Scraping
Text wrangling and pre-processing
Parts of Speech Tagging
Shallow Parsing
Constituency and Dependency Parsing
Named Entity Recognition
Emotion and Sentiment Analysis
This should give you a good idea of how to get started with analyzing syntax and semantics in text corpora.
Formally, NLP is a specialized field of computer science and artificial intelligence with roots in computational linguistics. It is primarily concerned with designing and building applications and systems that enable interaction between machines and natural languages that have been evolved for use by humans. Hence, often it is perceived as a niche area to work on. And people usually tend to focus more on machine learning or statistical learning.
When I started delving into the world of data science, even I was overwhelmed by the challenges in analyzing and modeling on text data. However, after working as a Data Scientist on several challenging problems around NLP over the years, I’ve noticed certain interesting aspects, including techniques, strategies and workflows which can be leveraged to solve a wide variety of problems. I have covered several topics around NLP in my books “Text Analytics with Python” (I’m writing a revised version of this soon) and “Practical Machine Learning with Python”.
However, based on all the excellent feedback I’ve received from all my readers (yes all you amazing people out there!), the main objective and motivation in creating this series of articles is to share my learnings with more people, who can’t always find time to sit and read through a book and can even refer to these articles on the go! Thus, there is no pre-requisite to buy any of these books to learn NLP.
When building the content and examples for this article, I was thinking if I should focus on a toy dataset to explain things better, or focus on an existing dataset from one of the main sources for data science datasets. Then I thought, why not build an end-to-end tutorial, where we scrape the web to get some text data and showcase examples based on that!
The source data which we will be working on will be news articles, which we have retrieved from inshorts, a website that gives us short, 60-word news articles on a wide variety of topics, and they even have an app for it!
inshorts.com
In this article, we will be working with text data from news articles on technology, sports and world news. I will be covering some basics on how to scrape and retrieve these news articles from their website in the next section.
I am assuming you are aware of the CRISP-DM model, which is typically an industry standard for executing any data science project. Typically, any NLP-based problem can be solved by a methodical workflow that has a sequence of steps. The major steps are depicted in the following figure.
We usually start with a corpus of text documents and follow standard processes of text wrangling and pre-processing, parsing and basic exploratory data analysis. Based on the initial insights, we usually represent the text using relevant feature engineering techniques. Depending on the problem at hand, we either focus on building predictive supervised models or unsupervised models, which usually focus more on pattern mining and grouping. Finally, we evaluate the model and the overall success criteria with relevant stakeholders or customers, and deploy the final model for future usage.
We will be scraping inshorts, the website, by leveraging python to retrieve news articles. We will be focusing on articles on technology, sports and world affairs. We will retrieve one page’s worth of articles for each category. A typical news category landing page is depicted in the following figure, which also highlights the HTML section for the textual content of each article.
Thus, we can see the specific HTML tags which contain the textual content of each news article in the landing page mentioned above. We will be using this information to extract news articles by leveraging the BeautifulSoup and requests libraries. Let’s first load up the following dependencies.
import requestsfrom bs4 import BeautifulSoupimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport os%matplotlib inline
We will now build a function which will leverage requests to access and get the HTML content from the landing pages of each of the three news categories. Then, we will use BeautifulSoup to parse and extract the news headline and article textual content for all the news articles in each category. We find the content by accessing the specific HTML tags and classes, where they are present (a sample of which I depicted in the previous figure).
It is pretty clear that we extract the news headline, article text and category and build out a data frame, where each row corresponds to a specific news article. We will now invoke this function and build our dataset.
news_df = build_dataset(seed_urls)news_df.head(10)
We, now, have a neatly formatted dataset of news articles and you can quickly check the total number of news articles with the following code.
news_df.news_category.value_counts()Output:-------world 25sports 25technology 24Name: news_category, dtype: int64
There are usually multiple steps involved in cleaning and pre-processing textual data. I have covered text pre-processing in detail in Chapter 3 of ‘Text Analytics with Python’ (code is open-sourced). However, in this section, I will highlight some of the most important steps which are used heavily in Natural Language Processing (NLP) pipelines and I frequently use them in my NLP projects. We will be leveraging a fair bit of nltk and spacy, both state-of-the-art libraries in NLP. Typically a pip install <library> or a conda install <library> should suffice. However, in case you face issues with loading up spacy’s language models, feel free to follow the steps highlighted below to resolve this issue (I had faced this issue in one of my systems).
# OPTIONAL: ONLY USE IF SPACY FAILS TO LOAD LANGUAGE MODEL# Use the following command to install spaCy> pip install -U spacyOR> conda install -c conda-forge spacy# Download the following language model and store it in diskhttps://github.com/explosion/spacy-models/releases/tag/en_core_web_md-2.0.0# Link the same to spacy > python -m spacy link ./spacymodels/en_core_web_md-2.0.0/en_core_web_md en_coreLinking successful ./spacymodels/en_core_web_md-2.0.0/en_core_web_md --> ./Anaconda3/lib/site-packages/spacy/data/en_coreYou can now load the model via spacy.load('en_core')
Let’s now load up the necessary dependencies for text pre-processing. We will remove negation words from stop words, since we would want to keep them as they might be useful, especially during sentiment analysis.
❗ IMPORTANT NOTE: A lot of you have messaged me about not being able to load the contractions module. It’s not a standard python module. We leverage a standard set of contractions available in the contractions.py file in my repository.Please add it in the same directory you run your code from, else it will not work.
import spacyimport pandas as pdimport numpy as npimport nltkfrom nltk.tokenize.toktok import ToktokTokenizerimport refrom bs4 import BeautifulSoupfrom contractions import CONTRACTION_MAPimport unicodedatanlp = spacy.load('en_core', parse=True, tag=True, entity=True)#nlp_vec = spacy.load('en_vecs', parse = True, tag=True, #entity=True)tokenizer = ToktokTokenizer()stopword_list = nltk.corpus.stopwords.words('english')stopword_list.remove('no')stopword_list.remove('not')
Often, unstructured text contains a lot of noise, especially if you use techniques like web or screen scraping. HTML tags are typically one of these components which don’t add much value towards understanding and analyzing text.
'Some important text'
It is quite evident from the above output that we can remove unnecessary HTML tags and retain the useful textual information from any document.
Usually in any text corpus, you might be dealing with accented characters/letters, especially if you only want to analyze the English language. Hence, we need to make sure that these characters are converted and standardized into ASCII characters. A simple example — converting é to e.
'Some Accented text'
The preceding function shows us how we can easily convert accented characters to normal English characters, which helps standardize the words in our corpus.
Contractions are shortened version of words or syllables. They often exist in either written or spoken forms in the English language. These shortened versions or contractions of words are created by removing specific letters and sounds. In case of English contractions, they are often created by removing one of the vowels from the word. Examples would be, do not to don’t and I would to I’d. Converting each contraction to its expanded, original form helps with text standardization.
We leverage a standard set of contractions available in the contractions.py file in my repository.
'You all cannot expand contractions I would think'
We can see how our function helps expand the contractions from the preceding output. Are there better ways of doing this? Definitely! If we have enough examples, we can even train a deep learning model for better performance.
Special characters and symbols are usually non-alphanumeric characters or even occasionally numeric characters (depending on the problem), which add to the extra noise in unstructured text. Usually, simple regular expressions (regexes) can be used to remove them.
'Well this was fun What do you think '
I’ve kept removing digits as optional, because often we might need to keep them in the pre-processed text.
To understand stemming, you need to gain some perspective on what word stems represent. Word stems are also known as the base form of a word, and we can create new words by attaching affixes to them in a process known as inflection. Consider the word JUMP. You can add affixes to it and form new words like JUMPS, JUMPED, and JUMPING. In this case, the base word JUMP is the word stem.
The figure shows how the word stem is present in all its inflections, since it forms the base on which each inflection is built upon using affixes. The reverse process of obtaining the base form of a word from its inflected form is known as stemming. Stemming helps us in standardizing words to their base or root stem, irrespective of their inflections, which helps many applications like classifying or clustering text, and even in information retrieval. Let’s see the popular Porter stemmer in action now!
'My system keep crash hi crash yesterday, our crash daili'
The Porter stemmer is based on the algorithm developed by its inventor, Dr. Martin Porter. Originally, the algorithm is said to have had a total of five different phases for reduction of inflections to their stems, where each phase has its own set of rules.
Do note that usually stemming has a fixed set of rules, hence, the root stems may not be lexicographically correct. Which means, the stemmed words may not be semantically correct, and might have a chance of not being present in the dictionary (as evident from the preceding output).
Lemmatization is very similar to stemming, where we remove word affixes to get to the base form of a word. However, the base form in this case is known as the root word, but not the root stem. The difference being that the root word is always a lexicographically correct word (present in the dictionary), but the root stem may not be so. Thus, root word, also known as the lemma, will always be present in the dictionary. Both nltk and spacy have excellent lemmatizers. We will be using spacy here.
'My system keep crash ! his crash yesterday , ours crash daily'
You can see that the semantics of the words are not affected by this, yet our text is still standardized.
Do note that the lemmatization process is considerably slower than stemming, because an additional step is involved where the root form or lemma is formed by removing the affix from the word if and only if the lemma is present in the dictionary.
Words which have little or no significance, especially when constructing meaningful features from text, are known as stopwords or stop words. These are usually words that end up having the maximum frequency if you do a simple term or word frequency in a corpus. Typically, these can be articles, conjunctions, prepositions and so on. Some examples of stopwords are a, an, the, and the like.
', , stopwords , computer not'
There is no universal stopword list, but we use a standard English language stopwords list from nltk. You can also add your own domain-specific stopwords as needed.
While we can definitely keep going with more techniques like correcting spelling, grammar and so on, let’s now bring everything we learnt together and chain these operations to build a text normalizer to pre-process text data.
Let’s now put this function in action! We will first combine the news headline and the news article text together to form a document for each piece of news. Then, we will pre-process them.
{'clean_text': 'us unveils world powerful supercomputer beat china us unveil world powerful supercomputer call summit beat previous record holder china sunway taihulight peak performance trillion calculation per second twice fast sunway taihulight capable trillion calculation per second summit server reportedly take size two tennis court', 'full_text': "US unveils world's most powerful supercomputer, beats China. The US has unveiled the world's most powerful supercomputer called 'Summit', beating the previous record-holder China's Sunway TaihuLight. With a peak performance of 200,000 trillion calculations per second, it is over twice as fast as Sunway TaihuLight, which is capable of 93,000 trillion calculations per second. Summit has 4,608 servers, which reportedly take up the size of two tennis courts."}
Thus, you can see how our text pre-processor helps in pre-processing our news articles! After this, you can save this dataset to disk if needed, so that you can always load it up later for future analysis.
news_df.to_csv('news.csv', index=False, encoding='utf-8')
For any language, syntax and structure usually go hand in hand, where a set of specific rules, conventions, and principles govern the way words are combined into phrases; phrases get combines into clauses; and clauses get combined into sentences. We will be talking specifically about the English language syntax and structure in this section. In English, words usually combine together to form other constituent units. These constituents include words, phrases, clauses, and sentences. Considering a sentence, “The brown fox is quick and he is jumping over the lazy dog”, it is made of a bunch of words and just looking at the words by themselves don’t tell us much.
Knowledge about the structure and syntax of language is helpful in many areas like text processing, annotation, and parsing for further operations such as text classification or summarization. Typical parsing techniques for understanding text syntax are mentioned below.
Parts of Speech (POS) Tagging
Shallow Parsing or Chunking
Constituency Parsing
Dependency Parsing
We will be looking at all of these techniques in subsequent sections. Considering our previous example sentence “The brown fox is quick and he is jumping over the lazy dog”, if we were to annotate it using basic POS tags, it would look like the following figure.
Thus, a sentence typically follows a hierarchical structure consisting the following components,
sentence → clauses → phrases → words
Parts of speech (POS) are specific lexical categories to which words are assigned, based on their syntactic context and role. Usually, words can fall into one of the following major categories.
N(oun): This usually denotes words that depict some object or entity, which may be living or nonliving. Some examples would be fox , dog , book , and so on. The POS tag symbol for nouns is N.
V(erb): Verbs are words that are used to describe certain actions, states, or occurrences. There are a wide variety of further subcategories, such as auxiliary, reflexive, and transitive verbs (and many more). Some typical examples of verbs would be running , jumping , read , and write . The POS tag symbol for verbs is V.
Adj(ective): Adjectives are words used to describe or qualify other words, typically nouns and noun phrases. The phrase beautiful flower has the noun (N) flower which is described or qualified using the adjective (ADJ) beautiful . The POS tag symbol for adjectives is ADJ .
Adv(erb): Adverbs usually act as modifiers for other words including nouns, adjectives, verbs, or other adverbs. The phrase very beautiful flower has the adverb (ADV) very , which modifies the adjective (ADJ) beautiful , indicating the degree to which the flower is beautiful. The POS tag symbol for adverbs is ADV.
Besides these four major categories of parts of speech , there are other categories that occur frequently in the English language. These include pronouns, prepositions, interjections, conjunctions, determiners, and many others. Furthermore, each POS tag like the noun (N) can be further subdivided into categories like singular nouns (NN), singular proper nouns (NNP), and plural nouns (NNS).
The process of classifying and labeling POS tags for words called parts of speech tagging or POS tagging . POS tags are used to annotate words and depict their POS, which is really helpful to perform specific analysis, such as narrowing down upon nouns and seeing which ones are the most prominent, word sense disambiguation, and grammar analysis. We will be leveraging both nltk and spacy which usually use the Penn Treebank notation for POS tagging.
We can see that each of these libraries treat tokens in their own way and assign specific tags for them. Based on what we see, spacy seems to be doing slightly better than nltk.
Based on the hierarchy we depicted earlier, groups of words make up phrases. There are five major categories of phrases:
Noun phrase (NP): These are phrases where a noun acts as the head word. Noun phrases act as a subject or object to a verb.
Verb phrase (VP): These phrases are lexical units that have a verb acting as the head word. Usually, there are two forms of verb phrases. One form has the verb components as well as other entities such as nouns, adjectives, or adverbs as parts of the object.
Adjective phrase (ADJP): These are phrases with an adjective as the head word. Their main role is to describe or qualify nouns and pronouns in a sentence, and they will be either placed before or after the noun or pronoun.
Adverb phrase (ADVP): These phrases act like adverbs since the adverb acts as the head word in the phrase. Adverb phrases are used as modifiers for nouns, verbs, or adverbs themselves by providing further details that describe or qualify them.
Prepositional phrase (PP): These phrases usually contain a preposition as the head word and other lexical components like nouns, pronouns, and so on. These act like an adjective or adverb describing other words or phrases.
Shallow parsing, also known as light parsing or chunking , is a popular natural language processing technique of analyzing the structure of a sentence to break it down into its smallest constituents (which are tokens such as words) and group them together into higher-level phrases. This includes POS tags as well as phrases from a sentence.
We will leverage the conll2000 corpus for training our shallow parser model. This corpus is available in nltk with chunk annotations and we will be using around 10K records for training our model. A sample annotated sentence is depicted as follows.
10900 48(S Chancellor/NNP (PP of/IN) (NP the/DT Exchequer/NNP) (NP Nigel/NNP Lawson/NNP) (NP 's/POS restated/VBN commitment/NN) (PP to/TO) (NP a/DT firm/NN monetary/JJ policy/NN) (VP has/VBZ helped/VBN to/TO prevent/VB) (NP a/DT freefall/NN) (PP in/IN) (NP sterling/NN) (PP over/IN) (NP the/DT past/JJ week/NN) ./.)
From the preceding output, you can see that our data points are sentences that are already annotated with phrases and POS tags metadata that will be useful in training our shallow parser model. We will leverage two chunking utility functions, tree2conlltags , to get triples of word, tag, and chunk tags for each token, and conlltags2tree to generate a parse tree from these token triples. We will be using these functions to train our parser. A sample is depicted below.
[('Chancellor', 'NNP', 'O'), ('of', 'IN', 'B-PP'), ('the', 'DT', 'B-NP'), ('Exchequer', 'NNP', 'I-NP'), ('Nigel', 'NNP', 'B-NP'), ('Lawson', 'NNP', 'I-NP'), ("'s", 'POS', 'B-NP'), ('restated', 'VBN', 'I-NP'), ('commitment', 'NN', 'I-NP'), ('to', 'TO', 'B-PP'), ('a', 'DT', 'B-NP'), ('firm', 'NN', 'I-NP'), ('monetary', 'JJ', 'I-NP'), ('policy', 'NN', 'I-NP'), ('has', 'VBZ', 'B-VP'), ('helped', 'VBN', 'I-VP'), ('to', 'TO', 'I-VP'), ('prevent', 'VB', 'I-VP'), ('a', 'DT', 'B-NP'), ('freefall', 'NN', 'I-NP'), ('in', 'IN', 'B-PP'), ('sterling', 'NN', 'B-NP'), ('over', 'IN', 'B-PP'), ('the', 'DT', 'B-NP'), ('past', 'JJ', 'I-NP'), ('week', 'NN', 'I-NP'), ('.', '.', 'O')]
The chunk tags use the IOB format. This notation represents Inside, Outside, and Beginning. The B- prefix before a tag indicates it is the beginning of a chunk, and I- prefix indicates that it is inside a chunk. The O tag indicates that the token does not belong to any chunk. The B- tag is always used when there are subsequent tags of the same type following it without the presence of O tags between them.
We will now define a function conll_tag_ chunks() to extract POS and chunk tags from sentences with chunked annotations and a function called combined_taggers() to train multiple taggers with backoff taggers (e.g. unigram and bigram taggers)
We will now define a class NGramTagChunker that will take in tagged sentences as training input, get their (word, POS tag, Chunk tag) WTC triples, and train a BigramTagger with a UnigramTagger as the backoff tagger. We will also define a parse() function to perform shallow parsing on new sentences
The UnigramTagger , BigramTagger , and TrigramTagger are classes that inherit from the base class NGramTagger , which itself inherits from the ContextTagger class , which inherits from the SequentialBackoffTagger class .
We will use this class to train on the conll2000 chunked train_data and evaluate the model performance on the test_data
ChunkParse score: IOB Accuracy: 90.0%% Precision: 82.1%% Recall: 86.3%% F-Measure: 84.1%%
Our chunking model gets an accuracy of around 90% which is quite good! Let’s now leverage this model to shallow parse and chunk our sample news article headline which we used earlier, “US unveils world’s most powerful supercomputer, beats China”.
chunk_tree = ntc.parse(nltk_pos_tagged)print(chunk_tree)Output:-------(S (NP US/NNP) (VP unveils/VBZ world's/VBZ) (NP most/RBS powerful/JJ supercomputer,/JJ beats/NNS China/NNP))
Thus you can see it has identified two noun phrases (NP) and one verb phrase (VP) in the news article. Each word’s POS tags are also visible. We can also visualize this in the form of a tree as follows. You might need to install ghostscript in case nltk throws an error.
The preceding output gives a good sense of structure after shallow parsing the news headline.
Constituent-based grammars are used to analyze and determine the constituents of a sentence. These grammars can be used to model or represent the internal structure of sentences in terms of a hierarchically ordered structure of their constituents. Each and every word usually belongs to a specific lexical category in the case and forms the head word of different phrases. These phrases are formed based on rules called phrase structure rules.
Phrase structure rules form the core of constituency grammars, because they talk about syntax and rules that govern the hierarchy and ordering of the various constituents in the sentences. These rules cater to two things primarily.
They determine what words are used to construct the phrases or constituents.
They determine how we need to order these constituents together.
The generic representation of a phrase structure rule is S → AB , which depicts that the structure S consists of constituents A and B , and the ordering is A followed by B . While there are several rules (refer to Chapter 1, Page 19: Text Analytics with Python, if you want to dive deeper), the most important rule describes how to divide a sentence or a clause. The phrase structure rule denotes a binary division for a sentence or a clause as S → NP VP where S is the sentence or clause, and it is divided into the subject, denoted by the noun phrase (NP) and the predicate, denoted by the verb phrase (VP).
A constituency parser can be built based on such grammars/rules, which are usually collectively available as context-free grammar (CFG) or phrase-structured grammar. The parser will process input sentences according to these rules, and help in building a parse tree.
We will be using nltk and the StanfordParser here to generate parse trees.
Prerequisites: Download the official Stanford Parser from here, which seems to work quite well. You can try out a later version by going to this website and checking the Release History section. After downloading, unzip it to a known location in your filesystem. Once done, you are now ready to use the parser from nltk , which we will be exploring soon.
The Stanford parser generally uses a PCFG (probabilistic context-free grammar) parser. A PCFG is a context-free grammar that associates a probability with each of its production rules. The probability of a parse tree generated from a PCFG is simply the production of the individual probabilities of the productions used to generate it.
(ROOT (SINV (S (NP (NNP US)) (VP (VBZ unveils) (NP (NP (NN world) (POS 's)) (ADJP (RBS most) (JJ powerful)) (NN supercomputer)))) (, ,) (VP (VBZ beats)) (NP (NNP China))))
We can see the constituency parse tree for our news headline. Let’s visualize it to understand the structure better.
from IPython.display import displaydisplay(result[0])
We can see the nested hierarchical structure of the constituents in the preceding output as compared to the flat structure in shallow parsing. In case you are wondering what SINV means, it represents an Inverted declarative sentence, i.e. one in which the subject follows the tensed verb or modal. Refer to the Penn Treebank reference as needed to lookup other tags.
In dependency parsing, we try to use dependency-based grammars to analyze and infer both structure and semantic dependencies and relationships between tokens in a sentence. The basic principle behind a dependency grammar is that in any sentence in the language, all words except one, have some relationship or dependency on other words in the sentence. The word that has no dependency is called the root of the sentence. The verb is taken as the root of the sentence in most cases. All the other words are directly or indirectly linked to the root verb using links , which are the dependencies.
Considering our sentence “The brown fox is quick and he is jumping over the lazy dog” , if we wanted to draw the dependency syntax tree for this, we would have the structure
These dependency relationships each have their own meaning and are a part of a list of universal dependency types. This is discussed in an original paper, Universal Stanford Dependencies: A Cross-Linguistic Typology by de Marneffe et al, 2014). You can check out the exhaustive list of dependency types and their meanings here.
If we observe some of these dependencies, it is not too hard to understand them.
The dependency tag det is pretty intuitive — it denotes the determiner relationship between a nominal head and the determiner. Usually, the word with POS tag DET will also have the det dependency tag relation. Examples include fox → the and dog → the.
The dependency tag amod stands for adjectival modifier and stands for any adjective that modifies the meaning of a noun. Examples include fox → brown and dog → lazy.
The dependency tag nsubj stands for an entity that acts as a subject or agent in a clause. Examples include is → fox and jumping → he.
The dependencies cc and conj have more to do with linkages related to words connected by coordinating conjunctions . Examples include is → and and is → jumping.
The dependency tag aux indicates the auxiliary or secondary verb in the clause. Example: jumping → is.
The dependency tag acomp stands for adjective complement and acts as the complement or object to a verb in the sentence. Example: is → quick
The dependency tag prep denotes a prepositional modifier, which usually modifies the meaning of a noun, verb, adjective, or preposition. Usually, this representation is used for prepositions having a noun or noun phrase complement. Example: jumping → over.
The dependency tag pobj is used to denote the object of a preposition . This is usually the head of a noun phrase following a preposition in the sentence. Example: over → dog.
Spacy had two types of English dependency parsers based on what language models you use, you can find more details here. Based on language models, you can use the Universal Dependencies Scheme or the CLEAR Style Dependency Scheme also available in NLP4J now. We will now leverage spacy and print out the dependencies for each token in our news headline.
[]<---US[compound]--->[]--------['US']<---unveils[nsubj]--->['supercomputer', ',']--------[]<---world[poss]--->["'s"]--------[]<---'s[case]--->[]--------[]<---most[amod]--->[]--------[]<---powerful[compound]--->[]--------['world', 'most', 'powerful']<---supercomputer[appos]--->[]--------[]<---,[punct]--->[]--------['unveils']<---beats[ROOT]--->['China']--------[]<---China[dobj]--->[]--------
It is evident that the verb beats is the ROOT since it doesn’t have any other dependencies as compared to the other tokens. For knowing more about each annotation you can always refer to the CLEAR dependency scheme. We can also visualize the above dependencies in a better way.
You can also leverage nltk and the StanfordDependencyParser to visualize and build out the dependency tree. We showcase the dependency tree both in its raw and annotated form as follows.
(beats (unveils US (supercomputer (world 's) (powerful most))) China)
You can notice the similarities with the tree we had obtained earlier. The annotations help with understanding the type of dependency among the different tokens.
In any text document, there are particular terms that represent specific entities that are more informative and have a unique context. These entities are known as named entities , which more specifically refer to terms that represent real-world objects like people, places, organizations, and so on, which are often denoted by proper names. A naive approach could be to find these by looking at the noun phrases in text documents. Named entity recognition (NER) , also known as entity chunking/extraction , is a popular technique used in information extraction to identify and segment the named entities and classify or categorize them under various predefined classes.
SpaCy has some excellent capabilities for named entity recognition. Let’s try and use it on one of our sample news articles.
[(US, 'GPE'), (China, 'GPE'), (US, 'GPE'), (China, 'GPE'), (Sunway, 'ORG'), (TaihuLight, 'ORG'), (200,000, 'CARDINAL'), (second, 'ORDINAL'), (Sunway, 'ORG'), (TaihuLight, 'ORG'), (93,000, 'CARDINAL'), (4,608, 'CARDINAL'), (two, 'CARDINAL')]
We can clearly see that the major named entities have been identified by spacy. To understand more in detail about what each named entity means, you can refer to the documentation or check out the following table for convenience.
Let’s now find out the most frequent named entities in our news corpus! For this, we will build out a data frame of all the named entities and their types using the following code.
We can now transform and aggregate this data frame to find the top occuring entities and types.
Do you notice anything interesting? (Hint: Maybe the supposed summit between Trump and Kim Jong!). We also see that it has correctly identified ‘Messenger’ as a product (from Facebook).
We can also group by the entity types to get a sense of what types of entites occur most in our news corpus.
We can see that people, places and organizations are the most mentioned entities though interestingly we also have many other entities.
Another nice NER tagger is the StanfordNERTagger available from the nltk interface. For this, you need to have Java installed and then download the Stanford NER resources. Unzip them to a location of your choice (I used E:/stanford in my system).
Stanford’s Named Entity Recognizer is based on an implementation of linear chain Conditional Random Field (CRF) sequence models. Unfortunately this model is only trained on instances of PERSON, ORGANIZATION and LOCATION types. Following code can be used as a standard workflow which helps us extract the named entities using this tagger and show the top named entities and their types (extraction differs slightly from spacy).
We notice quite similar results though restricted to only three types of named entities. Interestingly, we see a number of mentioned of several people in various sports.
Sentiment analysis is perhaps one of the most popular applications of NLP, with a vast number of tutorials, courses, and applications that focus on analyzing sentiments of diverse datasets ranging from corporate surveys to movie reviews. The key aspect of sentiment analysis is to analyze a body of text for understanding the opinion expressed by it. Typically, we quantify this sentiment with a positive or negative value, called polarity. The overall sentiment is often inferred as positive, neutral or negative from the sign of the polarity score.
Usually, sentiment analysis works best on text that has a subjective context than on text with only an objective context. Objective text usually depicts some normal statements or facts without expressing any emotion, feelings, or mood. Subjective text contains text that is usually expressed by a human having typical moods, emotions, and feelings. Sentiment analysis is widely used, especially as a part of social media analysis for any domain, be it a business, a recent movie, or a product launch, to understand its reception by the people and what they think of it based on their opinions or, you guessed it, sentiment!
Typically, sentiment analysis for text data can be computed on several levels, including on an individual sentence level, paragraph level, or the entire document as a whole. Often, sentiment is computed on the document as a whole or some aggregations are done after computing the sentiment for individual sentences. There are two major approaches to sentiment analysis.
Supervised machine learning or deep learning approaches
Unsupervised lexicon-based approaches
For the first approach we typically need pre-labeled data. Hence, we will be focusing on the second approach. For a comprehensive coverage of sentiment analysis, refer to Chapter 7: Analyzing Movie Reviews Sentiment, Practical Machine Learning with Python, Springer\Apress, 2018. In this scenario, we do not have the convenience of a well-labeled training dataset. Hence, we will need to use unsupervised techniques for predicting the sentiment by using knowledgebases, ontologies, databases, and lexicons that have detailed information, specially curated and prepared just for sentiment analysis. A lexicon is a dictionary, vocabulary, or a book of words. In our case, lexicons are special dictionaries or vocabularies that have been created for analyzing sentiments. Most of these lexicons have a list of positive and negative polar words with some score associated with them, and using various techniques like the position of words, surrounding words, context, parts of speech, phrases, and so on, scores are assigned to the text documents for which we want to compute the sentiment. After aggregating these scores, we get the final sentiment.
Various popular lexicons are used for sentiment analysis, including the following.
AFINN lexicon
Bing Liu’s lexicon
MPQA subjectivity lexicon
SentiWordNet
VADER lexicon
TextBlob lexicon
This is not an exhaustive list of lexicons that can be leveraged for sentiment analysis, and there are several other lexicons which can be easily obtained from the Internet. Feel free to check out each of these links and explore them. We will be covering two techniques in this section.
The AFINN lexicon is perhaps one of the simplest and most popular lexicons that can be used extensively for sentiment analysis. Developed and curated by Finn Årup Nielsen, you can find more details on this lexicon in the paper, “A new ANEW: evaluation of a word list for sentiment analysis in microblogs”, proceedings of the ESWC 2011 Workshop. The current version of the lexicon is AFINN-en-165. txt and it contains over 3,300+ words with a polarity score associated with each word. You can find this lexicon at the author’s official GitHub repository along with previous versions of it, including AFINN-111. The author has also created a nice wrapper library on top of this in Python called afinn, which we will be using for our analysis.
The following code computes sentiment for all our news articles and shows summary statistics of general sentiment per news category.
We can get a good idea of general sentiment statistics across different news categories. Looks like the average sentiment is very positive in sports and reasonably negative in technology! Let’s look at some visualizations now.
We can see that the spread of sentiment polarity is much higher in sports and world as compared to technology where a lot of the articles seem to be having a negative polarity. We can also visualize the frequency of sentiment labels.
No surprises here that technology has the most number of negative articles and world the most number of positive articles. Sports might have more neutral articles due to the presence of articles which are more objective in nature (talking about sporting events without the presence of any emotion or feelings). Let’s dive deeper into the most positive and negative sentiment news articles for technology news.
Looks like the most negative article is all about a recent smartphone scam in India and the most positive article is about a contest to get married in a self-driving shuttle. Interesting! Let’s do a similar analysis for world news.
Interestingly Trump features in both the most positive and the most negative world news articles. Do read the articles to get some more perspective into why the model selected one of them as the most negative and the other one as the most positive (no surprises here!).
TextBlob is another excellent open-source library for performing NLP tasks with ease, including sentiment analysis. It also an a sentiment lexicon (in the form of an XML file) which it leverages to give both polarity and subjectivity scores. Typically, the scores have a normalized scale as compare to Afinn. The polarity score is a float within the range [-1.0, 1.0]. The subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. Let’s use this now to get the sentiment polarity and labels for each news article and aggregate the summary statistics per news category.
Looks like the average sentiment is the most positive in world and least positive in technology! However, these metrics might be indicating that the model is predicting more articles as positive. Let’s look at the sentiment frequency distribution per news category.
There definitely seems to be more positive articles across the news categories here as compared to our previous model. However, still looks like technology has the most negative articles and world, the most positive articles similar to our previous analysis. Let’s now do a comparative analysis and see if we still get similar articles in the most positive and negative categories for world news.
Well, looks like the most negative world news article here is even more depressing than what we saw the last time! The most positive article is still the same as what we had obtained in our last model.
Finally, we can even evaluate and compare between these two models as to how many predictions are matching and how many are not (by leveraging a confusion matrix which is often used in classification). We leverage our nifty model_evaluation_utils module for this.
In the preceding table, the ‘Actual’ labels are predictions from the Afinn sentiment analyzer and the ‘Predicted’ labels are predictions from TextBlob. Looks like our previous assumption was correct. TextBlob definitely predicts several neutral and negative articles as positive. Overall most of the sentiment predictions seem to match, which is good!
This was definitely one of my longer articles! If you are reading this, I really commend your efforts for staying with me till the end of this article. These examples should give you a good idea about how to start working with a corpus of text documents and popular strategies for text retrieval, pre-processing, parsing, understanding structure, entities and sentiment. We will be covering feature engineering and representation techniques with hands-on examples in the next article of this series. Stay tuned!
All the code and datasets used in this article can be accessed from my GitHub
The code is also available as a Jupyter notebook
I often mentor and help students at Springboard to learn essential skills around Data Science. Thanks to them for helping me develop this content. Do check out Springboard’s DSC bootcamp if you are interested in a career-focused structured path towards learning Data Science.
www.springboard.com
A lot of this code comes from the research and work that I had done during writing my book “Text Analytics with Python”. The code is open-sourced on GitHub. (Python 3.x edition coming by end of this year!)
www.springer.com
“Practical Machine Learning with Python”, my other book also covers text classification and sentiment analysis in detail. The code is open-sourced on GitHub for your convenience.
www.springer.com
If you have any feedback, comments or interesting insights to share about my article or data science in general, feel free to reach out to me on my LinkedIn social media channel.
www.linkedin.com
Thanks to Durba for editing this article.
|
[
{
"code": null,
"e": 395,
"s": 47,
"text": "Unstructured data, especially text, images and videos contain a wealth of information. However, due to the inherent complexity in processing and analyzing this data, people often refrain from spending extra time and effort in venturing out from structured datasets to analyze these unstructured sources of data, which can be a potential gold mine."
},
{
"code": null,
"e": 981,
"s": 395,
"text": "Natural Language Processing (NLP) is all about leveraging tools, techniques and algorithms to process and understand natural language-based data, which is usually unstructured like text, speech and so on. In this series of articles, we will be looking at tried and tested strategies, techniques and workflows which can be leveraged by practitioners and data scientists to extract useful insights from text data. We will also cover some useful and interesting use-cases for NLP. This article will be all about processing and understanding text data with tutorials and hands-on examples."
},
{
"code": null,
"e": 1240,
"s": 981,
"text": "The nature of this series will be a mix of theoretical concepts but with a focus on hands-on techniques and strategies covering a wide variety of NLP problems. Some of the major areas that we will be covering in this series of articles include the following."
},
{
"code": null,
"e": 1410,
"s": 1240,
"text": "Processing & Understanding TextFeature Engineering & Text RepresentationSupervised Learning Models for Text DataUnsupervised Learning Models for Text DataAdvanced Topics"
},
{
"code": null,
"e": 1442,
"s": 1410,
"text": "Processing & Understanding Text"
},
{
"code": null,
"e": 1484,
"s": 1442,
"text": "Feature Engineering & Text Representation"
},
{
"code": null,
"e": 1525,
"s": 1484,
"text": "Supervised Learning Models for Text Data"
},
{
"code": null,
"e": 1568,
"s": 1525,
"text": "Unsupervised Learning Models for Text Data"
},
{
"code": null,
"e": 1584,
"s": 1568,
"text": "Advanced Topics"
},
{
"code": null,
"e": 1815,
"s": 1584,
"text": "Feel free to suggest more ideas as this series progresses, and I will be glad to cover something I might have missed out on. A lot of these articles will showcase tips and strategies which have worked well in real-world scenarios."
},
{
"code": null,
"e": 1908,
"s": 1815,
"text": "This article will be covering the following aspects of NLP in detail with hands-on examples."
},
{
"code": null,
"e": 2101,
"s": 1908,
"text": "Data Retrieval with Web ScrapingText wrangling and pre-processingParts of Speech TaggingShallow ParsingConstituency and Dependency ParsingNamed Entity RecognitionEmotion and Sentiment Analysis"
},
{
"code": null,
"e": 2134,
"s": 2101,
"text": "Data Retrieval with Web Scraping"
},
{
"code": null,
"e": 2168,
"s": 2134,
"text": "Text wrangling and pre-processing"
},
{
"code": null,
"e": 2192,
"s": 2168,
"text": "Parts of Speech Tagging"
},
{
"code": null,
"e": 2208,
"s": 2192,
"text": "Shallow Parsing"
},
{
"code": null,
"e": 2244,
"s": 2208,
"text": "Constituency and Dependency Parsing"
},
{
"code": null,
"e": 2269,
"s": 2244,
"text": "Named Entity Recognition"
},
{
"code": null,
"e": 2300,
"s": 2269,
"text": "Emotion and Sentiment Analysis"
},
{
"code": null,
"e": 2408,
"s": 2300,
"text": "This should give you a good idea of how to get started with analyzing syntax and semantics in text corpora."
},
{
"code": null,
"e": 2858,
"s": 2408,
"text": "Formally, NLP is a specialized field of computer science and artificial intelligence with roots in computational linguistics. It is primarily concerned with designing and building applications and systems that enable interaction between machines and natural languages that have been evolved for use by humans. Hence, often it is perceived as a niche area to work on. And people usually tend to focus more on machine learning or statistical learning."
},
{
"code": null,
"e": 3418,
"s": 2858,
"text": "When I started delving into the world of data science, even I was overwhelmed by the challenges in analyzing and modeling on text data. However, after working as a Data Scientist on several challenging problems around NLP over the years, I’ve noticed certain interesting aspects, including techniques, strategies and workflows which can be leveraged to solve a wide variety of problems. I have covered several topics around NLP in my books “Text Analytics with Python” (I’m writing a revised version of this soon) and “Practical Machine Learning with Python”."
},
{
"code": null,
"e": 3829,
"s": 3418,
"text": "However, based on all the excellent feedback I’ve received from all my readers (yes all you amazing people out there!), the main objective and motivation in creating this series of articles is to share my learnings with more people, who can’t always find time to sit and read through a book and can even refer to these articles on the go! Thus, there is no pre-requisite to buy any of these books to learn NLP."
},
{
"code": null,
"e": 4187,
"s": 3829,
"text": "When building the content and examples for this article, I was thinking if I should focus on a toy dataset to explain things better, or focus on an existing dataset from one of the main sources for data science datasets. Then I thought, why not build an end-to-end tutorial, where we scrape the web to get some text data and showcase examples based on that!"
},
{
"code": null,
"e": 4409,
"s": 4187,
"text": "The source data which we will be working on will be news articles, which we have retrieved from inshorts, a website that gives us short, 60-word news articles on a wide variety of topics, and they even have an app for it!"
},
{
"code": null,
"e": 4422,
"s": 4409,
"text": "inshorts.com"
},
{
"code": null,
"e": 4651,
"s": 4422,
"text": "In this article, we will be working with text data from news articles on technology, sports and world news. I will be covering some basics on how to scrape and retrieve these news articles from their website in the next section."
},
{
"code": null,
"e": 4938,
"s": 4651,
"text": "I am assuming you are aware of the CRISP-DM model, which is typically an industry standard for executing any data science project. Typically, any NLP-based problem can be solved by a methodical workflow that has a sequence of steps. The major steps are depicted in the following figure."
},
{
"code": null,
"e": 5530,
"s": 4938,
"text": "We usually start with a corpus of text documents and follow standard processes of text wrangling and pre-processing, parsing and basic exploratory data analysis. Based on the initial insights, we usually represent the text using relevant feature engineering techniques. Depending on the problem at hand, we either focus on building predictive supervised models or unsupervised models, which usually focus more on pattern mining and grouping. Finally, we evaluate the model and the overall success criteria with relevant stakeholders or customers, and deploy the final model for future usage."
},
{
"code": null,
"e": 5913,
"s": 5530,
"text": "We will be scraping inshorts, the website, by leveraging python to retrieve news articles. We will be focusing on articles on technology, sports and world affairs. We will retrieve one page’s worth of articles for each category. A typical news category landing page is depicted in the following figure, which also highlights the HTML section for the textual content of each article."
},
{
"code": null,
"e": 6208,
"s": 5913,
"text": "Thus, we can see the specific HTML tags which contain the textual content of each news article in the landing page mentioned above. We will be using this information to extract news articles by leveraging the BeautifulSoup and requests libraries. Let’s first load up the following dependencies."
},
{
"code": null,
"e": 6369,
"s": 6208,
"text": "import requestsfrom bs4 import BeautifulSoupimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport os%matplotlib inline"
},
{
"code": null,
"e": 6813,
"s": 6369,
"text": "We will now build a function which will leverage requests to access and get the HTML content from the landing pages of each of the three news categories. Then, we will use BeautifulSoup to parse and extract the news headline and article textual content for all the news articles in each category. We find the content by accessing the specific HTML tags and classes, where they are present (a sample of which I depicted in the previous figure)."
},
{
"code": null,
"e": 7032,
"s": 6813,
"text": "It is pretty clear that we extract the news headline, article text and category and build out a data frame, where each row corresponds to a specific news article. We will now invoke this function and build our dataset."
},
{
"code": null,
"e": 7083,
"s": 7032,
"text": "news_df = build_dataset(seed_urls)news_df.head(10)"
},
{
"code": null,
"e": 7226,
"s": 7083,
"text": "We, now, have a neatly formatted dataset of news articles and you can quickly check the total number of news articles with the following code."
},
{
"code": null,
"e": 7358,
"s": 7226,
"text": "news_df.news_category.value_counts()Output:-------world 25sports 25technology 24Name: news_category, dtype: int64"
},
{
"code": null,
"e": 8113,
"s": 7358,
"text": "There are usually multiple steps involved in cleaning and pre-processing textual data. I have covered text pre-processing in detail in Chapter 3 of ‘Text Analytics with Python’ (code is open-sourced). However, in this section, I will highlight some of the most important steps which are used heavily in Natural Language Processing (NLP) pipelines and I frequently use them in my NLP projects. We will be leveraging a fair bit of nltk and spacy, both state-of-the-art libraries in NLP. Typically a pip install <library> or a conda install <library> should suffice. However, in case you face issues with loading up spacy’s language models, feel free to follow the steps highlighted below to resolve this issue (I had faced this issue in one of my systems)."
},
{
"code": null,
"e": 8692,
"s": 8113,
"text": "# OPTIONAL: ONLY USE IF SPACY FAILS TO LOAD LANGUAGE MODEL# Use the following command to install spaCy> pip install -U spacyOR> conda install -c conda-forge spacy# Download the following language model and store it in diskhttps://github.com/explosion/spacy-models/releases/tag/en_core_web_md-2.0.0# Link the same to spacy > python -m spacy link ./spacymodels/en_core_web_md-2.0.0/en_core_web_md en_coreLinking successful ./spacymodels/en_core_web_md-2.0.0/en_core_web_md --> ./Anaconda3/lib/site-packages/spacy/data/en_coreYou can now load the model via spacy.load('en_core')"
},
{
"code": null,
"e": 8905,
"s": 8692,
"text": "Let’s now load up the necessary dependencies for text pre-processing. We will remove negation words from stop words, since we would want to keep them as they might be useful, especially during sentiment analysis."
},
{
"code": null,
"e": 9223,
"s": 8905,
"text": "❗ IMPORTANT NOTE: A lot of you have messaged me about not being able to load the contractions module. It’s not a standard python module. We leverage a standard set of contractions available in the contractions.py file in my repository.Please add it in the same directory you run your code from, else it will not work."
},
{
"code": null,
"e": 9696,
"s": 9223,
"text": "import spacyimport pandas as pdimport numpy as npimport nltkfrom nltk.tokenize.toktok import ToktokTokenizerimport refrom bs4 import BeautifulSoupfrom contractions import CONTRACTION_MAPimport unicodedatanlp = spacy.load('en_core', parse=True, tag=True, entity=True)#nlp_vec = spacy.load('en_vecs', parse = True, tag=True, #entity=True)tokenizer = ToktokTokenizer()stopword_list = nltk.corpus.stopwords.words('english')stopword_list.remove('no')stopword_list.remove('not')"
},
{
"code": null,
"e": 9925,
"s": 9696,
"text": "Often, unstructured text contains a lot of noise, especially if you use techniques like web or screen scraping. HTML tags are typically one of these components which don’t add much value towards understanding and analyzing text."
},
{
"code": null,
"e": 9947,
"s": 9925,
"text": "'Some important text'"
},
{
"code": null,
"e": 10091,
"s": 9947,
"text": "It is quite evident from the above output that we can remove unnecessary HTML tags and retain the useful textual information from any document."
},
{
"code": null,
"e": 10378,
"s": 10091,
"text": "Usually in any text corpus, you might be dealing with accented characters/letters, especially if you only want to analyze the English language. Hence, we need to make sure that these characters are converted and standardized into ASCII characters. A simple example — converting é to e."
},
{
"code": null,
"e": 10399,
"s": 10378,
"text": "'Some Accented text'"
},
{
"code": null,
"e": 10556,
"s": 10399,
"text": "The preceding function shows us how we can easily convert accented characters to normal English characters, which helps standardize the words in our corpus."
},
{
"code": null,
"e": 11041,
"s": 10556,
"text": "Contractions are shortened version of words or syllables. They often exist in either written or spoken forms in the English language. These shortened versions or contractions of words are created by removing specific letters and sounds. In case of English contractions, they are often created by removing one of the vowels from the word. Examples would be, do not to don’t and I would to I’d. Converting each contraction to its expanded, original form helps with text standardization."
},
{
"code": null,
"e": 11140,
"s": 11041,
"text": "We leverage a standard set of contractions available in the contractions.py file in my repository."
},
{
"code": null,
"e": 11191,
"s": 11140,
"text": "'You all cannot expand contractions I would think'"
},
{
"code": null,
"e": 11417,
"s": 11191,
"text": "We can see how our function helps expand the contractions from the preceding output. Are there better ways of doing this? Definitely! If we have enough examples, we can even train a deep learning model for better performance."
},
{
"code": null,
"e": 11681,
"s": 11417,
"text": "Special characters and symbols are usually non-alphanumeric characters or even occasionally numeric characters (depending on the problem), which add to the extra noise in unstructured text. Usually, simple regular expressions (regexes) can be used to remove them."
},
{
"code": null,
"e": 11720,
"s": 11681,
"text": "'Well this was fun What do you think '"
},
{
"code": null,
"e": 11827,
"s": 11720,
"text": "I’ve kept removing digits as optional, because often we might need to keep them in the pre-processed text."
},
{
"code": null,
"e": 12213,
"s": 11827,
"text": "To understand stemming, you need to gain some perspective on what word stems represent. Word stems are also known as the base form of a word, and we can create new words by attaching affixes to them in a process known as inflection. Consider the word JUMP. You can add affixes to it and form new words like JUMPS, JUMPED, and JUMPING. In this case, the base word JUMP is the word stem."
},
{
"code": null,
"e": 12722,
"s": 12213,
"text": "The figure shows how the word stem is present in all its inflections, since it forms the base on which each inflection is built upon using affixes. The reverse process of obtaining the base form of a word from its inflected form is known as stemming. Stemming helps us in standardizing words to their base or root stem, irrespective of their inflections, which helps many applications like classifying or clustering text, and even in information retrieval. Let’s see the popular Porter stemmer in action now!"
},
{
"code": null,
"e": 12781,
"s": 12722,
"text": "'My system keep crash hi crash yesterday, our crash daili'"
},
{
"code": null,
"e": 13039,
"s": 12781,
"text": "The Porter stemmer is based on the algorithm developed by its inventor, Dr. Martin Porter. Originally, the algorithm is said to have had a total of five different phases for reduction of inflections to their stems, where each phase has its own set of rules."
},
{
"code": null,
"e": 13322,
"s": 13039,
"text": "Do note that usually stemming has a fixed set of rules, hence, the root stems may not be lexicographically correct. Which means, the stemmed words may not be semantically correct, and might have a chance of not being present in the dictionary (as evident from the preceding output)."
},
{
"code": null,
"e": 13821,
"s": 13322,
"text": "Lemmatization is very similar to stemming, where we remove word affixes to get to the base form of a word. However, the base form in this case is known as the root word, but not the root stem. The difference being that the root word is always a lexicographically correct word (present in the dictionary), but the root stem may not be so. Thus, root word, also known as the lemma, will always be present in the dictionary. Both nltk and spacy have excellent lemmatizers. We will be using spacy here."
},
{
"code": null,
"e": 13885,
"s": 13821,
"text": "'My system keep crash ! his crash yesterday , ours crash daily'"
},
{
"code": null,
"e": 13991,
"s": 13885,
"text": "You can see that the semantics of the words are not affected by this, yet our text is still standardized."
},
{
"code": null,
"e": 14237,
"s": 13991,
"text": "Do note that the lemmatization process is considerably slower than stemming, because an additional step is involved where the root form or lemma is formed by removing the affix from the word if and only if the lemma is present in the dictionary."
},
{
"code": null,
"e": 14628,
"s": 14237,
"text": "Words which have little or no significance, especially when constructing meaningful features from text, are known as stopwords or stop words. These are usually words that end up having the maximum frequency if you do a simple term or word frequency in a corpus. Typically, these can be articles, conjunctions, prepositions and so on. Some examples of stopwords are a, an, the, and the like."
},
{
"code": null,
"e": 14659,
"s": 14628,
"text": "', , stopwords , computer not'"
},
{
"code": null,
"e": 14824,
"s": 14659,
"text": "There is no universal stopword list, but we use a standard English language stopwords list from nltk. You can also add your own domain-specific stopwords as needed."
},
{
"code": null,
"e": 15051,
"s": 14824,
"text": "While we can definitely keep going with more techniques like correcting spelling, grammar and so on, let’s now bring everything we learnt together and chain these operations to build a text normalizer to pre-process text data."
},
{
"code": null,
"e": 15240,
"s": 15051,
"text": "Let’s now put this function in action! We will first combine the news headline and the news article text together to form a document for each piece of news. Then, we will pre-process them."
},
{
"code": null,
"e": 16057,
"s": 15240,
"text": "{'clean_text': 'us unveils world powerful supercomputer beat china us unveil world powerful supercomputer call summit beat previous record holder china sunway taihulight peak performance trillion calculation per second twice fast sunway taihulight capable trillion calculation per second summit server reportedly take size two tennis court', 'full_text': \"US unveils world's most powerful supercomputer, beats China. The US has unveiled the world's most powerful supercomputer called 'Summit', beating the previous record-holder China's Sunway TaihuLight. With a peak performance of 200,000 trillion calculations per second, it is over twice as fast as Sunway TaihuLight, which is capable of 93,000 trillion calculations per second. Summit has 4,608 servers, which reportedly take up the size of two tennis courts.\"}"
},
{
"code": null,
"e": 16263,
"s": 16057,
"text": "Thus, you can see how our text pre-processor helps in pre-processing our news articles! After this, you can save this dataset to disk if needed, so that you can always load it up later for future analysis."
},
{
"code": null,
"e": 16321,
"s": 16263,
"text": "news_df.to_csv('news.csv', index=False, encoding='utf-8')"
},
{
"code": null,
"e": 16989,
"s": 16321,
"text": "For any language, syntax and structure usually go hand in hand, where a set of specific rules, conventions, and principles govern the way words are combined into phrases; phrases get combines into clauses; and clauses get combined into sentences. We will be talking specifically about the English language syntax and structure in this section. In English, words usually combine together to form other constituent units. These constituents include words, phrases, clauses, and sentences. Considering a sentence, “The brown fox is quick and he is jumping over the lazy dog”, it is made of a bunch of words and just looking at the words by themselves don’t tell us much."
},
{
"code": null,
"e": 17260,
"s": 16989,
"text": "Knowledge about the structure and syntax of language is helpful in many areas like text processing, annotation, and parsing for further operations such as text classification or summarization. Typical parsing techniques for understanding text syntax are mentioned below."
},
{
"code": null,
"e": 17290,
"s": 17260,
"text": "Parts of Speech (POS) Tagging"
},
{
"code": null,
"e": 17318,
"s": 17290,
"text": "Shallow Parsing or Chunking"
},
{
"code": null,
"e": 17339,
"s": 17318,
"text": "Constituency Parsing"
},
{
"code": null,
"e": 17358,
"s": 17339,
"text": "Dependency Parsing"
},
{
"code": null,
"e": 17621,
"s": 17358,
"text": "We will be looking at all of these techniques in subsequent sections. Considering our previous example sentence “The brown fox is quick and he is jumping over the lazy dog”, if we were to annotate it using basic POS tags, it would look like the following figure."
},
{
"code": null,
"e": 17718,
"s": 17621,
"text": "Thus, a sentence typically follows a hierarchical structure consisting the following components,"
},
{
"code": null,
"e": 17755,
"s": 17718,
"text": "sentence → clauses → phrases → words"
},
{
"code": null,
"e": 17949,
"s": 17755,
"text": "Parts of speech (POS) are specific lexical categories to which words are assigned, based on their syntactic context and role. Usually, words can fall into one of the following major categories."
},
{
"code": null,
"e": 18141,
"s": 17949,
"text": "N(oun): This usually denotes words that depict some object or entity, which may be living or nonliving. Some examples would be fox , dog , book , and so on. The POS tag symbol for nouns is N."
},
{
"code": null,
"e": 18465,
"s": 18141,
"text": "V(erb): Verbs are words that are used to describe certain actions, states, or occurrences. There are a wide variety of further subcategories, such as auxiliary, reflexive, and transitive verbs (and many more). Some typical examples of verbs would be running , jumping , read , and write . The POS tag symbol for verbs is V."
},
{
"code": null,
"e": 18739,
"s": 18465,
"text": "Adj(ective): Adjectives are words used to describe or qualify other words, typically nouns and noun phrases. The phrase beautiful flower has the noun (N) flower which is described or qualified using the adjective (ADJ) beautiful . The POS tag symbol for adjectives is ADJ ."
},
{
"code": null,
"e": 19055,
"s": 18739,
"text": "Adv(erb): Adverbs usually act as modifiers for other words including nouns, adjectives, verbs, or other adverbs. The phrase very beautiful flower has the adverb (ADV) very , which modifies the adjective (ADJ) beautiful , indicating the degree to which the flower is beautiful. The POS tag symbol for adverbs is ADV."
},
{
"code": null,
"e": 19448,
"s": 19055,
"text": "Besides these four major categories of parts of speech , there are other categories that occur frequently in the English language. These include pronouns, prepositions, interjections, conjunctions, determiners, and many others. Furthermore, each POS tag like the noun (N) can be further subdivided into categories like singular nouns (NN), singular proper nouns (NNP), and plural nouns (NNS)."
},
{
"code": null,
"e": 19900,
"s": 19448,
"text": "The process of classifying and labeling POS tags for words called parts of speech tagging or POS tagging . POS tags are used to annotate words and depict their POS, which is really helpful to perform specific analysis, such as narrowing down upon nouns and seeing which ones are the most prominent, word sense disambiguation, and grammar analysis. We will be leveraging both nltk and spacy which usually use the Penn Treebank notation for POS tagging."
},
{
"code": null,
"e": 20078,
"s": 19900,
"text": "We can see that each of these libraries treat tokens in their own way and assign specific tags for them. Based on what we see, spacy seems to be doing slightly better than nltk."
},
{
"code": null,
"e": 20199,
"s": 20078,
"text": "Based on the hierarchy we depicted earlier, groups of words make up phrases. There are five major categories of phrases:"
},
{
"code": null,
"e": 20322,
"s": 20199,
"text": "Noun phrase (NP): These are phrases where a noun acts as the head word. Noun phrases act as a subject or object to a verb."
},
{
"code": null,
"e": 20581,
"s": 20322,
"text": "Verb phrase (VP): These phrases are lexical units that have a verb acting as the head word. Usually, there are two forms of verb phrases. One form has the verb components as well as other entities such as nouns, adjectives, or adverbs as parts of the object."
},
{
"code": null,
"e": 20804,
"s": 20581,
"text": "Adjective phrase (ADJP): These are phrases with an adjective as the head word. Their main role is to describe or qualify nouns and pronouns in a sentence, and they will be either placed before or after the noun or pronoun."
},
{
"code": null,
"e": 21048,
"s": 20804,
"text": "Adverb phrase (ADVP): These phrases act like adverbs since the adverb acts as the head word in the phrase. Adverb phrases are used as modifiers for nouns, verbs, or adverbs themselves by providing further details that describe or qualify them."
},
{
"code": null,
"e": 21271,
"s": 21048,
"text": "Prepositional phrase (PP): These phrases usually contain a preposition as the head word and other lexical components like nouns, pronouns, and so on. These act like an adjective or adverb describing other words or phrases."
},
{
"code": null,
"e": 21613,
"s": 21271,
"text": "Shallow parsing, also known as light parsing or chunking , is a popular natural language processing technique of analyzing the structure of a sentence to break it down into its smallest constituents (which are tokens such as words) and group them together into higher-level phrases. This includes POS tags as well as phrases from a sentence."
},
{
"code": null,
"e": 21862,
"s": 21613,
"text": "We will leverage the conll2000 corpus for training our shallow parser model. This corpus is available in nltk with chunk annotations and we will be using around 10K records for training our model. A sample annotated sentence is depicted as follows."
},
{
"code": null,
"e": 22192,
"s": 21862,
"text": "10900 48(S Chancellor/NNP (PP of/IN) (NP the/DT Exchequer/NNP) (NP Nigel/NNP Lawson/NNP) (NP 's/POS restated/VBN commitment/NN) (PP to/TO) (NP a/DT firm/NN monetary/JJ policy/NN) (VP has/VBZ helped/VBN to/TO prevent/VB) (NP a/DT freefall/NN) (PP in/IN) (NP sterling/NN) (PP over/IN) (NP the/DT past/JJ week/NN) ./.)"
},
{
"code": null,
"e": 22664,
"s": 22192,
"text": "From the preceding output, you can see that our data points are sentences that are already annotated with phrases and POS tags metadata that will be useful in training our shallow parser model. We will leverage two chunking utility functions, tree2conlltags , to get triples of word, tag, and chunk tags for each token, and conlltags2tree to generate a parse tree from these token triples. We will be using these functions to train our parser. A sample is depicted below."
},
{
"code": null,
"e": 23335,
"s": 22664,
"text": "[('Chancellor', 'NNP', 'O'), ('of', 'IN', 'B-PP'), ('the', 'DT', 'B-NP'), ('Exchequer', 'NNP', 'I-NP'), ('Nigel', 'NNP', 'B-NP'), ('Lawson', 'NNP', 'I-NP'), (\"'s\", 'POS', 'B-NP'), ('restated', 'VBN', 'I-NP'), ('commitment', 'NN', 'I-NP'), ('to', 'TO', 'B-PP'), ('a', 'DT', 'B-NP'), ('firm', 'NN', 'I-NP'), ('monetary', 'JJ', 'I-NP'), ('policy', 'NN', 'I-NP'), ('has', 'VBZ', 'B-VP'), ('helped', 'VBN', 'I-VP'), ('to', 'TO', 'I-VP'), ('prevent', 'VB', 'I-VP'), ('a', 'DT', 'B-NP'), ('freefall', 'NN', 'I-NP'), ('in', 'IN', 'B-PP'), ('sterling', 'NN', 'B-NP'), ('over', 'IN', 'B-PP'), ('the', 'DT', 'B-NP'), ('past', 'JJ', 'I-NP'), ('week', 'NN', 'I-NP'), ('.', '.', 'O')]"
},
{
"code": null,
"e": 23744,
"s": 23335,
"text": "The chunk tags use the IOB format. This notation represents Inside, Outside, and Beginning. The B- prefix before a tag indicates it is the beginning of a chunk, and I- prefix indicates that it is inside a chunk. The O tag indicates that the token does not belong to any chunk. The B- tag is always used when there are subsequent tags of the same type following it without the presence of O tags between them."
},
{
"code": null,
"e": 23986,
"s": 23744,
"text": "We will now define a function conll_tag_ chunks() to extract POS and chunk tags from sentences with chunked annotations and a function called combined_taggers() to train multiple taggers with backoff taggers (e.g. unigram and bigram taggers)"
},
{
"code": null,
"e": 24285,
"s": 23986,
"text": "We will now define a class NGramTagChunker that will take in tagged sentences as training input, get their (word, POS tag, Chunk tag) WTC triples, and train a BigramTagger with a UnigramTagger as the backoff tagger. We will also define a parse() function to perform shallow parsing on new sentences"
},
{
"code": null,
"e": 24506,
"s": 24285,
"text": "The UnigramTagger , BigramTagger , and TrigramTagger are classes that inherit from the base class NGramTagger , which itself inherits from the ContextTagger class , which inherits from the SequentialBackoffTagger class ."
},
{
"code": null,
"e": 24626,
"s": 24506,
"text": "We will use this class to train on the conll2000 chunked train_data and evaluate the model performance on the test_data"
},
{
"code": null,
"e": 24744,
"s": 24626,
"text": "ChunkParse score: IOB Accuracy: 90.0%% Precision: 82.1%% Recall: 86.3%% F-Measure: 84.1%%"
},
{
"code": null,
"e": 24991,
"s": 24744,
"text": "Our chunking model gets an accuracy of around 90% which is quite good! Let’s now leverage this model to shallow parse and chunk our sample news article headline which we used earlier, “US unveils world’s most powerful supercomputer, beats China”."
},
{
"code": null,
"e": 25173,
"s": 24991,
"text": "chunk_tree = ntc.parse(nltk_pos_tagged)print(chunk_tree)Output:-------(S (NP US/NNP) (VP unveils/VBZ world's/VBZ) (NP most/RBS powerful/JJ supercomputer,/JJ beats/NNS China/NNP))"
},
{
"code": null,
"e": 25444,
"s": 25173,
"text": "Thus you can see it has identified two noun phrases (NP) and one verb phrase (VP) in the news article. Each word’s POS tags are also visible. We can also visualize this in the form of a tree as follows. You might need to install ghostscript in case nltk throws an error."
},
{
"code": null,
"e": 25538,
"s": 25444,
"text": "The preceding output gives a good sense of structure after shallow parsing the news headline."
},
{
"code": null,
"e": 25982,
"s": 25538,
"text": "Constituent-based grammars are used to analyze and determine the constituents of a sentence. These grammars can be used to model or represent the internal structure of sentences in terms of a hierarchically ordered structure of their constituents. Each and every word usually belongs to a specific lexical category in the case and forms the head word of different phrases. These phrases are formed based on rules called phrase structure rules."
},
{
"code": null,
"e": 26214,
"s": 25982,
"text": "Phrase structure rules form the core of constituency grammars, because they talk about syntax and rules that govern the hierarchy and ordering of the various constituents in the sentences. These rules cater to two things primarily."
},
{
"code": null,
"e": 26291,
"s": 26214,
"text": "They determine what words are used to construct the phrases or constituents."
},
{
"code": null,
"e": 26356,
"s": 26291,
"text": "They determine how we need to order these constituents together."
},
{
"code": null,
"e": 26966,
"s": 26356,
"text": "The generic representation of a phrase structure rule is S → AB , which depicts that the structure S consists of constituents A and B , and the ordering is A followed by B . While there are several rules (refer to Chapter 1, Page 19: Text Analytics with Python, if you want to dive deeper), the most important rule describes how to divide a sentence or a clause. The phrase structure rule denotes a binary division for a sentence or a clause as S → NP VP where S is the sentence or clause, and it is divided into the subject, denoted by the noun phrase (NP) and the predicate, denoted by the verb phrase (VP)."
},
{
"code": null,
"e": 27233,
"s": 26966,
"text": "A constituency parser can be built based on such grammars/rules, which are usually collectively available as context-free grammar (CFG) or phrase-structured grammar. The parser will process input sentences according to these rules, and help in building a parse tree."
},
{
"code": null,
"e": 27308,
"s": 27233,
"text": "We will be using nltk and the StanfordParser here to generate parse trees."
},
{
"code": null,
"e": 27663,
"s": 27308,
"text": "Prerequisites: Download the official Stanford Parser from here, which seems to work quite well. You can try out a later version by going to this website and checking the Release History section. After downloading, unzip it to a known location in your filesystem. Once done, you are now ready to use the parser from nltk , which we will be exploring soon."
},
{
"code": null,
"e": 27999,
"s": 27663,
"text": "The Stanford parser generally uses a PCFG (probabilistic context-free grammar) parser. A PCFG is a context-free grammar that associates a probability with each of its production rules. The probability of a parse tree generated from a PCFG is simply the production of the individual probabilities of the productions used to generate it."
},
{
"code": null,
"e": 28235,
"s": 27999,
"text": "(ROOT (SINV (S (NP (NNP US)) (VP (VBZ unveils) (NP (NP (NN world) (POS 's)) (ADJP (RBS most) (JJ powerful)) (NN supercomputer)))) (, ,) (VP (VBZ beats)) (NP (NNP China))))"
},
{
"code": null,
"e": 28352,
"s": 28235,
"text": "We can see the constituency parse tree for our news headline. Let’s visualize it to understand the structure better."
},
{
"code": null,
"e": 28406,
"s": 28352,
"text": "from IPython.display import displaydisplay(result[0])"
},
{
"code": null,
"e": 28773,
"s": 28406,
"text": "We can see the nested hierarchical structure of the constituents in the preceding output as compared to the flat structure in shallow parsing. In case you are wondering what SINV means, it represents an Inverted declarative sentence, i.e. one in which the subject follows the tensed verb or modal. Refer to the Penn Treebank reference as needed to lookup other tags."
},
{
"code": null,
"e": 29368,
"s": 28773,
"text": "In dependency parsing, we try to use dependency-based grammars to analyze and infer both structure and semantic dependencies and relationships between tokens in a sentence. The basic principle behind a dependency grammar is that in any sentence in the language, all words except one, have some relationship or dependency on other words in the sentence. The word that has no dependency is called the root of the sentence. The verb is taken as the root of the sentence in most cases. All the other words are directly or indirectly linked to the root verb using links , which are the dependencies."
},
{
"code": null,
"e": 29542,
"s": 29368,
"text": "Considering our sentence “The brown fox is quick and he is jumping over the lazy dog” , if we wanted to draw the dependency syntax tree for this, we would have the structure"
},
{
"code": null,
"e": 29870,
"s": 29542,
"text": "These dependency relationships each have their own meaning and are a part of a list of universal dependency types. This is discussed in an original paper, Universal Stanford Dependencies: A Cross-Linguistic Typology by de Marneffe et al, 2014). You can check out the exhaustive list of dependency types and their meanings here."
},
{
"code": null,
"e": 29951,
"s": 29870,
"text": "If we observe some of these dependencies, it is not too hard to understand them."
},
{
"code": null,
"e": 30203,
"s": 29951,
"text": "The dependency tag det is pretty intuitive — it denotes the determiner relationship between a nominal head and the determiner. Usually, the word with POS tag DET will also have the det dependency tag relation. Examples include fox → the and dog → the."
},
{
"code": null,
"e": 30369,
"s": 30203,
"text": "The dependency tag amod stands for adjectival modifier and stands for any adjective that modifies the meaning of a noun. Examples include fox → brown and dog → lazy."
},
{
"code": null,
"e": 30504,
"s": 30369,
"text": "The dependency tag nsubj stands for an entity that acts as a subject or agent in a clause. Examples include is → fox and jumping → he."
},
{
"code": null,
"e": 30665,
"s": 30504,
"text": "The dependencies cc and conj have more to do with linkages related to words connected by coordinating conjunctions . Examples include is → and and is → jumping."
},
{
"code": null,
"e": 30768,
"s": 30665,
"text": "The dependency tag aux indicates the auxiliary or secondary verb in the clause. Example: jumping → is."
},
{
"code": null,
"e": 30909,
"s": 30768,
"text": "The dependency tag acomp stands for adjective complement and acts as the complement or object to a verb in the sentence. Example: is → quick"
},
{
"code": null,
"e": 31166,
"s": 30909,
"text": "The dependency tag prep denotes a prepositional modifier, which usually modifies the meaning of a noun, verb, adjective, or preposition. Usually, this representation is used for prepositions having a noun or noun phrase complement. Example: jumping → over."
},
{
"code": null,
"e": 31342,
"s": 31166,
"text": "The dependency tag pobj is used to denote the object of a preposition . This is usually the head of a noun phrase following a preposition in the sentence. Example: over → dog."
},
{
"code": null,
"e": 31696,
"s": 31342,
"text": "Spacy had two types of English dependency parsers based on what language models you use, you can find more details here. Based on language models, you can use the Universal Dependencies Scheme or the CLEAR Style Dependency Scheme also available in NLP4J now. We will now leverage spacy and print out the dependencies for each token in our news headline."
},
{
"code": null,
"e": 32091,
"s": 31696,
"text": "[]<---US[compound]--->[]--------['US']<---unveils[nsubj]--->['supercomputer', ',']--------[]<---world[poss]--->[\"'s\"]--------[]<---'s[case]--->[]--------[]<---most[amod]--->[]--------[]<---powerful[compound]--->[]--------['world', 'most', 'powerful']<---supercomputer[appos]--->[]--------[]<---,[punct]--->[]--------['unveils']<---beats[ROOT]--->['China']--------[]<---China[dobj]--->[]--------"
},
{
"code": null,
"e": 32369,
"s": 32091,
"text": "It is evident that the verb beats is the ROOT since it doesn’t have any other dependencies as compared to the other tokens. For knowing more about each annotation you can always refer to the CLEAR dependency scheme. We can also visualize the above dependencies in a better way."
},
{
"code": null,
"e": 32556,
"s": 32369,
"text": "You can also leverage nltk and the StanfordDependencyParser to visualize and build out the dependency tree. We showcase the dependency tree both in its raw and annotated form as follows."
},
{
"code": null,
"e": 32628,
"s": 32556,
"text": "(beats (unveils US (supercomputer (world 's) (powerful most))) China)"
},
{
"code": null,
"e": 32790,
"s": 32628,
"text": "You can notice the similarities with the tree we had obtained earlier. The annotations help with understanding the type of dependency among the different tokens."
},
{
"code": null,
"e": 33460,
"s": 32790,
"text": "In any text document, there are particular terms that represent specific entities that are more informative and have a unique context. These entities are known as named entities , which more specifically refer to terms that represent real-world objects like people, places, organizations, and so on, which are often denoted by proper names. A naive approach could be to find these by looking at the noun phrases in text documents. Named entity recognition (NER) , also known as entity chunking/extraction , is a popular technique used in information extraction to identify and segment the named entities and classify or categorize them under various predefined classes."
},
{
"code": null,
"e": 33585,
"s": 33460,
"text": "SpaCy has some excellent capabilities for named entity recognition. Let’s try and use it on one of our sample news articles."
},
{
"code": null,
"e": 33829,
"s": 33585,
"text": "[(US, 'GPE'), (China, 'GPE'), (US, 'GPE'), (China, 'GPE'), (Sunway, 'ORG'), (TaihuLight, 'ORG'), (200,000, 'CARDINAL'), (second, 'ORDINAL'), (Sunway, 'ORG'), (TaihuLight, 'ORG'), (93,000, 'CARDINAL'), (4,608, 'CARDINAL'), (two, 'CARDINAL')]"
},
{
"code": null,
"e": 34059,
"s": 33829,
"text": "We can clearly see that the major named entities have been identified by spacy. To understand more in detail about what each named entity means, you can refer to the documentation or check out the following table for convenience."
},
{
"code": null,
"e": 34240,
"s": 34059,
"text": "Let’s now find out the most frequent named entities in our news corpus! For this, we will build out a data frame of all the named entities and their types using the following code."
},
{
"code": null,
"e": 34336,
"s": 34240,
"text": "We can now transform and aggregate this data frame to find the top occuring entities and types."
},
{
"code": null,
"e": 34522,
"s": 34336,
"text": "Do you notice anything interesting? (Hint: Maybe the supposed summit between Trump and Kim Jong!). We also see that it has correctly identified ‘Messenger’ as a product (from Facebook)."
},
{
"code": null,
"e": 34631,
"s": 34522,
"text": "We can also group by the entity types to get a sense of what types of entites occur most in our news corpus."
},
{
"code": null,
"e": 34767,
"s": 34631,
"text": "We can see that people, places and organizations are the most mentioned entities though interestingly we also have many other entities."
},
{
"code": null,
"e": 35014,
"s": 34767,
"text": "Another nice NER tagger is the StanfordNERTagger available from the nltk interface. For this, you need to have Java installed and then download the Stanford NER resources. Unzip them to a location of your choice (I used E:/stanford in my system)."
},
{
"code": null,
"e": 35441,
"s": 35014,
"text": "Stanford’s Named Entity Recognizer is based on an implementation of linear chain Conditional Random Field (CRF) sequence models. Unfortunately this model is only trained on instances of PERSON, ORGANIZATION and LOCATION types. Following code can be used as a standard workflow which helps us extract the named entities using this tagger and show the top named entities and their types (extraction differs slightly from spacy)."
},
{
"code": null,
"e": 35611,
"s": 35441,
"text": "We notice quite similar results though restricted to only three types of named entities. Interestingly, we see a number of mentioned of several people in various sports."
},
{
"code": null,
"e": 36162,
"s": 35611,
"text": "Sentiment analysis is perhaps one of the most popular applications of NLP, with a vast number of tutorials, courses, and applications that focus on analyzing sentiments of diverse datasets ranging from corporate surveys to movie reviews. The key aspect of sentiment analysis is to analyze a body of text for understanding the opinion expressed by it. Typically, we quantify this sentiment with a positive or negative value, called polarity. The overall sentiment is often inferred as positive, neutral or negative from the sign of the polarity score."
},
{
"code": null,
"e": 36786,
"s": 36162,
"text": "Usually, sentiment analysis works best on text that has a subjective context than on text with only an objective context. Objective text usually depicts some normal statements or facts without expressing any emotion, feelings, or mood. Subjective text contains text that is usually expressed by a human having typical moods, emotions, and feelings. Sentiment analysis is widely used, especially as a part of social media analysis for any domain, be it a business, a recent movie, or a product launch, to understand its reception by the people and what they think of it based on their opinions or, you guessed it, sentiment!"
},
{
"code": null,
"e": 37156,
"s": 36786,
"text": "Typically, sentiment analysis for text data can be computed on several levels, including on an individual sentence level, paragraph level, or the entire document as a whole. Often, sentiment is computed on the document as a whole or some aggregations are done after computing the sentiment for individual sentences. There are two major approaches to sentiment analysis."
},
{
"code": null,
"e": 37212,
"s": 37156,
"text": "Supervised machine learning or deep learning approaches"
},
{
"code": null,
"e": 37250,
"s": 37212,
"text": "Unsupervised lexicon-based approaches"
},
{
"code": null,
"e": 38397,
"s": 37250,
"text": "For the first approach we typically need pre-labeled data. Hence, we will be focusing on the second approach. For a comprehensive coverage of sentiment analysis, refer to Chapter 7: Analyzing Movie Reviews Sentiment, Practical Machine Learning with Python, Springer\\Apress, 2018. In this scenario, we do not have the convenience of a well-labeled training dataset. Hence, we will need to use unsupervised techniques for predicting the sentiment by using knowledgebases, ontologies, databases, and lexicons that have detailed information, specially curated and prepared just for sentiment analysis. A lexicon is a dictionary, vocabulary, or a book of words. In our case, lexicons are special dictionaries or vocabularies that have been created for analyzing sentiments. Most of these lexicons have a list of positive and negative polar words with some score associated with them, and using various techniques like the position of words, surrounding words, context, parts of speech, phrases, and so on, scores are assigned to the text documents for which we want to compute the sentiment. After aggregating these scores, we get the final sentiment."
},
{
"code": null,
"e": 38480,
"s": 38397,
"text": "Various popular lexicons are used for sentiment analysis, including the following."
},
{
"code": null,
"e": 38494,
"s": 38480,
"text": "AFINN lexicon"
},
{
"code": null,
"e": 38513,
"s": 38494,
"text": "Bing Liu’s lexicon"
},
{
"code": null,
"e": 38539,
"s": 38513,
"text": "MPQA subjectivity lexicon"
},
{
"code": null,
"e": 38552,
"s": 38539,
"text": "SentiWordNet"
},
{
"code": null,
"e": 38566,
"s": 38552,
"text": "VADER lexicon"
},
{
"code": null,
"e": 38583,
"s": 38566,
"text": "TextBlob lexicon"
},
{
"code": null,
"e": 38870,
"s": 38583,
"text": "This is not an exhaustive list of lexicons that can be leveraged for sentiment analysis, and there are several other lexicons which can be easily obtained from the Internet. Feel free to check out each of these links and explore them. We will be covering two techniques in this section."
},
{
"code": null,
"e": 39612,
"s": 38870,
"text": "The AFINN lexicon is perhaps one of the simplest and most popular lexicons that can be used extensively for sentiment analysis. Developed and curated by Finn Årup Nielsen, you can find more details on this lexicon in the paper, “A new ANEW: evaluation of a word list for sentiment analysis in microblogs”, proceedings of the ESWC 2011 Workshop. The current version of the lexicon is AFINN-en-165. txt and it contains over 3,300+ words with a polarity score associated with each word. You can find this lexicon at the author’s official GitHub repository along with previous versions of it, including AFINN-111. The author has also created a nice wrapper library on top of this in Python called afinn, which we will be using for our analysis."
},
{
"code": null,
"e": 39745,
"s": 39612,
"text": "The following code computes sentiment for all our news articles and shows summary statistics of general sentiment per news category."
},
{
"code": null,
"e": 39972,
"s": 39745,
"text": "We can get a good idea of general sentiment statistics across different news categories. Looks like the average sentiment is very positive in sports and reasonably negative in technology! Let’s look at some visualizations now."
},
{
"code": null,
"e": 40206,
"s": 39972,
"text": "We can see that the spread of sentiment polarity is much higher in sports and world as compared to technology where a lot of the articles seem to be having a negative polarity. We can also visualize the frequency of sentiment labels."
},
{
"code": null,
"e": 40616,
"s": 40206,
"text": "No surprises here that technology has the most number of negative articles and world the most number of positive articles. Sports might have more neutral articles due to the presence of articles which are more objective in nature (talking about sporting events without the presence of any emotion or feelings). Let’s dive deeper into the most positive and negative sentiment news articles for technology news."
},
{
"code": null,
"e": 40848,
"s": 40616,
"text": "Looks like the most negative article is all about a recent smartphone scam in India and the most positive article is about a contest to get married in a self-driving shuttle. Interesting! Let’s do a similar analysis for world news."
},
{
"code": null,
"e": 41118,
"s": 40848,
"text": "Interestingly Trump features in both the most positive and the most negative world news articles. Do read the articles to get some more perspective into why the model selected one of them as the most negative and the other one as the most positive (no surprises here!)."
},
{
"code": null,
"e": 41737,
"s": 41118,
"text": "TextBlob is another excellent open-source library for performing NLP tasks with ease, including sentiment analysis. It also an a sentiment lexicon (in the form of an XML file) which it leverages to give both polarity and subjectivity scores. Typically, the scores have a normalized scale as compare to Afinn. The polarity score is a float within the range [-1.0, 1.0]. The subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. Let’s use this now to get the sentiment polarity and labels for each news article and aggregate the summary statistics per news category."
},
{
"code": null,
"e": 42003,
"s": 41737,
"text": "Looks like the average sentiment is the most positive in world and least positive in technology! However, these metrics might be indicating that the model is predicting more articles as positive. Let’s look at the sentiment frequency distribution per news category."
},
{
"code": null,
"e": 42400,
"s": 42003,
"text": "There definitely seems to be more positive articles across the news categories here as compared to our previous model. However, still looks like technology has the most negative articles and world, the most positive articles similar to our previous analysis. Let’s now do a comparative analysis and see if we still get similar articles in the most positive and negative categories for world news."
},
{
"code": null,
"e": 42602,
"s": 42400,
"text": "Well, looks like the most negative world news article here is even more depressing than what we saw the last time! The most positive article is still the same as what we had obtained in our last model."
},
{
"code": null,
"e": 42866,
"s": 42602,
"text": "Finally, we can even evaluate and compare between these two models as to how many predictions are matching and how many are not (by leveraging a confusion matrix which is often used in classification). We leverage our nifty model_evaluation_utils module for this."
},
{
"code": null,
"e": 43218,
"s": 42866,
"text": "In the preceding table, the ‘Actual’ labels are predictions from the Afinn sentiment analyzer and the ‘Predicted’ labels are predictions from TextBlob. Looks like our previous assumption was correct. TextBlob definitely predicts several neutral and negative articles as positive. Overall most of the sentiment predictions seem to match, which is good!"
},
{
"code": null,
"e": 43730,
"s": 43218,
"text": "This was definitely one of my longer articles! If you are reading this, I really commend your efforts for staying with me till the end of this article. These examples should give you a good idea about how to start working with a corpus of text documents and popular strategies for text retrieval, pre-processing, parsing, understanding structure, entities and sentiment. We will be covering feature engineering and representation techniques with hands-on examples in the next article of this series. Stay tuned!"
},
{
"code": null,
"e": 43808,
"s": 43730,
"text": "All the code and datasets used in this article can be accessed from my GitHub"
},
{
"code": null,
"e": 43857,
"s": 43808,
"text": "The code is also available as a Jupyter notebook"
},
{
"code": null,
"e": 44133,
"s": 43857,
"text": "I often mentor and help students at Springboard to learn essential skills around Data Science. Thanks to them for helping me develop this content. Do check out Springboard’s DSC bootcamp if you are interested in a career-focused structured path towards learning Data Science."
},
{
"code": null,
"e": 44153,
"s": 44133,
"text": "www.springboard.com"
},
{
"code": null,
"e": 44359,
"s": 44153,
"text": "A lot of this code comes from the research and work that I had done during writing my book “Text Analytics with Python”. The code is open-sourced on GitHub. (Python 3.x edition coming by end of this year!)"
},
{
"code": null,
"e": 44376,
"s": 44359,
"text": "www.springer.com"
},
{
"code": null,
"e": 44555,
"s": 44376,
"text": "“Practical Machine Learning with Python”, my other book also covers text classification and sentiment analysis in detail. The code is open-sourced on GitHub for your convenience."
},
{
"code": null,
"e": 44572,
"s": 44555,
"text": "www.springer.com"
},
{
"code": null,
"e": 44751,
"s": 44572,
"text": "If you have any feedback, comments or interesting insights to share about my article or data science in general, feel free to reach out to me on my LinkedIn social media channel."
},
{
"code": null,
"e": 44768,
"s": 44751,
"text": "www.linkedin.com"
}
] |
Longest Palindromic Substring in Python
|
Suppose we have a string S. We have to find the longest palindromic substring in S. We are assuming that the length of the string S is 1000. So if the string is “BABAC”, then the longest palindromic substring is “BAB”.
To solve this, we will follow these steps
Define one square matrix of order same as the length of string, and fill it with False
Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1
start := 0
for l in range 2 to length of S + 1for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
end := i + l
if l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i
if S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i
DP[i, end - 1] = True, max_len := l, and start := i
otherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
if S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
DP[i, end - 1] = True, max_len := l, and start := i
return a substring of from index start to start + max_len
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def longestPalindrome(self, s):
dp = [[False for i in range(len(s))] for i in range(len(s))]
for i in range(len(s)):
dp[i][i] = True
max_length = 1
start = 0
for l in range(2,len(s)+1):
for i in range(len(s)-l+1):
end = i+l
if l==2:
if s[i] == s[end-1]:
dp[i][end-1]=True
max_length = l
start = i
else:
if s[i] == s[end-1] and dp[i+1][end-2]:
dp[i][end-1]=True
max_length = l
start = i
return s[start:start+max_length]
ob1 = Solution()
print(ob1.longestPalindrome("ABBABBC"))
"ABBABBC"
"BBABB"
|
[
{
"code": null,
"e": 1281,
"s": 1062,
"text": "Suppose we have a string S. We have to find the longest palindromic substring in S. We are assuming that the length of the string S is 1000. So if the string is “BABAC”, then the longest palindromic substring is “BAB”."
},
{
"code": null,
"e": 1323,
"s": 1281,
"text": "To solve this, we will follow these steps"
},
{
"code": null,
"e": 1410,
"s": 1323,
"text": "Define one square matrix of order same as the length of string, and fill it with False"
},
{
"code": null,
"e": 1500,
"s": 1410,
"text": "Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1"
},
{
"code": null,
"e": 1511,
"s": 1500,
"text": "start := 0"
},
{
"code": null,
"e": 1798,
"s": 1511,
"text": "for l in range 2 to length of S + 1for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i"
},
{
"code": null,
"e": 2050,
"s": 1798,
"text": "for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i"
},
{
"code": null,
"e": 2063,
"s": 2050,
"text": "end := i + l"
},
{
"code": null,
"e": 2155,
"s": 2063,
"text": "if l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i"
},
{
"code": null,
"e": 2233,
"s": 2155,
"text": "if S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i"
},
{
"code": null,
"e": 2285,
"s": 2233,
"text": "DP[i, end - 1] = True, max_len := l, and start := i"
},
{
"code": null,
"e": 2395,
"s": 2285,
"text": "otherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i"
},
{
"code": null,
"e": 2496,
"s": 2395,
"text": "if S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i"
},
{
"code": null,
"e": 2548,
"s": 2496,
"text": "DP[i, end - 1] = True, max_len := l, and start := i"
},
{
"code": null,
"e": 2606,
"s": 2548,
"text": "return a substring of from index start to start + max_len"
},
{
"code": null,
"e": 2676,
"s": 2606,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2687,
"s": 2676,
"text": " Live Demo"
},
{
"code": null,
"e": 3418,
"s": 2687,
"text": "class Solution(object):\n def longestPalindrome(self, s):\n dp = [[False for i in range(len(s))] for i in range(len(s))]\n for i in range(len(s)):\n dp[i][i] = True\n max_length = 1\n start = 0\n for l in range(2,len(s)+1):\n for i in range(len(s)-l+1):\n end = i+l\n if l==2:\n if s[i] == s[end-1]:\n dp[i][end-1]=True\n max_length = l\n start = i\n else:\n if s[i] == s[end-1] and dp[i+1][end-2]:\n dp[i][end-1]=True\n max_length = l\n start = i\n return s[start:start+max_length]\nob1 = Solution()\nprint(ob1.longestPalindrome(\"ABBABBC\"))"
},
{
"code": null,
"e": 3428,
"s": 3418,
"text": "\"ABBABBC\""
},
{
"code": null,
"e": 3436,
"s": 3428,
"text": "\"BBABB\""
}
] |
Easy Interactive Plot — Pandas plotly backend | by Cornellius Yudha Wijaya | Towards Data Science
|
Pandas offer an easy way to explore data (EDA). One example is how we could create a plot just from the Pandas Series or Data Frame without importing any visualization module. Here I show you in the case below.
#I only use seaborn to import sample datasetimport pandas as pd, seaborn as snstips = sns.load_dataset('tips')tips['tip'].plot(kind = 'hist')
Just by using .plot attribute, we could produce a matplotlib plot by default. Although, in this article what I would show is how we could create an interactive plotly plot with a similar line as above. The example result is shown below.
If you want to learn more about EDA with Pandas, there is an article by Pararawendy Indarjo here that nicely covers what you could do with Pandas, Still, in this article, I would only focus on creating an interactive plot.
Plotly is a module that improves any visualization to become more interactive. On 26 May 2020, Plotly release version 4.8.0 which supports Pandas plotting. This is a new feature that I personally excited to use. The backend is plotly-express powered, which is another package within plotly to create a fast, interactive plot. Below is an example of plotly express usage during data analysis.
import plotly.express as pxfig = px.histogram(tips['tip'])fig.show()
Now rather than importing the plotly.express, Plotly Version 4.8.0 has provided a backend to use it in the Pandas Series or Data Frame. To implement this, you need to install the Plotly module first.
#If you never install Plotlypip install plotly#If you have install Plotly previouslypip install -U plotly
With the Plotly module installed, we need to set up the environment first by using the following code.
pd.options.plotting.backend = "plotly"
With that, we already change our pandas plot backend from the default matplotlib to the plotly module. Let us try various plots we could create.
Scatter Plot
tips.plot.scatter(x = 'tip', y='total_bill')
Box Plot
tips['tip'].plot.box()
Horizontal Bar Plot
#The y axis in the Plotly bar plot is the index, that is why I set up another column as the indextips.set_index('sex')['size'].plot.barh()
Facet Plot
tips[['tip', 'smoker']].plot.box(facet_col = 'smoker')
That is a few plots that supported through Pandas Plotly Backend. To be precise, currently only scatter, line, area, bar, barh, hist and box plot is available. If you want to read more about it, you could refer to the documentation here.
In this article, I just show how to create an easy interactive plot using Plotly from Pandas Series and Data Frame. This feature is still brand new at the time of this article creation, but I am sure in the future, the function would implement many more plots that we could use.
If you are not subscribed as a Medium Member, please consider subscribing through my referral.
|
[
{
"code": null,
"e": 383,
"s": 172,
"text": "Pandas offer an easy way to explore data (EDA). One example is how we could create a plot just from the Pandas Series or Data Frame without importing any visualization module. Here I show you in the case below."
},
{
"code": null,
"e": 525,
"s": 383,
"text": "#I only use seaborn to import sample datasetimport pandas as pd, seaborn as snstips = sns.load_dataset('tips')tips['tip'].plot(kind = 'hist')"
},
{
"code": null,
"e": 762,
"s": 525,
"text": "Just by using .plot attribute, we could produce a matplotlib plot by default. Although, in this article what I would show is how we could create an interactive plotly plot with a similar line as above. The example result is shown below."
},
{
"code": null,
"e": 985,
"s": 762,
"text": "If you want to learn more about EDA with Pandas, there is an article by Pararawendy Indarjo here that nicely covers what you could do with Pandas, Still, in this article, I would only focus on creating an interactive plot."
},
{
"code": null,
"e": 1377,
"s": 985,
"text": "Plotly is a module that improves any visualization to become more interactive. On 26 May 2020, Plotly release version 4.8.0 which supports Pandas plotting. This is a new feature that I personally excited to use. The backend is plotly-express powered, which is another package within plotly to create a fast, interactive plot. Below is an example of plotly express usage during data analysis."
},
{
"code": null,
"e": 1446,
"s": 1377,
"text": "import plotly.express as pxfig = px.histogram(tips['tip'])fig.show()"
},
{
"code": null,
"e": 1646,
"s": 1446,
"text": "Now rather than importing the plotly.express, Plotly Version 4.8.0 has provided a backend to use it in the Pandas Series or Data Frame. To implement this, you need to install the Plotly module first."
},
{
"code": null,
"e": 1752,
"s": 1646,
"text": "#If you never install Plotlypip install plotly#If you have install Plotly previouslypip install -U plotly"
},
{
"code": null,
"e": 1855,
"s": 1752,
"text": "With the Plotly module installed, we need to set up the environment first by using the following code."
},
{
"code": null,
"e": 1894,
"s": 1855,
"text": "pd.options.plotting.backend = \"plotly\""
},
{
"code": null,
"e": 2039,
"s": 1894,
"text": "With that, we already change our pandas plot backend from the default matplotlib to the plotly module. Let us try various plots we could create."
},
{
"code": null,
"e": 2052,
"s": 2039,
"text": "Scatter Plot"
},
{
"code": null,
"e": 2097,
"s": 2052,
"text": "tips.plot.scatter(x = 'tip', y='total_bill')"
},
{
"code": null,
"e": 2106,
"s": 2097,
"text": "Box Plot"
},
{
"code": null,
"e": 2129,
"s": 2106,
"text": "tips['tip'].plot.box()"
},
{
"code": null,
"e": 2149,
"s": 2129,
"text": "Horizontal Bar Plot"
},
{
"code": null,
"e": 2288,
"s": 2149,
"text": "#The y axis in the Plotly bar plot is the index, that is why I set up another column as the indextips.set_index('sex')['size'].plot.barh()"
},
{
"code": null,
"e": 2299,
"s": 2288,
"text": "Facet Plot"
},
{
"code": null,
"e": 2354,
"s": 2299,
"text": "tips[['tip', 'smoker']].plot.box(facet_col = 'smoker')"
},
{
"code": null,
"e": 2592,
"s": 2354,
"text": "That is a few plots that supported through Pandas Plotly Backend. To be precise, currently only scatter, line, area, bar, barh, hist and box plot is available. If you want to read more about it, you could refer to the documentation here."
},
{
"code": null,
"e": 2871,
"s": 2592,
"text": "In this article, I just show how to create an easy interactive plot using Plotly from Pandas Series and Data Frame. This feature is still brand new at the time of this article creation, but I am sure in the future, the function would implement many more plots that we could use."
}
] |
Delete all the nodes from the list that are greater than x in C++
|
In this tutorial, we are going to learn how to delete all prime nodes from a singly linked list.
Let's see the steps to solve the problem.
Write struct with data and next pointer.
Write struct with data and next pointer.
Write a function to insert the node into the singly linked list.
Write a function to insert the node into the singly linked list.
Initialize the singly linked list with dummy data.
Initialize the singly linked list with dummy data.
Iterate over the singly linked list. Find whether the current node data is greater than x or not.
Iterate over the singly linked list. Find whether the current node data is greater than x or not.
If the current data is greater than x, then delete the node.
If the current data is greater than x, then delete the node.
Write a function to delete the node. Consider the following three cases while deleting the node.If the node is head node, then move the head to next node.If the node is middle node, then link the next node to the previous nodeIf the node is end node, then remove the previous node link.
Write a function to delete the node. Consider the following three cases while deleting the node.
If the node is head node, then move the head to next node.
If the node is head node, then move the head to next node.
If the node is middle node, then link the next node to the previous node
If the node is middle node, then link the next node to the previous node
If the node is end node, then remove the previous node link.
If the node is end node, then remove the previous node link.
Let's see the code.
Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* getNewNode(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void deleteGreaterNodes(Node** head_ref, int x) {
Node *temp = *head_ref, *prev;
if (temp != NULL && temp->data > x) {
*head_ref = temp->next;
free(temp);
temp = *head_ref;
}
while (temp != NULL) {
while (temp != NULL && temp->data <= x) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
return;
}
prev->next = temp->next;
delete temp;
temp = prev->next;
}
}
void printLinkedList(Node* head) {
while (head) {
cout << head->data << " -> ";
head = head->next;
}
}
int main() {
Node* head = getNewNode(1);
head->next = getNewNode(2);
head->next->next = getNewNode(3);
head->next->next->next = getNewNode(4);
head->next->next->next->next = getNewNode(5);
head->next->next->next->next->next = getNewNode(6);
int x = 3;
cout << "Linked List before deletion:" << endl;
printLinkedList(head);
deleteGreaterNodes(&head, x);
cout << "\nLinked List after deletion:" << endl;
printLinkedList(head);
return 0;
}
If you execute the above program, then you will get the following result.
Linked List before deletion:
1 -> 2 -> 3 -> 4 -> 5 -> 6 ->
Linked List after deletion:
1 -> 2 -> 3 ->
If you have any queries in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "In this tutorial, we are going to learn how to delete all prime nodes from a singly linked list."
},
{
"code": null,
"e": 1201,
"s": 1159,
"text": "Let's see the steps to solve the problem."
},
{
"code": null,
"e": 1242,
"s": 1201,
"text": "Write struct with data and next pointer."
},
{
"code": null,
"e": 1283,
"s": 1242,
"text": "Write struct with data and next pointer."
},
{
"code": null,
"e": 1348,
"s": 1283,
"text": "Write a function to insert the node into the singly linked list."
},
{
"code": null,
"e": 1413,
"s": 1348,
"text": "Write a function to insert the node into the singly linked list."
},
{
"code": null,
"e": 1464,
"s": 1413,
"text": "Initialize the singly linked list with dummy data."
},
{
"code": null,
"e": 1515,
"s": 1464,
"text": "Initialize the singly linked list with dummy data."
},
{
"code": null,
"e": 1613,
"s": 1515,
"text": "Iterate over the singly linked list. Find whether the current node data is greater than x or not."
},
{
"code": null,
"e": 1711,
"s": 1613,
"text": "Iterate over the singly linked list. Find whether the current node data is greater than x or not."
},
{
"code": null,
"e": 1772,
"s": 1711,
"text": "If the current data is greater than x, then delete the node."
},
{
"code": null,
"e": 1833,
"s": 1772,
"text": "If the current data is greater than x, then delete the node."
},
{
"code": null,
"e": 2120,
"s": 1833,
"text": "Write a function to delete the node. Consider the following three cases while deleting the node.If the node is head node, then move the head to next node.If the node is middle node, then link the next node to the previous nodeIf the node is end node, then remove the previous node link."
},
{
"code": null,
"e": 2217,
"s": 2120,
"text": "Write a function to delete the node. Consider the following three cases while deleting the node."
},
{
"code": null,
"e": 2276,
"s": 2217,
"text": "If the node is head node, then move the head to next node."
},
{
"code": null,
"e": 2335,
"s": 2276,
"text": "If the node is head node, then move the head to next node."
},
{
"code": null,
"e": 2408,
"s": 2335,
"text": "If the node is middle node, then link the next node to the previous node"
},
{
"code": null,
"e": 2481,
"s": 2408,
"text": "If the node is middle node, then link the next node to the previous node"
},
{
"code": null,
"e": 2542,
"s": 2481,
"text": "If the node is end node, then remove the previous node link."
},
{
"code": null,
"e": 2603,
"s": 2542,
"text": "If the node is end node, then remove the previous node link."
},
{
"code": null,
"e": 2623,
"s": 2603,
"text": "Let's see the code."
},
{
"code": null,
"e": 2634,
"s": 2623,
"text": " Live Demo"
},
{
"code": null,
"e": 3918,
"s": 2634,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Node {\n int data;\n Node* next;\n};\nNode* getNewNode(int data) {\n Node* newNode = new Node;\n newNode->data = data;\n newNode->next = NULL;\n return newNode;\n}\nvoid deleteGreaterNodes(Node** head_ref, int x) {\n Node *temp = *head_ref, *prev;\n if (temp != NULL && temp->data > x) {\n *head_ref = temp->next;\n free(temp);\n temp = *head_ref;\n }\n while (temp != NULL) {\n while (temp != NULL && temp->data <= x) {\n prev = temp;\n temp = temp->next;\n }\n if (temp == NULL) {\n return;\n }\n prev->next = temp->next;\n delete temp;\n temp = prev->next;\n }\n}\nvoid printLinkedList(Node* head) {\n while (head) {\n cout << head->data << \" -> \";\n head = head->next;\n }\n}\nint main() {\n Node* head = getNewNode(1);\n head->next = getNewNode(2);\n head->next->next = getNewNode(3);\n head->next->next->next = getNewNode(4);\n head->next->next->next->next = getNewNode(5);\n head->next->next->next->next->next = getNewNode(6);\n int x = 3;\n cout << \"Linked List before deletion:\" << endl;\n printLinkedList(head);\n deleteGreaterNodes(&head, x);\n cout << \"\\nLinked List after deletion:\" << endl;\n printLinkedList(head);\n return 0;\n}"
},
{
"code": null,
"e": 3992,
"s": 3918,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 4094,
"s": 3992,
"text": "Linked List before deletion:\n1 -> 2 -> 3 -> 4 -> 5 -> 6 ->\nLinked List after deletion:\n1 -> 2 -> 3 ->"
},
{
"code": null,
"e": 4172,
"s": 4094,
"text": "If you have any queries in the tutorial, mention them in the comment section."
}
] |
What are Complex Data types in JavaScript?
|
Complex Data Type in JavaScript includes the typeof operator. The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
You can try to run the following code to learn how to work with typeof operator in JavaScript −
<html>
<body>
<script>
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "Complex Data Type in JavaScript includes the typeof operator. The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand."
},
{
"code": null,
"e": 1465,
"s": 1295,
"text": "The typeof operator evaluates to \"number\", \"string\", or \"boolean\" if its operand is a number, string, or boolean value and returns true or false based on the evaluation."
},
{
"code": null,
"e": 1561,
"s": 1465,
"text": "You can try to run the following code to learn how to work with typeof operator in JavaScript −"
},
{
"code": null,
"e": 2141,
"s": 1561,
"text": "<html>\n <body>\n <script>\n <!--\n var a = 10;\n var b = \"String\";\n var linebreak = \"<br />\";\n\n result = (typeof b == \"string\" ? \"B is String\" : \"B is Numeric\");\n document.write(\"Result => \");\n document.write(result);\n document.write(linebreak);\n\n result = (typeof a == \"string\" ? \"A is String\" : \"A is Numeric\");\n document.write(\"Result => \");\n document.write(result);\n document.write(linebreak);\n //-->\n </script>\n </body>\n</html>"
}
] |
HTML <textarea> placeholder Attribute
|
The placeholder attribute of the <textarea> element is used to set a placeholder text in the textarea. A placeholder is considered as a hint, like “Enter you name”, “Enter mobile number”, “Write in 100 words”, etc.
Following is the syntax−
<textarea placeholder="text">
Above, text is the hint you want to set for the textarea as a placeholder text.
Let us now see an example to implement the placeholder attribute of the <textarea> element−
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Interview Questions</h2>
<p>Q1</p>
<textarea rows="6" cols="70" placeholder="Why do you want go for the Editor Job Profile? (100 words)">
</textarea>
<p>Q2</p>
<textarea rows="6" cols="70" placeholder="Do you have any previous publishing experience? (100 words)">
</textarea>
</body>
</html>
In the above example, we have set two textarea−
<p>Q1</p>
<textarea rows="6" cols="70" placeholder="Why do you want go for the Editor Job Profile? (100 words)">
</textarea>
<p>Q2</p>
<textarea rows="6" cols="70" placeholder="Do you have any previous publishing experience? (100 words)">
</textarea>
To display a placeholder text, the placeholder attribute is used, for example−
placeholder="Why do you want go for the Editor Job Profile? (100 words)"
|
[
{
"code": null,
"e": 1277,
"s": 1062,
"text": "The placeholder attribute of the <textarea> element is used to set a placeholder text in the textarea. A placeholder is considered as a hint, like “Enter you name”, “Enter mobile number”, “Write in 100 words”, etc."
},
{
"code": null,
"e": 1302,
"s": 1277,
"text": "Following is the syntax−"
},
{
"code": null,
"e": 1332,
"s": 1302,
"text": "<textarea placeholder=\"text\">"
},
{
"code": null,
"e": 1412,
"s": 1332,
"text": "Above, text is the hint you want to set for the textarea as a placeholder text."
},
{
"code": null,
"e": 1504,
"s": 1412,
"text": "Let us now see an example to implement the placeholder attribute of the <textarea> element−"
},
{
"code": null,
"e": 1515,
"s": 1504,
"text": " Live Demo"
},
{
"code": null,
"e": 1841,
"s": 1515,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Interview Questions</h2>\n<p>Q1</p>\n<textarea rows=\"6\" cols=\"70\" placeholder=\"Why do you want go for the Editor Job Profile? (100 words)\">\n</textarea>\n<p>Q2</p>\n<textarea rows=\"6\" cols=\"70\" placeholder=\"Do you have any previous publishing experience? (100 words)\">\n</textarea>\n</body>\n</html>"
},
{
"code": null,
"e": 1889,
"s": 1841,
"text": "In the above example, we have set two textarea−"
},
{
"code": null,
"e": 2140,
"s": 1889,
"text": "<p>Q1</p>\n<textarea rows=\"6\" cols=\"70\" placeholder=\"Why do you want go for the Editor Job Profile? (100 words)\">\n</textarea>\n<p>Q2</p>\n<textarea rows=\"6\" cols=\"70\" placeholder=\"Do you have any previous publishing experience? (100 words)\">\n</textarea>"
},
{
"code": null,
"e": 2219,
"s": 2140,
"text": "To display a placeholder text, the placeholder attribute is used, for example−"
},
{
"code": null,
"e": 2292,
"s": 2219,
"text": "placeholder=\"Why do you want go for the Editor Job Profile? (100 words)\""
}
] |
Sales Forecasting with Price & Promotion effects | by Susan Li | Towards Data Science
|
Many businesses are very seasonal, and some of them make money during holidays like Super Bowl, Labor Day, Thanksgiving, and Christmas. In addition, they use sales promotions to increase the demand for or visibility of a product or service for several weeks during the year.
In this post, we are going to analyze the historical data using time series analysis techniques, with promotion effect.
The data we are going to use is a weekly sales and price data for 9 stores and 3 products. At the end, we are going to forecast the sales for next 50 weeks for one of the three products at one of the stores. You can find the data set here.
Store: the store code. We have 9 stores in total.
Product: the product code. We have 3 products in total.
Is_Holiday: an indicator for whether that week contains holiday: 0 = no, 1 = yes.
Base Price: base or everyday price without discount.
Price: Actual price for each week. They are either promotion prices when promotion is going on or everyday prices otherwise.
Weekly_Units_Sold: Weekly units sold.
In the above data pre-processing, we added new feature like weekly sales amount in dollars, year, month, day, week of year.
To get the first impression about continuous variables in the data we are going to plot ECDF.
Although in the best week, a store sold more than 2500 units, about 80% of the time, weekly units sold did not exceed 500.
Although the highest weekly sales exceeded 25K dollars, over 90% of the data had weekly sales less than 5K dollars.
df.groupby('Store')['weekly_sales'].describe()
df.groupby('Store')['Weekly_Units_Sold'].sum()
It is easy to see that Store 10 has the highest average weekly sales among all 9 stores, also Store 10 has the most total weekly units sold.
And Store 5 has the lowest average weekly sales.
Apparently, Store 10 is the most selling and crowded one.
g = sns.FacetGrid(df, col="Is_Holiday", height=4, aspect=.8)g.map(sns.barplot, "Product", "Price");
g = sns.FacetGrid(df, col="Is_Holiday", height=4, aspect=.8)g.map(sns.barplot, "Product", "Weekly_Units_Sold");
Product 2 is the cheapest product among all the three products, and it sells the most.
Product 3 is the most expensive product among all the three products.
In addition, product price did not change during holidays.
g = sns.FacetGrid(df, row="Is_Holiday", height=1.7, aspect=4,)g.map(sns.distplot, "Weekly_Units_Sold", hist=False, rug=True);
sns.factorplot(data= df, x= 'Is_Holiday', y= 'Weekly_Units_Sold', hue= 'Store');
sns.factorplot(data= df, x= 'Is_Holiday', y= 'Weekly_Units_Sold', hue= 'Product');
It does not seem that holidays have a positive impact for the business. For most of the stores, weekly unit sold during the holiday is as same as the normal days, while store 10 had a decrease during the holidays.
Weekly units sold for product 1 had a slightly increase during the holidays, while product 2 and product 3 had a decrease during the holidays.
g = sns.FacetGrid(df, col="Product", row="Is_Holiday", margin_titles=True, height=3)g.map(plt.scatter, "Price", "Weekly_Units_Sold", color="#338844", edgecolor="white", s=50, lw=1)g.set(xlim=(0, 30), ylim=(0, 2600));
Every product has more than one prices, both at holidays and normal days. I guess one is regular price, another is promotional price.
The price gap for product 3 is huge, it was slashed to almost 50% off during promotions.
Product 3 made the most sales during non-holidays.
g = sns.FacetGrid(df, col="Store", hue="Product", margin_titles=True, col_wrap=3)g.map(plt.scatter, 'Price', 'Weekly_Units_Sold', alpha=.7)g.add_legend();
All of these 9 stores carry these 3 products. They all seem to have similar kind of discount promotions. However, product 3 sells the most units during promotions at store 10.
g = sns.FacetGrid(df, col="Store", col_wrap=3, height=3, ylim=(0, 1000))g.map(sns.pointplot, "month", "Weekly_Units_Sold", color=".3", ci=None, order = [1,2,3,4,5,6,7,8,9,10,11,12]);
Every store has somewhat seasonality, store 10 has the most obvious seasonal pattern.
g = sns.FacetGrid(df, col="Product", col_wrap=3, height=3, ylim=(0, 1000))g.map(sns.pointplot, "month", "Weekly_Units_Sold", color=".3", ci=None, order = [1,2,3,4,5,6,7,8,9,10,11,12]);
Every product has somewhat seasonality, product 2 has two peak seasons per year and product 3 has one.
g = sns.FacetGrid(df, col="Store", col_wrap=3, height=3, ylim=(0, 2000), hue='Product', palette="Set1")g.map(sns.pointplot, "month", "Weekly_Units_Sold", ci=None, order = [1,2,3,4,5,6,7,8,9,10,11,12], alpha=.7)g.add_legend();
In general, product 2 sells more units per week than the other products in every store.
Once a while, product 3 would exceed product 2 at store 10.
g = sns.PairGrid(df, y_vars=["Weekly_Units_Sold"], x_vars=["Price", "Is_Holiday"], height=4)g.map(sns.regplot, color=".3");
The cheaper the price, the more weekly units were sold.
Is holiday or not has nothing to do with the unit sold.
Here we are adding a new column called “promotion”, which was derived from “Base Price” and “Price”.
sns.factorplot(data= df, x= 'promotion', y= 'Weekly_Units_Sold', hue= 'Store');
Every store sells more during the promotions, there is no exception.
sns.factorplot(data= df, x= 'promotion', y= 'Weekly_Units_Sold', hue= 'Product');
Every product sells more during the promotions, in particular, product 2 and product 3.
g = sns.FacetGrid(df, col="Store", hue="promotion", palette = 'plasma', row='promotion')g = (g.map(plt.scatter, "Price", "Weekly_Units_Sold") .add_legend())
All the stores have the similar price promotion pattern, for some reason, store 10 sells the most during the promotions.
g = sns.FacetGrid(df, hue="promotion", col="Product", height=4)g.map(qqplot, "Price", "Weekly_Units_Sold")g.add_legend();
Every product has the regular price and promotional price. Product 3 has the highest discount and sells the most during the promotions.
Observations
The most selling and crowded Store is Store 10, and the least crowded store is Store 5.
In terms of number of units sold, the most selling product is product 2 throughout the year.
Stores do not necessarily run product promotions during holidays. Holidays do not seem to have an impact on stores or products performance.
Product 2 seems to be the cheapest product, and Product 3 is the most expensive product.
Most stores have some kind of seasonality and they have two peak seasons per year.
Product 1 sells a little more in February than the other months, Product 2 sells the most around April and July, and Product 3 sells the most around July to September.
Each product has its regular price and promotional price. There isn’t significant gap between regular price and promotional price on Product 1 and Product 2, however, Product 3’s promotional price can be slashed to 50% of its original price. Although every store makes this kind of price cut for product 3, store 10 is the one made the highest sales during the price cut.
It is nothing unusual to sell more during promotion than the normal days. Store 10’s made Product 3 the best selling product around July to September.
We are going to build a time series analysis for product 3 at store 10, and we are going to forecast weekly sales in dollars.
Product 2’s seasonality at store 10 is obvious. The sales always peak between July and September during school holiday.
Below we are implementing prophet model, forecasting the weekly sales for the future 50 weeks.
The model was able to capture the seasonality.
model.plot_components(forecast);
metric_df = forecast.set_index('ds')[['yhat']].join(store_10_pro_3.set_index('ds').y).reset_index()metric_df.dropna(inplace=True)error = mean_squared_error(metric_df.y, metric_df.yhat)print('The RMSE is {}'. format(sqrt(error)))
A great thing about Prophet is that we can add our own custom seasonalities. Here we are going to add school holiday season that spans from early July to early September.
metric_df = forecast.set_index('ds')[['yhat']].join(store_10_pro_3.set_index('ds').y).reset_index()metric_df.dropna(inplace=True)error = mean_squared_error(metric_df.y, metric_df.yhat)print('The RMSE is {}'. format(sqrt(error)))
The RMSE decreased a little.
model.plot_components(forecast);
Jupyter notebook can be found on Github. Enjoy the rest of the week!
|
[
{
"code": null,
"e": 447,
"s": 172,
"text": "Many businesses are very seasonal, and some of them make money during holidays like Super Bowl, Labor Day, Thanksgiving, and Christmas. In addition, they use sales promotions to increase the demand for or visibility of a product or service for several weeks during the year."
},
{
"code": null,
"e": 567,
"s": 447,
"text": "In this post, we are going to analyze the historical data using time series analysis techniques, with promotion effect."
},
{
"code": null,
"e": 807,
"s": 567,
"text": "The data we are going to use is a weekly sales and price data for 9 stores and 3 products. At the end, we are going to forecast the sales for next 50 weeks for one of the three products at one of the stores. You can find the data set here."
},
{
"code": null,
"e": 857,
"s": 807,
"text": "Store: the store code. We have 9 stores in total."
},
{
"code": null,
"e": 913,
"s": 857,
"text": "Product: the product code. We have 3 products in total."
},
{
"code": null,
"e": 995,
"s": 913,
"text": "Is_Holiday: an indicator for whether that week contains holiday: 0 = no, 1 = yes."
},
{
"code": null,
"e": 1048,
"s": 995,
"text": "Base Price: base or everyday price without discount."
},
{
"code": null,
"e": 1173,
"s": 1048,
"text": "Price: Actual price for each week. They are either promotion prices when promotion is going on or everyday prices otherwise."
},
{
"code": null,
"e": 1211,
"s": 1173,
"text": "Weekly_Units_Sold: Weekly units sold."
},
{
"code": null,
"e": 1335,
"s": 1211,
"text": "In the above data pre-processing, we added new feature like weekly sales amount in dollars, year, month, day, week of year."
},
{
"code": null,
"e": 1429,
"s": 1335,
"text": "To get the first impression about continuous variables in the data we are going to plot ECDF."
},
{
"code": null,
"e": 1552,
"s": 1429,
"text": "Although in the best week, a store sold more than 2500 units, about 80% of the time, weekly units sold did not exceed 500."
},
{
"code": null,
"e": 1668,
"s": 1552,
"text": "Although the highest weekly sales exceeded 25K dollars, over 90% of the data had weekly sales less than 5K dollars."
},
{
"code": null,
"e": 1715,
"s": 1668,
"text": "df.groupby('Store')['weekly_sales'].describe()"
},
{
"code": null,
"e": 1762,
"s": 1715,
"text": "df.groupby('Store')['Weekly_Units_Sold'].sum()"
},
{
"code": null,
"e": 1903,
"s": 1762,
"text": "It is easy to see that Store 10 has the highest average weekly sales among all 9 stores, also Store 10 has the most total weekly units sold."
},
{
"code": null,
"e": 1952,
"s": 1903,
"text": "And Store 5 has the lowest average weekly sales."
},
{
"code": null,
"e": 2010,
"s": 1952,
"text": "Apparently, Store 10 is the most selling and crowded one."
},
{
"code": null,
"e": 2110,
"s": 2010,
"text": "g = sns.FacetGrid(df, col=\"Is_Holiday\", height=4, aspect=.8)g.map(sns.barplot, \"Product\", \"Price\");"
},
{
"code": null,
"e": 2222,
"s": 2110,
"text": "g = sns.FacetGrid(df, col=\"Is_Holiday\", height=4, aspect=.8)g.map(sns.barplot, \"Product\", \"Weekly_Units_Sold\");"
},
{
"code": null,
"e": 2309,
"s": 2222,
"text": "Product 2 is the cheapest product among all the three products, and it sells the most."
},
{
"code": null,
"e": 2379,
"s": 2309,
"text": "Product 3 is the most expensive product among all the three products."
},
{
"code": null,
"e": 2438,
"s": 2379,
"text": "In addition, product price did not change during holidays."
},
{
"code": null,
"e": 2581,
"s": 2438,
"text": "g = sns.FacetGrid(df, row=\"Is_Holiday\", height=1.7, aspect=4,)g.map(sns.distplot, \"Weekly_Units_Sold\", hist=False, rug=True);"
},
{
"code": null,
"e": 2705,
"s": 2581,
"text": "sns.factorplot(data= df, x= 'Is_Holiday', y= 'Weekly_Units_Sold', hue= 'Store');"
},
{
"code": null,
"e": 2831,
"s": 2705,
"text": "sns.factorplot(data= df, x= 'Is_Holiday', y= 'Weekly_Units_Sold', hue= 'Product');"
},
{
"code": null,
"e": 3045,
"s": 2831,
"text": "It does not seem that holidays have a positive impact for the business. For most of the stores, weekly unit sold during the holiday is as same as the normal days, while store 10 had a decrease during the holidays."
},
{
"code": null,
"e": 3188,
"s": 3045,
"text": "Weekly units sold for product 1 had a slightly increase during the holidays, while product 2 and product 3 had a decrease during the holidays."
},
{
"code": null,
"e": 3405,
"s": 3188,
"text": "g = sns.FacetGrid(df, col=\"Product\", row=\"Is_Holiday\", margin_titles=True, height=3)g.map(plt.scatter, \"Price\", \"Weekly_Units_Sold\", color=\"#338844\", edgecolor=\"white\", s=50, lw=1)g.set(xlim=(0, 30), ylim=(0, 2600));"
},
{
"code": null,
"e": 3539,
"s": 3405,
"text": "Every product has more than one prices, both at holidays and normal days. I guess one is regular price, another is promotional price."
},
{
"code": null,
"e": 3628,
"s": 3539,
"text": "The price gap for product 3 is huge, it was slashed to almost 50% off during promotions."
},
{
"code": null,
"e": 3679,
"s": 3628,
"text": "Product 3 made the most sales during non-holidays."
},
{
"code": null,
"e": 3834,
"s": 3679,
"text": "g = sns.FacetGrid(df, col=\"Store\", hue=\"Product\", margin_titles=True, col_wrap=3)g.map(plt.scatter, 'Price', 'Weekly_Units_Sold', alpha=.7)g.add_legend();"
},
{
"code": null,
"e": 4010,
"s": 3834,
"text": "All of these 9 stores carry these 3 products. They all seem to have similar kind of discount promotions. However, product 3 sells the most units during promotions at store 10."
},
{
"code": null,
"e": 4193,
"s": 4010,
"text": "g = sns.FacetGrid(df, col=\"Store\", col_wrap=3, height=3, ylim=(0, 1000))g.map(sns.pointplot, \"month\", \"Weekly_Units_Sold\", color=\".3\", ci=None, order = [1,2,3,4,5,6,7,8,9,10,11,12]);"
},
{
"code": null,
"e": 4279,
"s": 4193,
"text": "Every store has somewhat seasonality, store 10 has the most obvious seasonal pattern."
},
{
"code": null,
"e": 4464,
"s": 4279,
"text": "g = sns.FacetGrid(df, col=\"Product\", col_wrap=3, height=3, ylim=(0, 1000))g.map(sns.pointplot, \"month\", \"Weekly_Units_Sold\", color=\".3\", ci=None, order = [1,2,3,4,5,6,7,8,9,10,11,12]);"
},
{
"code": null,
"e": 4567,
"s": 4464,
"text": "Every product has somewhat seasonality, product 2 has two peak seasons per year and product 3 has one."
},
{
"code": null,
"e": 4793,
"s": 4567,
"text": "g = sns.FacetGrid(df, col=\"Store\", col_wrap=3, height=3, ylim=(0, 2000), hue='Product', palette=\"Set1\")g.map(sns.pointplot, \"month\", \"Weekly_Units_Sold\", ci=None, order = [1,2,3,4,5,6,7,8,9,10,11,12], alpha=.7)g.add_legend();"
},
{
"code": null,
"e": 4881,
"s": 4793,
"text": "In general, product 2 sells more units per week than the other products in every store."
},
{
"code": null,
"e": 4941,
"s": 4881,
"text": "Once a while, product 3 would exceed product 2 at store 10."
},
{
"code": null,
"e": 5065,
"s": 4941,
"text": "g = sns.PairGrid(df, y_vars=[\"Weekly_Units_Sold\"], x_vars=[\"Price\", \"Is_Holiday\"], height=4)g.map(sns.regplot, color=\".3\");"
},
{
"code": null,
"e": 5121,
"s": 5065,
"text": "The cheaper the price, the more weekly units were sold."
},
{
"code": null,
"e": 5177,
"s": 5121,
"text": "Is holiday or not has nothing to do with the unit sold."
},
{
"code": null,
"e": 5278,
"s": 5177,
"text": "Here we are adding a new column called “promotion”, which was derived from “Base Price” and “Price”."
},
{
"code": null,
"e": 5401,
"s": 5278,
"text": "sns.factorplot(data= df, x= 'promotion', y= 'Weekly_Units_Sold', hue= 'Store');"
},
{
"code": null,
"e": 5470,
"s": 5401,
"text": "Every store sells more during the promotions, there is no exception."
},
{
"code": null,
"e": 5595,
"s": 5470,
"text": "sns.factorplot(data= df, x= 'promotion', y= 'Weekly_Units_Sold', hue= 'Product');"
},
{
"code": null,
"e": 5683,
"s": 5595,
"text": "Every product sells more during the promotions, in particular, product 2 and product 3."
},
{
"code": null,
"e": 5844,
"s": 5683,
"text": "g = sns.FacetGrid(df, col=\"Store\", hue=\"promotion\", palette = 'plasma', row='promotion')g = (g.map(plt.scatter, \"Price\", \"Weekly_Units_Sold\") .add_legend())"
},
{
"code": null,
"e": 5965,
"s": 5844,
"text": "All the stores have the similar price promotion pattern, for some reason, store 10 sells the most during the promotions."
},
{
"code": null,
"e": 6087,
"s": 5965,
"text": "g = sns.FacetGrid(df, hue=\"promotion\", col=\"Product\", height=4)g.map(qqplot, \"Price\", \"Weekly_Units_Sold\")g.add_legend();"
},
{
"code": null,
"e": 6223,
"s": 6087,
"text": "Every product has the regular price and promotional price. Product 3 has the highest discount and sells the most during the promotions."
},
{
"code": null,
"e": 6236,
"s": 6223,
"text": "Observations"
},
{
"code": null,
"e": 6324,
"s": 6236,
"text": "The most selling and crowded Store is Store 10, and the least crowded store is Store 5."
},
{
"code": null,
"e": 6417,
"s": 6324,
"text": "In terms of number of units sold, the most selling product is product 2 throughout the year."
},
{
"code": null,
"e": 6557,
"s": 6417,
"text": "Stores do not necessarily run product promotions during holidays. Holidays do not seem to have an impact on stores or products performance."
},
{
"code": null,
"e": 6646,
"s": 6557,
"text": "Product 2 seems to be the cheapest product, and Product 3 is the most expensive product."
},
{
"code": null,
"e": 6729,
"s": 6646,
"text": "Most stores have some kind of seasonality and they have two peak seasons per year."
},
{
"code": null,
"e": 6897,
"s": 6729,
"text": "Product 1 sells a little more in February than the other months, Product 2 sells the most around April and July, and Product 3 sells the most around July to September."
},
{
"code": null,
"e": 7269,
"s": 6897,
"text": "Each product has its regular price and promotional price. There isn’t significant gap between regular price and promotional price on Product 1 and Product 2, however, Product 3’s promotional price can be slashed to 50% of its original price. Although every store makes this kind of price cut for product 3, store 10 is the one made the highest sales during the price cut."
},
{
"code": null,
"e": 7420,
"s": 7269,
"text": "It is nothing unusual to sell more during promotion than the normal days. Store 10’s made Product 3 the best selling product around July to September."
},
{
"code": null,
"e": 7546,
"s": 7420,
"text": "We are going to build a time series analysis for product 3 at store 10, and we are going to forecast weekly sales in dollars."
},
{
"code": null,
"e": 7666,
"s": 7546,
"text": "Product 2’s seasonality at store 10 is obvious. The sales always peak between July and September during school holiday."
},
{
"code": null,
"e": 7761,
"s": 7666,
"text": "Below we are implementing prophet model, forecasting the weekly sales for the future 50 weeks."
},
{
"code": null,
"e": 7808,
"s": 7761,
"text": "The model was able to capture the seasonality."
},
{
"code": null,
"e": 7841,
"s": 7808,
"text": "model.plot_components(forecast);"
},
{
"code": null,
"e": 8070,
"s": 7841,
"text": "metric_df = forecast.set_index('ds')[['yhat']].join(store_10_pro_3.set_index('ds').y).reset_index()metric_df.dropna(inplace=True)error = mean_squared_error(metric_df.y, metric_df.yhat)print('The RMSE is {}'. format(sqrt(error)))"
},
{
"code": null,
"e": 8241,
"s": 8070,
"text": "A great thing about Prophet is that we can add our own custom seasonalities. Here we are going to add school holiday season that spans from early July to early September."
},
{
"code": null,
"e": 8470,
"s": 8241,
"text": "metric_df = forecast.set_index('ds')[['yhat']].join(store_10_pro_3.set_index('ds').y).reset_index()metric_df.dropna(inplace=True)error = mean_squared_error(metric_df.y, metric_df.yhat)print('The RMSE is {}'. format(sqrt(error)))"
},
{
"code": null,
"e": 8499,
"s": 8470,
"text": "The RMSE decreased a little."
},
{
"code": null,
"e": 8532,
"s": 8499,
"text": "model.plot_components(forecast);"
}
] |
Equal Sum and XOR - GeeksforGeeks
|
04 Oct, 2021
Given a positive integer n, find count of positive integers i such that 0 <= i <= n and n+i = n^i
Examples :
Input : n = 7
Output : 1
Explanation:
7^i = 7+i holds only for only for i = 0
7+0 = 7^0 = 7
Input: n = 12
Output: 4
12^i = 12+i hold only for i = 0, 1, 2, 3
for i=0, 12+0 = 12^0 = 12
for i=1, 12+1 = 12^1 = 13
for i=2, 12+2 = 12^2 = 14
for i=3, 12+3 = 12^3 = 15
Method 1 (Simple) : One simple solution is to iterate over all values of i 0<= i <= n and count all satisfying values.
C++
Java
Python3
C#
PHP
Javascript
/* C++ program to print count of values such that n+i = n^i */#include <iostream>using namespace std; // function to count number of values less than// equal to n that satisfy the given conditionint countValues (int n){ int countV = 0; // Traverse all numbers from 0 to n and // increment result only when given condition // is satisfied. for (int i=0; i<=n; i++ ) if ((n+i) == (n^i) ) countV++; return countV;} // Driver programint main(){ int n = 12; cout << countValues(n); return 0;}
/* Java program to print count of values such that n+i = n^i */import java.util.*; class GFG { // function to count number of values // less than equal to n that satisfy // the given condition public static int countValues (int n) { int countV = 0; // Traverse all numbers from 0 to n // and increment result only when // given condition is satisfied. for (int i = 0; i <= n; i++ ) if ((n + i) == (n ^ i) ) countV++; return countV; } /* Driver program to test above function */ public static void main(String[] args) { int n = 12; System.out.println(countValues(n)); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 program to print count# of values such that n+i = n^i # function to count number# of values less than# equal to n that satisfy# the given conditiondef countValues (n): countV = 0; # Traverse all numbers # from 0 to n and # increment result only # when given condition # is satisfied. for i in range(n + 1): if ((n + i) == (n ^ i)): countV += 1; return countV; # Driver Coden = 12;print(countValues(n)); # This code is contributed by mits
/* C# program to print count of valuessuch that n+i = n^i */using System; class GFG { // function to count number of values // less than equal to n that satisfy // the given condition public static int countValues (int n) { int countV = 0; // Traverse all numbers from 0 to n // and increment result only when // given condition is satisfied. for (int i = 0; i <= n; i++ ) if ((n + i) == (n ^ i) ) countV++; return countV; } /* Driver program to test above function */ public static void Main() { int n = 12; Console.WriteLine(countValues(n)); }} // This code is contributed by anuj_67.
<?php// PHP program to print count// of values such that n+i = n^i // function to count number// of values less than// equal to n that satisfy// the given conditionfunction countValues ($n){ $countV = 0; // Traverse all numbers // from 0 to n and // increment result only // when given condition // is satisfied. for ($i = 0; $i <= $n; $i++ ) if (($n + $i) == ($n^$i) ) $countV++; return $countV;} // Driver Code $n = 12; echo countValues($n); // This code is contributed by m_kit?>
<script> /* JavaScript program to print count of values suchthat n+i = n^i */ // function to count number of values less than// equal to n that satisfy the given conditionfunction countValues (n){ let countV = 0; // Traverse all numbers from 0 to n and // increment result only when given condition // is satisfied. for (let i=0; i<=n; i++ ) if ((n+i) == (n^i) ) countV++; return countV;} // Driver program let n = 12; document.write(countValues(n)); // This code is contributed by Surbhi Tyagi. </script>
Output:
4
Time Complexity: O(n)
Space Complexity: O(1)
Method 2 (Efficient) : An efficient solution is as follows
we know that (n+i)=(n^i)+2*(n&i)So n + i = n ^ i implies n & i = 0Hence our problem reduces to finding values of i such that n & i = 0. How to find count of such pairs? We can use the count of unset-bits in the binary representation of n. For n & i to be zero, i must unset all set-bits of n. If the kth bit is set at a particular in n, kth bit in i must be 0 always, else kth bit of i can be 0 or 1Hence, total such combinations are 2^(count of unset bits in n)For example, consider n = 12 (Binary representation : 1 1 0 0). All possible values of i that can unset all bits of n are 0 0 0/1 0/1 where 0/1 implies either 0 or 1. Number of such values of i are 2^2 = 4.
The following is the program following the above idea.
C++
Java
C#
Python3
PHP
Javascript
/* c++ program to print count of values such that n+i = n^i */#include <bits/stdc++.h>using namespace std; // function to count number of values less than// equal to n that satisfy the given conditionint countValues(int n){ // unset_bits keeps track of count of un-set // bits in binary representation of n int unset_bits=0; while (n) { if ((n & 1) == 0) unset_bits++; n=n>>1; } // Return 2 ^ unset_bits return 1 << unset_bits;} // Driver codeint main(){ int n = 12; cout << countValues(n); return 0;}
/* Java program to print count of values such that n+i = n^i */import java.util.*; class GFG { // function to count number of values // less than equal to n that satisfy // the given condition public static int countValues(int n) { // unset_bits keeps track of count // of un-set bits in binary // representation of n int unset_bits=0; while (n > 0) { if ((n & 1) == 0) unset_bits++; n=n>>1; } // Return 2 ^ unset_bits return 1 << unset_bits; } /* Driver program to test above function */ public static void main(String[] args) { int n = 12; System.out.println(countValues(n)); }} // This code is contributed by Arnav Kr. Mandal.
/* C# program to print count of values such that n+i = n^i */using System;public class GFG { // function to count number of values // less than equal to n that satisfy // the given condition public static int countValues(int n) { // unset_bits keeps track of count // of un-set bits in binary // representation of n int unset_bits=0; while (n > 0) { if ((n & 1) == 0) unset_bits++; n=n>>1; } // Return 2 ^ unset_bits return 1 << unset_bits; } /* Driver program to test above function */ public static void Main(String[] args) { int n = 12; Console.WriteLine(countValues(n)); }} // This code is contributed by umadevi9616
# Python3 program to print count of values such# that n+i = n^i # function to count number of values less than# equal to n that satisfy the given conditiondef countValues(n): # unset_bits keeps track of count of un-set # bits in binary representation of n unset_bits = 0 while(n): if n & 1 == 0: unset_bits += 1 n = n >> 1 # Return 2 ^ unset_bits return 1 << unset_bits # Driver codeif __name__=='__main__': n = 12 print(countValues(n)) # This code is contributed by rutvik
<?php/* PHP program to print countof values such that n+i = n^i */ // function to count number of// values less than equal to n// that satisfy the given// conditionfunction countValues( $n){ // unset_bits keeps track // of count of un-set bits // in binary representation // of n $unset_bits = 0; while ($n) { if (($n & 1) == 0) $unset_bits++; $n = $n >> 1; } // Return 2 ^ unset_bits return 1 << $unset_bits;} // Driver code $n = 12; echo countValues($n); // This code is contributed// by Anuj_67.?>
<script> // Javascript program to print count of values// such that n+i = n^i // Function to count number of values// less than equal to n that satisfy// the given conditionfunction countValues(n){ // unset_bits keeps track of count // of un-set bits in binary // representation of n let unset_bits = 0; while (n > 0) { if ((n & 1) == 0) unset_bits++; n = n >> 1; } // Return 2 ^ unset_bits return 1 << unset_bits;} // Driver Codelet n = 12; document.write(countValues(n)); // This code is contributed by susmitakundugoaldanga </script>
Output :
4
Time Complexity: O(log(n))
Space Complexity: O(1)
YouTubeGeeksforGeeks500K subscribersEqual Sum and XOR | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=zhu605v9KOI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Nikhil Chakravartula. 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.
jit_t
vt_m
Mithun Kumar
rutvik_56
utkarshpandey1610
surbhityagi15
mohanyash73
susmitakundugoaldanga
umadevi9616
ashutoshsinghgeeksforgeeks
Bitwise-XOR
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Add two numbers without using arithmetic operators
Binary representation of a given number
Program to find whether a given number is power of 2
Find the element that appears once
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
Josephus problem | Set 1 (A O(n) Solution)
Write an Efficient C Program to Reverse Bits of a Number
|
[
{
"code": null,
"e": 24617,
"s": 24589,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 24716,
"s": 24617,
"text": "Given a positive integer n, find count of positive integers i such that 0 <= i <= n and n+i = n^i "
},
{
"code": null,
"e": 24728,
"s": 24716,
"text": "Examples : "
},
{
"code": null,
"e": 24991,
"s": 24728,
"text": "Input : n = 7\nOutput : 1\nExplanation:\n7^i = 7+i holds only for only for i = 0\n7+0 = 7^0 = 7\n\nInput: n = 12\nOutput: 4\n12^i = 12+i hold only for i = 0, 1, 2, 3\nfor i=0, 12+0 = 12^0 = 12\nfor i=1, 12+1 = 12^1 = 13\nfor i=2, 12+2 = 12^2 = 14\nfor i=3, 12+3 = 12^3 = 15"
},
{
"code": null,
"e": 25112,
"s": 24991,
"text": "Method 1 (Simple) : One simple solution is to iterate over all values of i 0<= i <= n and count all satisfying values. "
},
{
"code": null,
"e": 25116,
"s": 25112,
"text": "C++"
},
{
"code": null,
"e": 25121,
"s": 25116,
"text": "Java"
},
{
"code": null,
"e": 25129,
"s": 25121,
"text": "Python3"
},
{
"code": null,
"e": 25132,
"s": 25129,
"text": "C#"
},
{
"code": null,
"e": 25136,
"s": 25132,
"text": "PHP"
},
{
"code": null,
"e": 25147,
"s": 25136,
"text": "Javascript"
},
{
"code": "/* C++ program to print count of values such that n+i = n^i */#include <iostream>using namespace std; // function to count number of values less than// equal to n that satisfy the given conditionint countValues (int n){ int countV = 0; // Traverse all numbers from 0 to n and // increment result only when given condition // is satisfied. for (int i=0; i<=n; i++ ) if ((n+i) == (n^i) ) countV++; return countV;} // Driver programint main(){ int n = 12; cout << countValues(n); return 0;}",
"e": 25684,
"s": 25147,
"text": null
},
{
"code": "/* Java program to print count of values such that n+i = n^i */import java.util.*; class GFG { // function to count number of values // less than equal to n that satisfy // the given condition public static int countValues (int n) { int countV = 0; // Traverse all numbers from 0 to n // and increment result only when // given condition is satisfied. for (int i = 0; i <= n; i++ ) if ((n + i) == (n ^ i) ) countV++; return countV; } /* Driver program to test above function */ public static void main(String[] args) { int n = 12; System.out.println(countValues(n)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 26446,
"s": 25684,
"text": null
},
{
"code": "# Python3 program to print count# of values such that n+i = n^i # function to count number# of values less than# equal to n that satisfy# the given conditiondef countValues (n): countV = 0; # Traverse all numbers # from 0 to n and # increment result only # when given condition # is satisfied. for i in range(n + 1): if ((n + i) == (n ^ i)): countV += 1; return countV; # Driver Coden = 12;print(countValues(n)); # This code is contributed by mits",
"e": 26938,
"s": 26446,
"text": null
},
{
"code": "/* C# program to print count of valuessuch that n+i = n^i */using System; class GFG { // function to count number of values // less than equal to n that satisfy // the given condition public static int countValues (int n) { int countV = 0; // Traverse all numbers from 0 to n // and increment result only when // given condition is satisfied. for (int i = 0; i <= n; i++ ) if ((n + i) == (n ^ i) ) countV++; return countV; } /* Driver program to test above function */ public static void Main() { int n = 12; Console.WriteLine(countValues(n)); }} // This code is contributed by anuj_67.",
"e": 27666,
"s": 26938,
"text": null
},
{
"code": "<?php// PHP program to print count// of values such that n+i = n^i // function to count number// of values less than// equal to n that satisfy// the given conditionfunction countValues ($n){ $countV = 0; // Traverse all numbers // from 0 to n and // increment result only // when given condition // is satisfied. for ($i = 0; $i <= $n; $i++ ) if (($n + $i) == ($n^$i) ) $countV++; return $countV;} // Driver Code $n = 12; echo countValues($n); // This code is contributed by m_kit?>",
"e": 28203,
"s": 27666,
"text": null
},
{
"code": "<script> /* JavaScript program to print count of values suchthat n+i = n^i */ // function to count number of values less than// equal to n that satisfy the given conditionfunction countValues (n){ let countV = 0; // Traverse all numbers from 0 to n and // increment result only when given condition // is satisfied. for (let i=0; i<=n; i++ ) if ((n+i) == (n^i) ) countV++; return countV;} // Driver program let n = 12; document.write(countValues(n)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 28754,
"s": 28203,
"text": null
},
{
"code": null,
"e": 28763,
"s": 28754,
"text": "Output: "
},
{
"code": null,
"e": 28765,
"s": 28763,
"text": "4"
},
{
"code": null,
"e": 28787,
"s": 28765,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 28810,
"s": 28787,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 28869,
"s": 28810,
"text": "Method 2 (Efficient) : An efficient solution is as follows"
},
{
"code": null,
"e": 29539,
"s": 28869,
"text": "we know that (n+i)=(n^i)+2*(n&i)So n + i = n ^ i implies n & i = 0Hence our problem reduces to finding values of i such that n & i = 0. How to find count of such pairs? We can use the count of unset-bits in the binary representation of n. For n & i to be zero, i must unset all set-bits of n. If the kth bit is set at a particular in n, kth bit in i must be 0 always, else kth bit of i can be 0 or 1Hence, total such combinations are 2^(count of unset bits in n)For example, consider n = 12 (Binary representation : 1 1 0 0). All possible values of i that can unset all bits of n are 0 0 0/1 0/1 where 0/1 implies either 0 or 1. Number of such values of i are 2^2 = 4. "
},
{
"code": null,
"e": 29596,
"s": 29539,
"text": "The following is the program following the above idea. "
},
{
"code": null,
"e": 29600,
"s": 29596,
"text": "C++"
},
{
"code": null,
"e": 29605,
"s": 29600,
"text": "Java"
},
{
"code": null,
"e": 29608,
"s": 29605,
"text": "C#"
},
{
"code": null,
"e": 29616,
"s": 29608,
"text": "Python3"
},
{
"code": null,
"e": 29620,
"s": 29616,
"text": "PHP"
},
{
"code": null,
"e": 29631,
"s": 29620,
"text": "Javascript"
},
{
"code": "/* c++ program to print count of values such that n+i = n^i */#include <bits/stdc++.h>using namespace std; // function to count number of values less than// equal to n that satisfy the given conditionint countValues(int n){ // unset_bits keeps track of count of un-set // bits in binary representation of n int unset_bits=0; while (n) { if ((n & 1) == 0) unset_bits++; n=n>>1; } // Return 2 ^ unset_bits return 1 << unset_bits;} // Driver codeint main(){ int n = 12; cout << countValues(n); return 0;}",
"e": 30193,
"s": 29631,
"text": null
},
{
"code": "/* Java program to print count of values such that n+i = n^i */import java.util.*; class GFG { // function to count number of values // less than equal to n that satisfy // the given condition public static int countValues(int n) { // unset_bits keeps track of count // of un-set bits in binary // representation of n int unset_bits=0; while (n > 0) { if ((n & 1) == 0) unset_bits++; n=n>>1; } // Return 2 ^ unset_bits return 1 << unset_bits; } /* Driver program to test above function */ public static void main(String[] args) { int n = 12; System.out.println(countValues(n)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 31000,
"s": 30193,
"text": null
},
{
"code": "/* C# program to print count of values such that n+i = n^i */using System;public class GFG { // function to count number of values // less than equal to n that satisfy // the given condition public static int countValues(int n) { // unset_bits keeps track of count // of un-set bits in binary // representation of n int unset_bits=0; while (n > 0) { if ((n & 1) == 0) unset_bits++; n=n>>1; } // Return 2 ^ unset_bits return 1 << unset_bits; } /* Driver program to test above function */ public static void Main(String[] args) { int n = 12; Console.WriteLine(countValues(n)); }} // This code is contributed by umadevi9616",
"e": 31803,
"s": 31000,
"text": null
},
{
"code": "# Python3 program to print count of values such# that n+i = n^i # function to count number of values less than# equal to n that satisfy the given conditiondef countValues(n): # unset_bits keeps track of count of un-set # bits in binary representation of n unset_bits = 0 while(n): if n & 1 == 0: unset_bits += 1 n = n >> 1 # Return 2 ^ unset_bits return 1 << unset_bits # Driver codeif __name__=='__main__': n = 12 print(countValues(n)) # This code is contributed by rutvik",
"e": 32349,
"s": 31803,
"text": null
},
{
"code": "<?php/* PHP program to print countof values such that n+i = n^i */ // function to count number of// values less than equal to n// that satisfy the given// conditionfunction countValues( $n){ // unset_bits keeps track // of count of un-set bits // in binary representation // of n $unset_bits = 0; while ($n) { if (($n & 1) == 0) $unset_bits++; $n = $n >> 1; } // Return 2 ^ unset_bits return 1 << $unset_bits;} // Driver code $n = 12; echo countValues($n); // This code is contributed// by Anuj_67.?>",
"e": 32919,
"s": 32349,
"text": null
},
{
"code": "<script> // Javascript program to print count of values// such that n+i = n^i // Function to count number of values// less than equal to n that satisfy// the given conditionfunction countValues(n){ // unset_bits keeps track of count // of un-set bits in binary // representation of n let unset_bits = 0; while (n > 0) { if ((n & 1) == 0) unset_bits++; n = n >> 1; } // Return 2 ^ unset_bits return 1 << unset_bits;} // Driver Codelet n = 12; document.write(countValues(n)); // This code is contributed by susmitakundugoaldanga </script>",
"e": 33544,
"s": 32919,
"text": null
},
{
"code": null,
"e": 33554,
"s": 33544,
"text": "Output : "
},
{
"code": null,
"e": 33556,
"s": 33554,
"text": "4"
},
{
"code": null,
"e": 33583,
"s": 33556,
"text": "Time Complexity: O(log(n))"
},
{
"code": null,
"e": 33606,
"s": 33583,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 34422,
"s": 33606,
"text": "YouTubeGeeksforGeeks500K subscribersEqual Sum and XOR | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:50•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=zhu605v9KOI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 34727,
"s": 34422,
"text": "This article is contributed by Nikhil Chakravartula. 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": 34733,
"s": 34727,
"text": "jit_t"
},
{
"code": null,
"e": 34738,
"s": 34733,
"text": "vt_m"
},
{
"code": null,
"e": 34751,
"s": 34738,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 34761,
"s": 34751,
"text": "rutvik_56"
},
{
"code": null,
"e": 34779,
"s": 34761,
"text": "utkarshpandey1610"
},
{
"code": null,
"e": 34793,
"s": 34779,
"text": "surbhityagi15"
},
{
"code": null,
"e": 34805,
"s": 34793,
"text": "mohanyash73"
},
{
"code": null,
"e": 34827,
"s": 34805,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 34839,
"s": 34827,
"text": "umadevi9616"
},
{
"code": null,
"e": 34866,
"s": 34839,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 34878,
"s": 34866,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 34888,
"s": 34878,
"text": "Bit Magic"
},
{
"code": null,
"e": 34898,
"s": 34888,
"text": "Bit Magic"
},
{
"code": null,
"e": 34996,
"s": 34898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35005,
"s": 34996,
"text": "Comments"
},
{
"code": null,
"e": 35018,
"s": 35005,
"text": "Old Comments"
},
{
"code": null,
"e": 35064,
"s": 35018,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 35094,
"s": 35064,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 35145,
"s": 35094,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 35185,
"s": 35145,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 35238,
"s": 35185,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 35273,
"s": 35238,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 35324,
"s": 35273,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 35340,
"s": 35324,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 35383,
"s": 35340,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
}
] |
MySQL Server port number?
|
If you will install MySQL on your system, then you will get the default MySQL server port number i.e. 3306.
To know the MySQL server port number, you can use the following query. Here, we have used the SHOW VARIABLES command. The query is as follows −
mysql> SHOW VARIABLES WHERE Variable_Name = 'port';
The following is the output −
+---------------+-------+
| Variable_Name | Value |
+---------------+-------+
| port | 3306 |
+---------------+-------+
1 row in set (0.04 sec)
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "If you will install MySQL on your system, then you will get the default MySQL server port number i.e. 3306."
},
{
"code": null,
"e": 1314,
"s": 1170,
"text": "To know the MySQL server port number, you can use the following query. Here, we have used the SHOW VARIABLES command. The query is as follows −"
},
{
"code": null,
"e": 1366,
"s": 1314,
"text": "mysql> SHOW VARIABLES WHERE Variable_Name = 'port';"
},
{
"code": null,
"e": 1396,
"s": 1366,
"text": "The following is the output −"
},
{
"code": null,
"e": 1550,
"s": 1396,
"text": "+---------------+-------+\n| Variable_Name | Value |\n+---------------+-------+\n| port | 3306 |\n+---------------+-------+\n1 row in set (0.04 sec)"
}
] |
What is the Count property of ArrayList class in C#?
|
The Count property in the ArrayList class counts the number of elements in the ArrayList.
Firstly, add elements to the ArrayList −
ArrayList arrList = new ArrayList();
arrList.Add(98);
arrList.Add(55);
arrList.Add(65);
arrList.Add(34);
Then get the count of the array list −
arrList.Count
The following is the code to implement Count property in C# −
Live Demo
using System;
using System.Collections;
class Demo {
public static void Main() {
ArrayList arrList = new ArrayList();
arrList.Add(98);
arrList.Add(55);
arrList.Add(65);
arrList.Add(34);
Console.WriteLine("Count = " + arrList.Count);
}
}
Count = 4
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "The Count property in the ArrayList class counts the number of elements in the ArrayList."
},
{
"code": null,
"e": 1193,
"s": 1152,
"text": "Firstly, add elements to the ArrayList −"
},
{
"code": null,
"e": 1299,
"s": 1193,
"text": "ArrayList arrList = new ArrayList();\n\narrList.Add(98);\narrList.Add(55);\narrList.Add(65);\narrList.Add(34);"
},
{
"code": null,
"e": 1338,
"s": 1299,
"text": "Then get the count of the array list −"
},
{
"code": null,
"e": 1352,
"s": 1338,
"text": "arrList.Count"
},
{
"code": null,
"e": 1414,
"s": 1352,
"text": "The following is the code to implement Count property in C# −"
},
{
"code": null,
"e": 1425,
"s": 1414,
"text": " Live Demo"
},
{
"code": null,
"e": 1708,
"s": 1425,
"text": "using System;\nusing System.Collections;\n\nclass Demo {\n public static void Main() {\n ArrayList arrList = new ArrayList();\n\n arrList.Add(98);\n arrList.Add(55);\n arrList.Add(65);\n arrList.Add(34);\n\n Console.WriteLine(\"Count = \" + arrList.Count);\n\n }\n}"
},
{
"code": null,
"e": 1718,
"s": 1708,
"text": "Count = 4"
}
] |
MATLAB - Division (Left, Right) of Matrics
|
You can divide two matrices using left (\) or right (/) division operators. Both the operand matrices must have the same number of rows and columns.
Create a script file with the following code −
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a / b
d = a \ b
When you run the file, it displays the following result −
c =
-0.52542 0.68644 0.66102
-0.42373 0.94068 1.01695
-0.32203 1.19492 1.37288
d =
-3.27778 -1.05556 -4.86111
-0.11111 0.11111 -0.27778
3.05556 1.27778 4.30556
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": 2290,
"s": 2141,
"text": "You can divide two matrices using left (\\) or right (/) division operators. Both the operand matrices must have the same number of rows and columns."
},
{
"code": null,
"e": 2337,
"s": 2290,
"text": "Create a script file with the following code −"
},
{
"code": null,
"e": 2415,
"s": 2337,
"text": "a = [ 1 2 3 ; 4 5 6; 7 8 9];\nb = [ 7 5 6 ; 2 0 8; 5 7 1];\nc = a / b\nd = a \\ b"
},
{
"code": null,
"e": 2473,
"s": 2415,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 2676,
"s": 2473,
"text": "c =\n\n -0.52542 0.68644 0.66102\n -0.42373 0.94068 1.01695\n -0.32203 1.19492 1.37288\n\nd =\n\n -3.27778 -1.05556 -4.86111\n -0.11111 0.11111 -0.27778\n 3.05556 1.27778 4.30556\n"
},
{
"code": null,
"e": 2709,
"s": 2676,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2722,
"s": 2709,
"text": " Nouman Azam"
},
{
"code": null,
"e": 2757,
"s": 2722,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 2770,
"s": 2757,
"text": " Nouman Azam"
},
{
"code": null,
"e": 2803,
"s": 2770,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2812,
"s": 2803,
"text": " Sanjeev"
},
{
"code": null,
"e": 2845,
"s": 2812,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2861,
"s": 2845,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2894,
"s": 2861,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2910,
"s": 2894,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2943,
"s": 2910,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2960,
"s": 2943,
"text": " Phinite Academy"
},
{
"code": null,
"e": 2967,
"s": 2960,
"text": " Print"
},
{
"code": null,
"e": 2978,
"s": 2967,
"text": " Add Notes"
}
] |
<mat-select> in Angular Material
|
13 Apr, 2021
Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-select> tag is used to display the options in a dropdown.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatSelectModule’ from ‘@angular/material/select’ in the app.module.ts file.
Then use <mat-select> tag to group all the items inside this group tag.
Inside the <mat-select> tag we need to use <mat-option> tag for every item.
We can also disable options using the disabled property.
Once done with the above steps then serve or start the project.
Code Implementation:
app.module.ts:
Javascript
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatSelectModule,MatFormFieldModule } from '@angular/material'; import { AppComponent } from './example.component'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], imports: [ CommonModule, FormsModule, MatSelectModule, MatFormFieldModule ], }) export class AppModule {}
app.component.html:
HTML
<mat-form-field appearance="fill"> <mat-label>Choose a technology</mat-label> <mat-select> <mat-option value="html"> HTML </mat-option> <mat-option value="css" disabled>CSS (disabled)</mat-option> <mat-option value="js">JAVASCRIPT</mat-option> </mat-select></mat-form-field>
Output:
Reference: https://material.angular.io/components/select/overview
Angular-material
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 397,
"s": 28,
"text": "Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-select> tag is used to display the options in a dropdown."
},
{
"code": null,
"e": 418,
"s": 397,
"text": "Installation syntax:"
},
{
"code": null,
"e": 443,
"s": 418,
"text": "ng add @angular/material"
},
{
"code": null,
"e": 453,
"s": 443,
"text": "Approach:"
},
{
"code": null,
"e": 524,
"s": 453,
"text": "First, install the angular material using the above-mentioned command."
},
{
"code": null,
"e": 643,
"s": 524,
"text": "After completing the installation, Import ‘MatSelectModule’ from ‘@angular/material/select’ in the app.module.ts file."
},
{
"code": null,
"e": 715,
"s": 643,
"text": "Then use <mat-select> tag to group all the items inside this group tag."
},
{
"code": null,
"e": 791,
"s": 715,
"text": "Inside the <mat-select> tag we need to use <mat-option> tag for every item."
},
{
"code": null,
"e": 848,
"s": 791,
"text": "We can also disable options using the disabled property."
},
{
"code": null,
"e": 912,
"s": 848,
"text": "Once done with the above steps then serve or start the project."
},
{
"code": null,
"e": 933,
"s": 912,
"text": "Code Implementation:"
},
{
"code": null,
"e": 949,
"s": 933,
"text": "app.module.ts: "
},
{
"code": null,
"e": 960,
"s": 949,
"text": "Javascript"
},
{
"code": "import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatSelectModule,MatFormFieldModule } from '@angular/material'; import { AppComponent } from './example.component'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], imports: [ CommonModule, FormsModule, MatSelectModule, MatFormFieldModule ], }) export class AppModule {}",
"e": 1429,
"s": 960,
"text": null
},
{
"code": null,
"e": 1449,
"s": 1429,
"text": "app.component.html:"
},
{
"code": null,
"e": 1454,
"s": 1449,
"text": "HTML"
},
{
"code": "<mat-form-field appearance=\"fill\"> <mat-label>Choose a technology</mat-label> <mat-select> <mat-option value=\"html\"> HTML </mat-option> <mat-option value=\"css\" disabled>CSS (disabled)</mat-option> <mat-option value=\"js\">JAVASCRIPT</mat-option> </mat-select></mat-form-field>",
"e": 1741,
"s": 1454,
"text": null
},
{
"code": null,
"e": 1749,
"s": 1741,
"text": "Output:"
},
{
"code": null,
"e": 1815,
"s": 1749,
"text": "Reference: https://material.angular.io/components/select/overview"
},
{
"code": null,
"e": 1832,
"s": 1815,
"text": "Angular-material"
},
{
"code": null,
"e": 1842,
"s": 1832,
"text": "AngularJS"
},
{
"code": null,
"e": 1859,
"s": 1842,
"text": "Web Technologies"
},
{
"code": null,
"e": 1957,
"s": 1859,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1981,
"s": 1957,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 2016,
"s": 1981,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 2040,
"s": 2016,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 2093,
"s": 2040,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 2142,
"s": 2093,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 2175,
"s": 2142,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2237,
"s": 2175,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2298,
"s": 2237,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2348,
"s": 2298,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Find Minimum Number Of Arrows Needed To Burst All Balloons
|
30 Nov, 2021
Given an array points[][] of size N, where points[i] represents a balloon over the area of X-coordinates from points[i][0] to points[i][1]. The Y-coordinates don’t matter. All the balloons are required to be burst. To burst a balloon, an arrow can be launched at point (x, 0) and it travels vertically upwards and bursts all the balloons which satisfy the condition points[i][0] <= x <= points[i][1]. The task is to find the minimum number of arrows required to burst all the balloons.
Examples:
Input: N = 4, points = {{10, 16}, {2, 8}, {1, 6}, {7, 12}}Output: 2Explanation: One way is to shoot one arrow for example at x = 6 (bursting the balloons [2, 8] and [1, 6]) and another arrow at x = 11 (bursting the other two balloons).
Input: N = 1, points = {{1, 6}}Output: 1Explanation: One single arrow can burst the balloon.
Approach: The given problem can be solved by using the Greedy Approach to find the balloons which are overlapping with each other so that the arrow can pass through all such balloons and burst them. To do that optimally, sort the array with respect to the X-coordinate in ascending order. So, now consider 2 balloons, if the second balloon is starting before the first balloon then it must be ending after the first balloon or at the same position.
For example [1, 6], [2, 8] -> the second balloon starting position i.e 2 which is before the ending position of the first balloon i.e 6, and since the array is sorted the end of the second balloon is always greater than the end of the first balloon. The second balloon end i.e 8 is after the end of the first balloon i.e 6. which shows us the overlapping is there between [2, 6].
Follow the steps below to solve the problem:
Sort the array according to the end position of balloons using the comparator/lambda expression Arrays.sort(points, (a, b)-> Integer.compare(a[1], b[1])).
Make a variable arrow and initialize it with 1( as a minimum one arrow is going to be needed to burst the balloons )
Make a variable end and initialize it with points[0][1] that will be storing the end of the first balloon.
Iterate over the range [1, N) using the variable i and perform the following steps:Check whether the start of the next balloon points[i][0] is less than the end variable end.If so, then continue the iteration.Else, increase the count of the arrow by 1 and set the value of end as points[i][1].
Check whether the start of the next balloon points[i][0] is less than the end variable end.
If so, then continue the iteration.
Else, increase the count of the arrow by 1 and set the value of end as points[i][1].
After completing the above steps, print the value of arrow as the resultant count of arrows required.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; bool cmp(vector<int> a, vector<int> b){ return b[1] > a[1];} // Function to find the minimum count of// arrows required to burst all balloonsint minArrows(vector<vector<int>> points){ // To sort our array according // to end position of balloons sort(points.begin(), points.end(), cmp); // Initialize end variable with // the end of first balloon int end = points[0][1]; // Initialize arrow with 1 int arrow = 1; // Iterate through the entire // arrow of points for (int i = 1; i < points.size(); i++) { // If the start of ith balloon // <= end than do nothing if (points[i][0] <= end) { continue; } // if start of the next balloon // >= end of the first balloon // then increment the arrow else { // Update the new end end = points[i][1]; arrow++; } } // Return the total count of arrows return arrow;} // Driver codeint main(){ vector<vector<int>> points = {{10, 16}, {2, 8}, {1, 6}, {7, 12}}; cout << (minArrows(points)); return 0;} // This code is contributed by Potta Lokesh
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to find the minimum count of // arrows required to burst all balloons public static int minArrows(int points[][]) { // To sort our array according // to end position of balloons Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1])); // Initialize end variable with // the end of first balloon int end = points[0][1]; // Initialize arrow with 1 int arrow = 1; // Iterate through the entire // arrow of points for (int i = 1; i < points.length; i++) { // If the start of ith balloon // <= end than do nothing if (points[i][0] <= end) { continue; } // if start of the next balloon // >= end of the first balloon // then increment the arrow else { // Update the new end end = points[i][1]; arrow++; } } // Return the total count of arrows return arrow; } // Driver Code public static void main(String[] args) { int[][] points = { { 10, 16 }, { 2, 8 }, { 1, 6 }, { 7, 12 } }; System.out.println( minArrows(points)); }}
# Python3 program for the above approach # Function to find the minimum count of# arrows required to burst all balloonsdef minArrows(points): # To sort our array according # to end position of balloons points = sorted(points, key = lambda x:x[1]) # Initialize end variable with # the end of first balloon end = points[0][1]; # Initialize arrow with 1 arrow = 1; # Iterate through the entire # arrow of points for i in range (1, len(points)) : # If the start of ith balloon # <= end than do nothing if (points[i][0] <= end) : continue; # if start of the next balloon # >= end of the first balloon # then increment the arrow else : # Update the new end end = points[i][1] arrow = arrow + 1 # Return the total count of arrows return arrow; # Driver Codepoints = [[10, 16 ], [ 2, 8 ], [1, 6 ], [ 7, 12 ]]print(minArrows(points)) # This code is contributed by AR_Gaurav
// C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the minimum count of // arrows required to burst all balloons public static int minArrows(int[][] points) { // To sort our array according // to end position of balloons // Array.Sort(points, (a, b) => {return a[1] - b[1];}); Comparer<int> comparer = Comparer<int>.Default; Array.Sort<int[]>(points, (x,y) => comparer.Compare(x[1],y[1])); // Initialize end variable with // the end of first balloon int end = points[0][1]; // Initialize arrow with 1 int arrow = 1; // Iterate through the entire // arrow of points for (int i = 1; i < points.Length; i++) { // If the start of ith balloon // <= end than do nothing if (points[i][0] <= end) { continue; } // if start of the next balloon // >= end of the first balloon // then increment the arrow else { // Update the new end end = points[i][1]; arrow++; } } // Return the total count of arrows return arrow; } // Driver Code public static void Main(String[] args) { int[][] points = { new int[] { 10, 16 }, new int[] { 2, 8 }, new int[]{ 1, 6 }, new int[]{ 7, 12 } }; Console.Write(minArrows(points)); }} // This code is contributed by saurabh_jaiswal.
<script>// Javascript program for the above approach function cmp(a, b) { return a[1] - b[1];} // Function to find the minimum count of// arrows required to burst all balloonsfunction minArrows(points){ // To sort our array according // to end position of balloons points.sort(cmp); // Initialize end variable with // the end of first balloon let end = points[0][1]; // Initialize arrow with 1 let arrow = 1; // Iterate through the entire // arrow of points for (let i = 1; i < points.length; i++) { // If the start of ith balloon // <= end than do nothing if (points[i][0] <= end) { continue; } // if start of the next balloon // >= end of the first balloon // then increment the arrow else { // Update the new end end = points[i][1]; arrow++; } } // Return the total count of arrows return arrow;} // Driver codelet points = [ [10, 16], [2, 8], [1, 6], [7, 12],];document.write(minArrows(points)); // This code is contributed by gfgking.</script>
2
Time Complexity: O(N*log(N))Auxiliary Space: O(1)
lokeshpotta20
AR_Gaurav
gfgking
_saurabh_jaiswal
Arrays
Greedy
Mathematical
Sorting
Arrays
Greedy
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
What is Data Structure: Types, Classifications and Applications
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 538,
"s": 52,
"text": "Given an array points[][] of size N, where points[i] represents a balloon over the area of X-coordinates from points[i][0] to points[i][1]. The Y-coordinates don’t matter. All the balloons are required to be burst. To burst a balloon, an arrow can be launched at point (x, 0) and it travels vertically upwards and bursts all the balloons which satisfy the condition points[i][0] <= x <= points[i][1]. The task is to find the minimum number of arrows required to burst all the balloons."
},
{
"code": null,
"e": 548,
"s": 538,
"text": "Examples:"
},
{
"code": null,
"e": 784,
"s": 548,
"text": "Input: N = 4, points = {{10, 16}, {2, 8}, {1, 6}, {7, 12}}Output: 2Explanation: One way is to shoot one arrow for example at x = 6 (bursting the balloons [2, 8] and [1, 6]) and another arrow at x = 11 (bursting the other two balloons)."
},
{
"code": null,
"e": 877,
"s": 784,
"text": "Input: N = 1, points = {{1, 6}}Output: 1Explanation: One single arrow can burst the balloon."
},
{
"code": null,
"e": 1326,
"s": 877,
"text": "Approach: The given problem can be solved by using the Greedy Approach to find the balloons which are overlapping with each other so that the arrow can pass through all such balloons and burst them. To do that optimally, sort the array with respect to the X-coordinate in ascending order. So, now consider 2 balloons, if the second balloon is starting before the first balloon then it must be ending after the first balloon or at the same position."
},
{
"code": null,
"e": 1706,
"s": 1326,
"text": "For example [1, 6], [2, 8] -> the second balloon starting position i.e 2 which is before the ending position of the first balloon i.e 6, and since the array is sorted the end of the second balloon is always greater than the end of the first balloon. The second balloon end i.e 8 is after the end of the first balloon i.e 6. which shows us the overlapping is there between [2, 6]."
},
{
"code": null,
"e": 1751,
"s": 1706,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1906,
"s": 1751,
"text": "Sort the array according to the end position of balloons using the comparator/lambda expression Arrays.sort(points, (a, b)-> Integer.compare(a[1], b[1]))."
},
{
"code": null,
"e": 2023,
"s": 1906,
"text": "Make a variable arrow and initialize it with 1( as a minimum one arrow is going to be needed to burst the balloons )"
},
{
"code": null,
"e": 2130,
"s": 2023,
"text": "Make a variable end and initialize it with points[0][1] that will be storing the end of the first balloon."
},
{
"code": null,
"e": 2424,
"s": 2130,
"text": "Iterate over the range [1, N) using the variable i and perform the following steps:Check whether the start of the next balloon points[i][0] is less than the end variable end.If so, then continue the iteration.Else, increase the count of the arrow by 1 and set the value of end as points[i][1]."
},
{
"code": null,
"e": 2516,
"s": 2424,
"text": "Check whether the start of the next balloon points[i][0] is less than the end variable end."
},
{
"code": null,
"e": 2552,
"s": 2516,
"text": "If so, then continue the iteration."
},
{
"code": null,
"e": 2637,
"s": 2552,
"text": "Else, increase the count of the arrow by 1 and set the value of end as points[i][1]."
},
{
"code": null,
"e": 2739,
"s": 2637,
"text": "After completing the above steps, print the value of arrow as the resultant count of arrows required."
},
{
"code": null,
"e": 2790,
"s": 2739,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2794,
"s": 2790,
"text": "C++"
},
{
"code": null,
"e": 2799,
"s": 2794,
"text": "Java"
},
{
"code": null,
"e": 2807,
"s": 2799,
"text": "Python3"
},
{
"code": null,
"e": 2810,
"s": 2807,
"text": "C#"
},
{
"code": null,
"e": 2821,
"s": 2810,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; bool cmp(vector<int> a, vector<int> b){ return b[1] > a[1];} // Function to find the minimum count of// arrows required to burst all balloonsint minArrows(vector<vector<int>> points){ // To sort our array according // to end position of balloons sort(points.begin(), points.end(), cmp); // Initialize end variable with // the end of first balloon int end = points[0][1]; // Initialize arrow with 1 int arrow = 1; // Iterate through the entire // arrow of points for (int i = 1; i < points.size(); i++) { // If the start of ith balloon // <= end than do nothing if (points[i][0] <= end) { continue; } // if start of the next balloon // >= end of the first balloon // then increment the arrow else { // Update the new end end = points[i][1]; arrow++; } } // Return the total count of arrows return arrow;} // Driver codeint main(){ vector<vector<int>> points = {{10, 16}, {2, 8}, {1, 6}, {7, 12}}; cout << (minArrows(points)); return 0;} // This code is contributed by Potta Lokesh",
"e": 4072,
"s": 2821,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to find the minimum count of // arrows required to burst all balloons public static int minArrows(int points[][]) { // To sort our array according // to end position of balloons Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1])); // Initialize end variable with // the end of first balloon int end = points[0][1]; // Initialize arrow with 1 int arrow = 1; // Iterate through the entire // arrow of points for (int i = 1; i < points.length; i++) { // If the start of ith balloon // <= end than do nothing if (points[i][0] <= end) { continue; } // if start of the next balloon // >= end of the first balloon // then increment the arrow else { // Update the new end end = points[i][1]; arrow++; } } // Return the total count of arrows return arrow; } // Driver Code public static void main(String[] args) { int[][] points = { { 10, 16 }, { 2, 8 }, { 1, 6 }, { 7, 12 } }; System.out.println( minArrows(points)); }}",
"e": 5439,
"s": 4072,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the minimum count of# arrows required to burst all balloonsdef minArrows(points): # To sort our array according # to end position of balloons points = sorted(points, key = lambda x:x[1]) # Initialize end variable with # the end of first balloon end = points[0][1]; # Initialize arrow with 1 arrow = 1; # Iterate through the entire # arrow of points for i in range (1, len(points)) : # If the start of ith balloon # <= end than do nothing if (points[i][0] <= end) : continue; # if start of the next balloon # >= end of the first balloon # then increment the arrow else : # Update the new end end = points[i][1] arrow = arrow + 1 # Return the total count of arrows return arrow; # Driver Codepoints = [[10, 16 ], [ 2, 8 ], [1, 6 ], [ 7, 12 ]]print(minArrows(points)) # This code is contributed by AR_Gaurav",
"e": 6464,
"s": 5439,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the minimum count of // arrows required to burst all balloons public static int minArrows(int[][] points) { // To sort our array according // to end position of balloons // Array.Sort(points, (a, b) => {return a[1] - b[1];}); Comparer<int> comparer = Comparer<int>.Default; Array.Sort<int[]>(points, (x,y) => comparer.Compare(x[1],y[1])); // Initialize end variable with // the end of first balloon int end = points[0][1]; // Initialize arrow with 1 int arrow = 1; // Iterate through the entire // arrow of points for (int i = 1; i < points.Length; i++) { // If the start of ith balloon // <= end than do nothing if (points[i][0] <= end) { continue; } // if start of the next balloon // >= end of the first balloon // then increment the arrow else { // Update the new end end = points[i][1]; arrow++; } } // Return the total count of arrows return arrow; } // Driver Code public static void Main(String[] args) { int[][] points = { new int[] { 10, 16 }, new int[] { 2, 8 }, new int[]{ 1, 6 }, new int[]{ 7, 12 } }; Console.Write(minArrows(points)); }} // This code is contributed by saurabh_jaiswal.",
"e": 8021,
"s": 6464,
"text": null
},
{
"code": "<script>// Javascript program for the above approach function cmp(a, b) { return a[1] - b[1];} // Function to find the minimum count of// arrows required to burst all balloonsfunction minArrows(points){ // To sort our array according // to end position of balloons points.sort(cmp); // Initialize end variable with // the end of first balloon let end = points[0][1]; // Initialize arrow with 1 let arrow = 1; // Iterate through the entire // arrow of points for (let i = 1; i < points.length; i++) { // If the start of ith balloon // <= end than do nothing if (points[i][0] <= end) { continue; } // if start of the next balloon // >= end of the first balloon // then increment the arrow else { // Update the new end end = points[i][1]; arrow++; } } // Return the total count of arrows return arrow;} // Driver codelet points = [ [10, 16], [2, 8], [1, 6], [7, 12],];document.write(minArrows(points)); // This code is contributed by gfgking.</script>",
"e": 9043,
"s": 8021,
"text": null
},
{
"code": null,
"e": 9045,
"s": 9043,
"text": "2"
},
{
"code": null,
"e": 9097,
"s": 9047,
"text": "Time Complexity: O(N*log(N))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9111,
"s": 9097,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 9121,
"s": 9111,
"text": "AR_Gaurav"
},
{
"code": null,
"e": 9129,
"s": 9121,
"text": "gfgking"
},
{
"code": null,
"e": 9146,
"s": 9129,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 9153,
"s": 9146,
"text": "Arrays"
},
{
"code": null,
"e": 9160,
"s": 9153,
"text": "Greedy"
},
{
"code": null,
"e": 9173,
"s": 9160,
"text": "Mathematical"
},
{
"code": null,
"e": 9181,
"s": 9173,
"text": "Sorting"
},
{
"code": null,
"e": 9188,
"s": 9181,
"text": "Arrays"
},
{
"code": null,
"e": 9195,
"s": 9188,
"text": "Greedy"
},
{
"code": null,
"e": 9208,
"s": 9195,
"text": "Mathematical"
},
{
"code": null,
"e": 9216,
"s": 9208,
"text": "Sorting"
},
{
"code": null,
"e": 9314,
"s": 9216,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9346,
"s": 9314,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9371,
"s": 9346,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 9418,
"s": 9371,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 9449,
"s": 9418,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 9513,
"s": 9449,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9564,
"s": 9513,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 9615,
"s": 9564,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 9675,
"s": 9615,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 9733,
"s": 9675,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Python | Check for Whitespace in List
|
23 Jan, 2020
Sometimes, we might have a problem in which we need to check if the List of strings has any of blank spaces. This kind of problem can be in Machine Learning domain to get specific type of data set. Let’s discuss certain ways in which this kind of problem can be solved.
Method #1 : Using regex + any()This kind of problem can be solved using the regex utility offered by python. By feeding the appropriate regex string in search(), we can check presence of space in a string and iterate through entire list using any().
# Python3 code to demonstrate working of# Check for Whitespace in List# Using regex and any()import re # initializing list test_list = ["Geeks forGeeks", "is", "best"] # printing original listprint("The original list is : " + str(test_list)) # Check for Whitespace in List# Using regex and any()res = any(bool(re.search(r"\s", ele)) for ele in test_list) # printing result print("Does any string contain spaces ? " + str(res))
The original list is : ['Geeks forGeeks', 'is', 'best']
Does any string contain spaces ? True
Method #2 : Using in operator + any()This task can also be performed using in operator. Just required to check for a space in the string. The verdict returned is true even if a single space is found in any of string of list and false otherwise.
# Python3 code to demonstrate working of# Check for Whitespace in List# Using in operator + any()import re # initializing list test_list = ["Geeks forGeeks", "is", "best"] # printing original listprint("The original list is : " + str(test_list)) # Check for Whitespace in List# Using in operator + any()res = any('' in ele for ele in test_list) # printing result print("Does any string contain spaces ? " + str(res))
The original list is : ['Geeks forGeeks', 'is', 'best']
Does any string contain spaces ? True
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 298,
"s": 28,
"text": "Sometimes, we might have a problem in which we need to check if the List of strings has any of blank spaces. This kind of problem can be in Machine Learning domain to get specific type of data set. Let’s discuss certain ways in which this kind of problem can be solved."
},
{
"code": null,
"e": 548,
"s": 298,
"text": "Method #1 : Using regex + any()This kind of problem can be solved using the regex utility offered by python. By feeding the appropriate regex string in search(), we can check presence of space in a string and iterate through entire list using any()."
},
{
"code": "# Python3 code to demonstrate working of# Check for Whitespace in List# Using regex and any()import re # initializing list test_list = [\"Geeks forGeeks\", \"is\", \"best\"] # printing original listprint(\"The original list is : \" + str(test_list)) # Check for Whitespace in List# Using regex and any()res = any(bool(re.search(r\"\\s\", ele)) for ele in test_list) # printing result print(\"Does any string contain spaces ? \" + str(res))",
"e": 979,
"s": 548,
"text": null
},
{
"code": null,
"e": 1074,
"s": 979,
"text": "The original list is : ['Geeks forGeeks', 'is', 'best']\nDoes any string contain spaces ? True\n"
},
{
"code": null,
"e": 1321,
"s": 1076,
"text": "Method #2 : Using in operator + any()This task can also be performed using in operator. Just required to check for a space in the string. The verdict returned is true even if a single space is found in any of string of list and false otherwise."
},
{
"code": "# Python3 code to demonstrate working of# Check for Whitespace in List# Using in operator + any()import re # initializing list test_list = [\"Geeks forGeeks\", \"is\", \"best\"] # printing original listprint(\"The original list is : \" + str(test_list)) # Check for Whitespace in List# Using in operator + any()res = any('' in ele for ele in test_list) # printing result print(\"Does any string contain spaces ? \" + str(res))",
"e": 1742,
"s": 1321,
"text": null
},
{
"code": null,
"e": 1837,
"s": 1742,
"text": "The original list is : ['Geeks forGeeks', 'is', 'best']\nDoes any string contain spaces ? True\n"
},
{
"code": null,
"e": 1858,
"s": 1837,
"text": "Python list-programs"
},
{
"code": null,
"e": 1865,
"s": 1858,
"text": "Python"
},
{
"code": null,
"e": 1881,
"s": 1865,
"text": "Python Programs"
},
{
"code": null,
"e": 1979,
"s": 1881,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1997,
"s": 1979,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2039,
"s": 1997,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2061,
"s": 2039,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2096,
"s": 2061,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2122,
"s": 2096,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2165,
"s": 2122,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2187,
"s": 2165,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2226,
"s": 2187,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2264,
"s": 2226,
"text": "Python | Convert a list to dictionary"
}
] |
Singleton Design Pattern | Implementation
|
29 Nov, 2020
Singleton Design Pattern | IntroductionThe singleton pattern is one of the simplest design patterns. Sometimes we need to have only one instance of our class for example a single DB connection shared by multiple objects as creating a separate DB connection for every object may be costly. Similarly, there can be a single configuration manager or error manager in an application that handles all problems instead of creating multiple managers.Definition: The singleton pattern is a design pattern that restricts the instantiation of a class to one object. Let’s see various design options for implementing such a class. If you have a good handle on static class variables and access modifiers this should not be a difficult task. Method 1: Classic Implementation
Java
// Classical Java implementation of singleton// design patternclass Singleton{ private static Singleton obj; // private constructor to force use of // getInstance() to create Singleton object private Singleton() {} public static Singleton getInstance() { if (obj==null) obj = new Singleton(); return obj; }}
Here we have declared getInstance() static so that we can call it without instantiating the class. The first time getInstance() is called it creates a new singleton object and after that it just returns the same object. Note that Singleton obj is not created until we need it and call getInstance() method. This is called lazy instantiation.The main problem with above method is that it is not thread safe. Consider the following execution sequence.
This execution sequence creates two objects for singleton. Therefore this classic implementation is not thread safe. Method 2: make getInstance() synchronized
Java
// Thread Synchronized Java implementation of// singleton design patternclass Singleton{ private static Singleton obj; private Singleton() {} // Only one thread can execute this at a time public static synchronized Singleton getInstance() { if (obj==null) obj = new Singleton(); return obj; }}
Here using synchronized makes sure that only one thread at a time can execute getInstance(). The main disadvantage of this is method is that using synchronized every time while creating the singleton object is expensive and may decrease the performance of your program. However if performance of getInstance() is not critical for your application this method provides a clean and simple solution. Method 3: Eager Instantiation
Java
// Static initializer based Java implementation of// singleton design patternclass Singleton{ private static Singleton obj = new Singleton(); private Singleton() {} public static Singleton getInstance() { return obj; }}
Here we have created instance of singleton in static initializer. JVM executes static initializer when the class is loaded and hence this is guaranteed to be thread safe. Use this method only when your singleton class is light and is used throughout the execution of your program. Method 4 (Best): Use “Double Checked Locking” If you notice carefully once an object is created synchronization is no longer useful because now obj will not be null and any sequence of operations will lead to consistent results. So we will only acquire lock on the getInstance() once, when the obj is null. This way we only synchronize the first way through, just what we want.
Java
// Double Checked Locking based Java implementation of// singleton design patternclass Singleton{ private static volatile Singleton obj = null; private Singleton() {} public static Singleton getInstance() { if (obj == null) { // To make thread safe synchronized (Singleton.class) { // check again as multiple threads // can reach above step if (obj==null) obj = new Singleton(); } } return obj; }}
We have declared the obj volatile which ensures that multiple threads offer the obj variable correctly when it is being initialized to Singleton instance. This method drastically reduces the overhead of calling the synchronized method every time. References: Head First Design Patterns book (Highly recommended) https://en.wikipedia.org/wiki/Singleton_patternPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above
sanzzzay
Design Pattern
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Builder Design Pattern
Unified Modeling Language (UML) | An Introduction
Introduction of Programming Paradigms
MVC Design Pattern
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Nov, 2020"
},
{
"code": null,
"e": 819,
"s": 54,
"text": "Singleton Design Pattern | IntroductionThe singleton pattern is one of the simplest design patterns. Sometimes we need to have only one instance of our class for example a single DB connection shared by multiple objects as creating a separate DB connection for every object may be costly. Similarly, there can be a single configuration manager or error manager in an application that handles all problems instead of creating multiple managers.Definition: The singleton pattern is a design pattern that restricts the instantiation of a class to one object. Let’s see various design options for implementing such a class. If you have a good handle on static class variables and access modifiers this should not be a difficult task. Method 1: Classic Implementation "
},
{
"code": null,
"e": 824,
"s": 819,
"text": "Java"
},
{
"code": "// Classical Java implementation of singleton// design patternclass Singleton{ private static Singleton obj; // private constructor to force use of // getInstance() to create Singleton object private Singleton() {} public static Singleton getInstance() { if (obj==null) obj = new Singleton(); return obj; }}",
"e": 1180,
"s": 824,
"text": null
},
{
"code": null,
"e": 1631,
"s": 1180,
"text": "Here we have declared getInstance() static so that we can call it without instantiating the class. The first time getInstance() is called it creates a new singleton object and after that it just returns the same object. Note that Singleton obj is not created until we need it and call getInstance() method. This is called lazy instantiation.The main problem with above method is that it is not thread safe. Consider the following execution sequence. "
},
{
"code": null,
"e": 1792,
"s": 1631,
"text": "This execution sequence creates two objects for singleton. Therefore this classic implementation is not thread safe. Method 2: make getInstance() synchronized "
},
{
"code": null,
"e": 1797,
"s": 1792,
"text": "Java"
},
{
"code": "// Thread Synchronized Java implementation of// singleton design patternclass Singleton{ private static Singleton obj; private Singleton() {} // Only one thread can execute this at a time public static synchronized Singleton getInstance() { if (obj==null) obj = new Singleton(); return obj; }}",
"e": 2136,
"s": 1797,
"text": null
},
{
"code": null,
"e": 2565,
"s": 2136,
"text": "Here using synchronized makes sure that only one thread at a time can execute getInstance(). The main disadvantage of this is method is that using synchronized every time while creating the singleton object is expensive and may decrease the performance of your program. However if performance of getInstance() is not critical for your application this method provides a clean and simple solution. Method 3: Eager Instantiation "
},
{
"code": null,
"e": 2570,
"s": 2565,
"text": "Java"
},
{
"code": "// Static initializer based Java implementation of// singleton design patternclass Singleton{ private static Singleton obj = new Singleton(); private Singleton() {} public static Singleton getInstance() { return obj; }}",
"e": 2814,
"s": 2570,
"text": null
},
{
"code": null,
"e": 3475,
"s": 2814,
"text": "Here we have created instance of singleton in static initializer. JVM executes static initializer when the class is loaded and hence this is guaranteed to be thread safe. Use this method only when your singleton class is light and is used throughout the execution of your program. Method 4 (Best): Use “Double Checked Locking” If you notice carefully once an object is created synchronization is no longer useful because now obj will not be null and any sequence of operations will lead to consistent results. So we will only acquire lock on the getInstance() once, when the obj is null. This way we only synchronize the first way through, just what we want. "
},
{
"code": null,
"e": 3480,
"s": 3475,
"text": "Java"
},
{
"code": "// Double Checked Locking based Java implementation of// singleton design patternclass Singleton{ private static volatile Singleton obj = null; private Singleton() {} public static Singleton getInstance() { if (obj == null) { // To make thread safe synchronized (Singleton.class) { // check again as multiple threads // can reach above step if (obj==null) obj = new Singleton(); } } return obj; }}",
"e": 4032,
"s": 3480,
"text": null
},
{
"code": null,
"e": 4517,
"s": 4032,
"text": "We have declared the obj volatile which ensures that multiple threads offer the obj variable correctly when it is being initialized to Singleton instance. This method drastically reduces the overhead of calling the synchronized method every time. References: Head First Design Patterns book (Highly recommended) https://en.wikipedia.org/wiki/Singleton_patternPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 4526,
"s": 4517,
"text": "sanzzzay"
},
{
"code": null,
"e": 4541,
"s": 4526,
"text": "Design Pattern"
},
{
"code": null,
"e": 4546,
"s": 4541,
"text": "Java"
},
{
"code": null,
"e": 4551,
"s": 4546,
"text": "Java"
},
{
"code": null,
"e": 4649,
"s": 4551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4687,
"s": 4649,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 4710,
"s": 4687,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 4760,
"s": 4710,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 4798,
"s": 4760,
"text": "Introduction of Programming Paradigms"
},
{
"code": null,
"e": 4817,
"s": 4798,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 4832,
"s": 4817,
"text": "Arrays in Java"
},
{
"code": null,
"e": 4868,
"s": 4832,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 4912,
"s": 4868,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 4937,
"s": 4912,
"text": "Reverse a string in Java"
}
] |
How to Make get() Method Request in Java Spring?
|
26 Aug, 2021
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, etc.
There are several other concepts present in java that increase the user-friendly interaction between the java code and the programmer such as generic, Access specifiers, Annotations, etc these features add an extra property to the class as well as the method of the java program. In this article, we will discuss what is the GetMapping() annotation in java.
GetMapping() annotation mainly use in the spring boot applications that are used for handling the incoming request from the client by matching the incoming request header from the clientside
Syntax:
@GetMapping()
Parameters: Annotation contains an URL expression
Now let us discuss how to initialize Spring in web projects. Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using spring initializer and then use an IDE to create a sample GET route.
Steps to initialize Spring in web projects
They are provided below in a sequential manner with visual aids as follows:
Go to Spring InitializrFill in the details as per the requirements. For this application shown below asities:
Go to Spring Initializr
Fill in the details as per the requirements. For this application shown below asities:
Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web
Step 1: Click on Generate which will download the starter project.
Step 2: Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync.
Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.
Step 3: Go to src->main->java->com.gfg.Spring.boot.app, create a java class with name as Controller and add the annotation @RestController. Now create a GET API as shown below:”
@RestController
public class Controller {
@GetMapping("/get") public String home() {
return "This is the get request";
}
@GetMapping("/get/check") public String home1() {
return "This is the get check request";
}
}
Step 4: This application is now ready to run. Run the SpringBootAppApplication class and wait for the Tomcat server to start.
Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file.
Step 5: Now go to the browser and enter the URL localhost:8080. Observe the output and now do the same for localhost:8080/get/check
Geeks, we are done with get() method request in Spring as perceived from the above pop-up. Hence these were the steps at all.
zack_aayush
Java-Spring
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": 54,
"s": 26,
"text": "\n26 Aug, 2021"
},
{
"code": null,
"e": 466,
"s": 54,
"text": "Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, etc."
},
{
"code": null,
"e": 824,
"s": 466,
"text": "There are several other concepts present in java that increase the user-friendly interaction between the java code and the programmer such as generic, Access specifiers, Annotations, etc these features add an extra property to the class as well as the method of the java program. In this article, we will discuss what is the GetMapping() annotation in java."
},
{
"code": null,
"e": 1015,
"s": 824,
"text": "GetMapping() annotation mainly use in the spring boot applications that are used for handling the incoming request from the client by matching the incoming request header from the clientside"
},
{
"code": null,
"e": 1023,
"s": 1015,
"text": "Syntax:"
},
{
"code": null,
"e": 1037,
"s": 1023,
"text": "@GetMapping()"
},
{
"code": null,
"e": 1088,
"s": 1037,
"text": "Parameters: Annotation contains an URL expression "
},
{
"code": null,
"e": 1570,
"s": 1088,
"text": "Now let us discuss how to initialize Spring in web projects. Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using spring initializer and then use an IDE to create a sample GET route."
},
{
"code": null,
"e": 1613,
"s": 1570,
"text": "Steps to initialize Spring in web projects"
},
{
"code": null,
"e": 1689,
"s": 1613,
"text": "They are provided below in a sequential manner with visual aids as follows:"
},
{
"code": null,
"e": 1799,
"s": 1689,
"text": "Go to Spring InitializrFill in the details as per the requirements. For this application shown below asities:"
},
{
"code": null,
"e": 1823,
"s": 1799,
"text": "Go to Spring Initializr"
},
{
"code": null,
"e": 1910,
"s": 1823,
"text": "Fill in the details as per the requirements. For this application shown below asities:"
},
{
"code": null,
"e": 2011,
"s": 1910,
"text": "Project: Maven\nLanguage: Java \nSpring Boot: 2.2.8 \nPackaging: JAR \nJava: 8 \nDependencies: Spring Web"
},
{
"code": null,
"e": 2080,
"s": 2011,
"text": "Step 1: Click on Generate which will download the starter project. "
},
{
"code": null,
"e": 2297,
"s": 2080,
"text": "Step 2: Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync. "
},
{
"code": null,
"e": 2435,
"s": 2297,
"text": "Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project."
},
{
"code": null,
"e": 2613,
"s": 2435,
"text": "Step 3: Go to src->main->java->com.gfg.Spring.boot.app, create a java class with name as Controller and add the annotation @RestController. Now create a GET API as shown below:”"
},
{
"code": null,
"e": 2854,
"s": 2613,
"text": "@RestController\n\npublic class Controller {\n \n @GetMapping(\"/get\") public String home() {\n return \"This is the get request\";\n }\n\n @GetMapping(\"/get/check\") public String home1() {\n \n return \"This is the get check request\";\n }\n}"
},
{
"code": null,
"e": 2980,
"s": 2854,
"text": "Step 4: This application is now ready to run. Run the SpringBootAppApplication class and wait for the Tomcat server to start."
},
{
"code": null,
"e": 3087,
"s": 2980,
"text": "Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file."
},
{
"code": null,
"e": 3219,
"s": 3087,
"text": "Step 5: Now go to the browser and enter the URL localhost:8080. Observe the output and now do the same for localhost:8080/get/check"
},
{
"code": null,
"e": 3345,
"s": 3219,
"text": "Geeks, we are done with get() method request in Spring as perceived from the above pop-up. Hence these were the steps at all."
},
{
"code": null,
"e": 3357,
"s": 3345,
"text": "zack_aayush"
},
{
"code": null,
"e": 3369,
"s": 3357,
"text": "Java-Spring"
},
{
"code": null,
"e": 3374,
"s": 3369,
"text": "Java"
},
{
"code": null,
"e": 3379,
"s": 3374,
"text": "Java"
},
{
"code": null,
"e": 3477,
"s": 3379,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3492,
"s": 3477,
"text": "Stream In Java"
},
{
"code": null,
"e": 3513,
"s": 3492,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3534,
"s": 3513,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3553,
"s": 3534,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3570,
"s": 3553,
"text": "Generics in Java"
},
{
"code": null,
"e": 3600,
"s": 3570,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3616,
"s": 3600,
"text": "Strings in Java"
},
{
"code": null,
"e": 3642,
"s": 3616,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3662,
"s": 3642,
"text": "Abstraction in Java"
}
] |
now() function in Python
|
15 Oct, 2020
Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module.
Syntax : datetime.now(tz)
Parameters :tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)
Returns : Returns the current date and time in time format.
Code #1 :
# Python3 code to demonstrate# Getting current time using # now(). # importing datetime module for now()import datetime # using now() to get current timecurrent_time = datetime.datetime.now() # Printing value of now.print ("Time now at greenwich meridian is : " , end = "")print (current_time)
Output :
Time now at greenwich meridian is : 2018-03-29 10:26:23.473031
now() has different attributes, same as attributes of time such as year, month, date, hour, minute, second.
Code #2 : Demonstrate attributes of now().
# Python3 code to demonstrate# attributes of now() # importing datetime module for now()import datetime # using now() to get current timecurrent_time = datetime.datetime.now() # Printing attributes of now().print ("The attributes of now() are : ") print ("Year : ", end = "")print (current_time.year) print ("Month : ", end = "")print (current_time.month) print ("Day : ", end = "")print (current_time.day) print ("Hour : ", end = "")print (current_time.hour) print ("Minute : ", end = "")print (current_time.minute) print ("Second : ", end = "")print (current_time.second) print ("Microsecond : ", end = "")print (current_time.microsecond)
The attributes of now() are :
Year : 2018
Month : 3
Day : 26
Hour : 20
Minute : 9
Second : 4
Microsecond : 499806
Sometimes, the need is just to get the current time of a particular timezone. now() takes timezone as input to give timezone oriented output time. But these time zones are defined in pytz library.
Code #3 : Use of now() to handle specific timezone.
# Python3 code to demonstrate# attributes of now() for timezone # for now()import datetime # for timezone()import pytz # using now() to get current timecurrent_time = datetime.datetime.now(pytz.timezone('Asia / Calcutta')) # printing current time in indiaprint ("The current time in india is : ")print (current_time)
Output:
The current time in india is :
2018-03-29 03:09:33.878000+05:30
Note : Above code won’t work on online IDE due to absence of pytz module. Application :While developing any real world application, we might need to show real time of any timezone. now() function can do the work here very efficiently and easily.
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 238,
"s": 52,
"text": "Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module."
},
{
"code": null,
"e": 264,
"s": 238,
"text": "Syntax : datetime.now(tz)"
},
{
"code": null,
"e": 388,
"s": 264,
"text": "Parameters :tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)"
},
{
"code": null,
"e": 448,
"s": 388,
"text": "Returns : Returns the current date and time in time format."
},
{
"code": null,
"e": 459,
"s": 448,
"text": " Code #1 :"
},
{
"code": "# Python3 code to demonstrate# Getting current time using # now(). # importing datetime module for now()import datetime # using now() to get current timecurrent_time = datetime.datetime.now() # Printing value of now.print (\"Time now at greenwich meridian is : \" , end = \"\")print (current_time)",
"e": 791,
"s": 459,
"text": null
},
{
"code": null,
"e": 800,
"s": 791,
"text": "Output :"
},
{
"code": null,
"e": 864,
"s": 800,
"text": "Time now at greenwich meridian is : 2018-03-29 10:26:23.473031\n"
},
{
"code": null,
"e": 974,
"s": 866,
"text": "now() has different attributes, same as attributes of time such as year, month, date, hour, minute, second."
},
{
"code": null,
"e": 1017,
"s": 974,
"text": "Code #2 : Demonstrate attributes of now()."
},
{
"code": "# Python3 code to demonstrate# attributes of now() # importing datetime module for now()import datetime # using now() to get current timecurrent_time = datetime.datetime.now() # Printing attributes of now().print (\"The attributes of now() are : \") print (\"Year : \", end = \"\")print (current_time.year) print (\"Month : \", end = \"\")print (current_time.month) print (\"Day : \", end = \"\")print (current_time.day) print (\"Hour : \", end = \"\")print (current_time.hour) print (\"Minute : \", end = \"\")print (current_time.minute) print (\"Second : \", end = \"\")print (current_time.second) print (\"Microsecond : \", end = \"\")print (current_time.microsecond)",
"e": 1668,
"s": 1017,
"text": null
},
{
"code": null,
"e": 1784,
"s": 1668,
"text": "The attributes of now() are : \nYear : 2018\nMonth : 3\nDay : 26\nHour : 20\nMinute : 9\nSecond : 4\nMicrosecond : 499806\n"
},
{
"code": null,
"e": 1983,
"s": 1786,
"text": "Sometimes, the need is just to get the current time of a particular timezone. now() takes timezone as input to give timezone oriented output time. But these time zones are defined in pytz library."
},
{
"code": null,
"e": 2035,
"s": 1983,
"text": "Code #3 : Use of now() to handle specific timezone."
},
{
"code": "# Python3 code to demonstrate# attributes of now() for timezone # for now()import datetime # for timezone()import pytz # using now() to get current timecurrent_time = datetime.datetime.now(pytz.timezone('Asia / Calcutta')) # printing current time in indiaprint (\"The current time in india is : \")print (current_time) ",
"e": 2357,
"s": 2035,
"text": null
},
{
"code": null,
"e": 2365,
"s": 2357,
"text": "Output:"
},
{
"code": null,
"e": 2431,
"s": 2365,
"text": "The current time in india is : \n2018-03-29 03:09:33.878000+05:30\n"
},
{
"code": null,
"e": 2677,
"s": 2431,
"text": "Note : Above code won’t work on online IDE due to absence of pytz module. Application :While developing any real world application, we might need to show real time of any timezone. now() function can do the work here very efficiently and easily."
},
{
"code": null,
"e": 2703,
"s": 2677,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2710,
"s": 2703,
"text": "Python"
}
] |
turtle.bgpic() function in Python
|
28 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.
This function is used to set a background image or return name of the current background image. It requires only one argument “picname”. This argument can be used in different ways as follows :
If picname is a filename, set the corresponding image as background.
If picname is “nopic”, delete background image, if present.
If picname is None, return the filename of the current backgroundimage.
Syntax :
turtle.bgpic(picname=None)
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # check background imageprint(turtle.bgpic())
Output :
nopic
Example 2 :
Python3
# import packageimport turtle # set background imageturtle.bgpic("gfg.png")
Output :
Example 3 :
Python3
# import packageimport turtle # set background imageturtle.bgpic("gfg.png") # loop for motionfor i in range(20): turtle.forward(5+5*i) turtle.right(90) # delete background imageturtle.bgpic("nopic")
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 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": 439,
"s": 245,
"text": "This function is used to set a background image or return name of the current background image. It requires only one argument “picname”. This argument can be used in different ways as follows :"
},
{
"code": null,
"e": 508,
"s": 439,
"text": "If picname is a filename, set the corresponding image as background."
},
{
"code": null,
"e": 568,
"s": 508,
"text": "If picname is “nopic”, delete background image, if present."
},
{
"code": null,
"e": 640,
"s": 568,
"text": "If picname is None, return the filename of the current backgroundimage."
},
{
"code": null,
"e": 649,
"s": 640,
"text": "Syntax :"
},
{
"code": null,
"e": 677,
"s": 649,
"text": "turtle.bgpic(picname=None)\n"
},
{
"code": null,
"e": 746,
"s": 677,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 758,
"s": 746,
"text": "Example 1 :"
},
{
"code": null,
"e": 766,
"s": 758,
"text": "Python3"
},
{
"code": "# import packageimport turtle # check background imageprint(turtle.bgpic())",
"e": 843,
"s": 766,
"text": null
},
{
"code": null,
"e": 852,
"s": 843,
"text": "Output :"
},
{
"code": null,
"e": 859,
"s": 852,
"text": "nopic\n"
},
{
"code": null,
"e": 871,
"s": 859,
"text": "Example 2 :"
},
{
"code": null,
"e": 879,
"s": 871,
"text": "Python3"
},
{
"code": "# import packageimport turtle # set background imageturtle.bgpic(\"gfg.png\")",
"e": 956,
"s": 879,
"text": null
},
{
"code": null,
"e": 965,
"s": 956,
"text": "Output :"
},
{
"code": null,
"e": 977,
"s": 965,
"text": "Example 3 :"
},
{
"code": null,
"e": 985,
"s": 977,
"text": "Python3"
},
{
"code": "# import packageimport turtle # set background imageturtle.bgpic(\"gfg.png\") # loop for motionfor i in range(20): turtle.forward(5+5*i) turtle.right(90) # delete background imageturtle.bgpic(\"nopic\")",
"e": 1193,
"s": 985,
"text": null
},
{
"code": null,
"e": 1202,
"s": 1193,
"text": "Output :"
},
{
"code": null,
"e": 1216,
"s": 1202,
"text": "Python-turtle"
},
{
"code": null,
"e": 1223,
"s": 1216,
"text": "Python"
}
] |
Python – Create dictionary from the list
|
When it is required to create dictionary from a list, the ‘fromkeys’ method in the ‘dict’ method is used.
Below is a demonstration of the same −
my_list = ['Hi', 'Will', 'how', 'Python', 'cool']
print("The list is ")
print(my_list)
my_dict = dict.fromkeys(my_list, "my_value")
print(my_dict)
The list is
['Hi', 'Will', 'how', 'Python', 'cool']
{'Hi': 'my_value', 'Will': 'my_value', 'how': 'my_value', 'Python': 'my_value', 'cool': 'my_value'}
A list of strings is defined and is displayed on the console.
A list of strings is defined and is displayed on the console.
The ‘fromkeys’ method present in ‘dict’ is used to convert the elements of the list to dictionary keys.
The ‘fromkeys’ method present in ‘dict’ is used to convert the elements of the list to dictionary keys.
The value for every key is specified here itself.
The value for every key is specified here itself.
This is assigned to a variable.
This is assigned to a variable.
It is displayed as output on the console.
It is displayed as output on the console.
|
[
{
"code": null,
"e": 1293,
"s": 1187,
"text": "When it is required to create dictionary from a list, the ‘fromkeys’ method in the ‘dict’ method is used."
},
{
"code": null,
"e": 1332,
"s": 1293,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1480,
"s": 1332,
"text": "my_list = ['Hi', 'Will', 'how', 'Python', 'cool']\nprint(\"The list is \")\nprint(my_list)\n\nmy_dict = dict.fromkeys(my_list, \"my_value\")\nprint(my_dict)"
},
{
"code": null,
"e": 1632,
"s": 1480,
"text": "The list is\n['Hi', 'Will', 'how', 'Python', 'cool']\n{'Hi': 'my_value', 'Will': 'my_value', 'how': 'my_value', 'Python': 'my_value', 'cool': 'my_value'}"
},
{
"code": null,
"e": 1694,
"s": 1632,
"text": "A list of strings is defined and is displayed on the console."
},
{
"code": null,
"e": 1756,
"s": 1694,
"text": "A list of strings is defined and is displayed on the console."
},
{
"code": null,
"e": 1860,
"s": 1756,
"text": "The ‘fromkeys’ method present in ‘dict’ is used to convert the elements of the list to dictionary keys."
},
{
"code": null,
"e": 1964,
"s": 1860,
"text": "The ‘fromkeys’ method present in ‘dict’ is used to convert the elements of the list to dictionary keys."
},
{
"code": null,
"e": 2014,
"s": 1964,
"text": "The value for every key is specified here itself."
},
{
"code": null,
"e": 2064,
"s": 2014,
"text": "The value for every key is specified here itself."
},
{
"code": null,
"e": 2096,
"s": 2064,
"text": "This is assigned to a variable."
},
{
"code": null,
"e": 2128,
"s": 2096,
"text": "This is assigned to a variable."
},
{
"code": null,
"e": 2170,
"s": 2128,
"text": "It is displayed as output on the console."
},
{
"code": null,
"e": 2212,
"s": 2170,
"text": "It is displayed as output on the console."
}
] |
How to remove connected remote desktop user sessions using PowerShell?
|
We can remove connected RDP sessions using PowerShell and for that, we can use the cmd command “reset session” in PowerShell. Let’s see the supported parameters for it.
PS C:\> reset session /?
Reset the session subsytem hardware and software to known initial values.
RESET SESSION {sessionname | sessionid} [/SERVER:servername] [/V]
sessionname Identifies the session with name sessionname.
sessionid Identifies the session with ID sessionid.
/SERVER:servername The server containing the session (default is current).
/V Display additional information.
We can provide here session ID or Name and also the remote server name.
Suppose we have below active sessions on a remote computer called Test1-Win2k12,
We can disconnect the remote sessions using Session Name or the Session ID. First, we will disconnect the remote sessions with session ID 1.
reset session 1 /server:test1-win2k12
When we query the session again,
query session /server:Test1-win2k12
Now we will disconnect the session called rdp-tcp#0 using the SessionName,
reset session rdp-tcp#0 /server:test1-win2k12
Let’s query the session again and it should get disconnected from the remote server.
|
[
{
"code": null,
"e": 1357,
"s": 1187,
"text": "We can remove connected RDP sessions using PowerShell and for that, we can use the cmd command “reset session” in PowerShell. Let’s see the supported parameters for it."
},
{
"code": null,
"e": 1780,
"s": 1357,
"text": "PS C:\\> reset session /?\nReset the session subsytem hardware and software to known initial values.\n\nRESET SESSION {sessionname | sessionid} [/SERVER:servername] [/V]\n\nsessionname Identifies the session with name sessionname.\nsessionid Identifies the session with ID sessionid.\n/SERVER:servername The server containing the session (default is current).\n/V Display additional information."
},
{
"code": null,
"e": 1852,
"s": 1780,
"text": "We can provide here session ID or Name and also the remote server name."
},
{
"code": null,
"e": 1933,
"s": 1852,
"text": "Suppose we have below active sessions on a remote computer called Test1-Win2k12,"
},
{
"code": null,
"e": 2074,
"s": 1933,
"text": "We can disconnect the remote sessions using Session Name or the Session ID. First, we will disconnect the remote sessions with session ID 1."
},
{
"code": null,
"e": 2112,
"s": 2074,
"text": "reset session 1 /server:test1-win2k12"
},
{
"code": null,
"e": 2145,
"s": 2112,
"text": "When we query the session again,"
},
{
"code": null,
"e": 2181,
"s": 2145,
"text": "query session /server:Test1-win2k12"
},
{
"code": null,
"e": 2256,
"s": 2181,
"text": "Now we will disconnect the session called rdp-tcp#0 using the SessionName,"
},
{
"code": null,
"e": 2302,
"s": 2256,
"text": "reset session rdp-tcp#0 /server:test1-win2k12"
},
{
"code": null,
"e": 2387,
"s": 2302,
"text": "Let’s query the session again and it should get disconnected from the remote server."
}
] |
Previous perfect square and cube number smaller than number N
|
03 Sep, 2021
Given an integer N, the task is to find the previous perfect square or perfect cube smaller than the number N.Examples:
Input: N = 6 Output: Perfect Square = 4 Perfect Cube = 1Input: N = 30 Output: Perfect Square = 25 Perfect Cube = 27
Approach: Previous perfect square number less than N can be computed as follows:
Find the square root of given number N.
Calculate its floor value using floor function of the respective language.
Then subtract 1 from it if N is already a perfect square.
Print square of that number.
Previous perfect cube number less than N can be computed as follows:
Find the cube root of given N.
Calculate its floor value using floor function of the respective language.
Then subtract 1 from it if N is already a perfect cube.
Print cube of that number.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// previous perfect square and cube// smaller than the given number #include <cmath>#include <iostream> using namespace std; // Function to find the previous// perfect square of the number Nint previousPerfectSquare(int N){ int prevN = floor(sqrt(N)); // If N is already a perfect square // decrease prevN by 1. if (prevN * prevN == N) prevN -= 1; return prevN * prevN;} // Function to find the// previous perfect cubeint previousPerfectCube(int N){ int prevN = floor(cbrt(N)); // If N is already a perfect cube // decrease prevN by 1. if (prevN * prevN * prevN == N) prevN -= 1; return prevN * prevN * prevN;} // Driver Codeint main(){ int n = 30; cout << previousPerfectSquare(n) << "\n"; cout << previousPerfectCube(n) << "\n"; return 0;}
// Java implementation to find the// previous perfect square and cube// smaller than the given numberimport java.util.*; class GFG{ // Function to find the previous// perfect square of the number Nstatic int previousPerfectSquare(int N){ int prevN = (int)Math.floor(Math.sqrt(N)); // If N is already a perfect square // decrease prevN by 1. if (prevN * prevN == N) prevN -= 1; return prevN * prevN;} // Function to find the// previous perfect cubestatic int previousPerfectCube(int N){ int prevN = (int)Math.floor(Math.cbrt(N)); // If N is already a perfect cube // decrease prevN by 1. if (prevN * prevN * prevN == N) prevN -= 1; return prevN * prevN * prevN;} // Driver Codepublic static void main(String[] args){ int n = 30; System.out.println(previousPerfectSquare(n)); System.out.println(previousPerfectCube(n));}} // This code is contributed by Rohit_ranjan
# Python3 implementation to find the# previous perfect square and cube# smaller than the given numberimport mathimport numpy as np # Function to find the previous# perfect square of the number Ndef previousPerfectSquare(N): prevN = math.floor(math.sqrt(N)); # If N is already a perfect square # decrease prevN by 1. if (prevN * prevN == N): prevN -= 1; return prevN * prevN; # Function to find the# previous perfect cubedef previousPerfectCube(N): prevN = math.floor(np.cbrt(N)); # If N is already a perfect cube # decrease prevN by 1. if (prevN * prevN * prevN == N): prevN -= 1; return prevN * prevN * prevN; # Driver Coden = 30; print(previousPerfectSquare(n));print(previousPerfectCube(n)); # This code is contributed by Code_Mech
// C# implementation to find the// previous perfect square and cube// smaller than the given numberusing System; class GFG{ // Function to find the previous// perfect square of the number Nstatic int previousPerfectSquare(int N){ int prevN = (int)Math.Floor(Math.Sqrt(N)); // If N is already a perfect square // decrease prevN by 1. if (prevN * prevN == N) prevN -= 1; return prevN * prevN;} // Function to find the// previous perfect cubestatic int previousPerfectCube(int N){ int prevN = (int)Math.Floor(Math.Cbrt(N)); // If N is already a perfect cube // decrease prevN by 1. if (prevN * prevN * prevN == N) prevN -= 1; return prevN * prevN * prevN;} // Driver Codepublic static void Main(String[] args){ int n = 30; Console.WriteLine(previousPerfectSquare(n)); Console.WriteLine(previousPerfectCube(n));}} // This code is contributed by sapnasingh4991
<script>// JavaScript implementation to find the// previous perfect square and cube// smaller than the given number // Function to find the previous// perfect square of the number Nfunction previousPerfectSquare(N){ let prevN = Math.floor(Math.sqrt(N)); // If N is already a perfect square // decrease prevN by 1. if (prevN * prevN == N) prevN -= 1; return prevN * prevN;} // Function to find the// previous perfect cubefunction previousPerfectCube(N){ let prevN = Math.floor(Math.cbrt(N)); // If N is already a perfect cube // decrease prevN by 1. if (prevN * prevN * prevN == N) prevN -= 1; return prevN * prevN * prevN;} // Driver Code let n = 30; document.write(previousPerfectSquare(n) + "<br>"); document.write(previousPerfectCube(n) + "<br>"); // This code is contributed by Manoj.</script>
25
27
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)
Rohit_ranjan
sapnasingh4991
Code_Mech
subhammahato348
mank1083
surindertarika1234
maths-perfect-cube
maths-perfect-square
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Sep, 2021"
},
{
"code": null,
"e": 149,
"s": 28,
"text": "Given an integer N, the task is to find the previous perfect square or perfect cube smaller than the number N.Examples: "
},
{
"code": null,
"e": 266,
"s": 149,
"text": "Input: N = 6 Output: Perfect Square = 4 Perfect Cube = 1Input: N = 30 Output: Perfect Square = 25 Perfect Cube = 27 "
},
{
"code": null,
"e": 349,
"s": 266,
"text": "Approach: Previous perfect square number less than N can be computed as follows: "
},
{
"code": null,
"e": 389,
"s": 349,
"text": "Find the square root of given number N."
},
{
"code": null,
"e": 464,
"s": 389,
"text": "Calculate its floor value using floor function of the respective language."
},
{
"code": null,
"e": 522,
"s": 464,
"text": "Then subtract 1 from it if N is already a perfect square."
},
{
"code": null,
"e": 551,
"s": 522,
"text": "Print square of that number."
},
{
"code": null,
"e": 622,
"s": 551,
"text": "Previous perfect cube number less than N can be computed as follows: "
},
{
"code": null,
"e": 653,
"s": 622,
"text": "Find the cube root of given N."
},
{
"code": null,
"e": 728,
"s": 653,
"text": "Calculate its floor value using floor function of the respective language."
},
{
"code": null,
"e": 784,
"s": 728,
"text": "Then subtract 1 from it if N is already a perfect cube."
},
{
"code": null,
"e": 811,
"s": 784,
"text": "Print cube of that number."
},
{
"code": null,
"e": 860,
"s": 811,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 864,
"s": 860,
"text": "C++"
},
{
"code": null,
"e": 869,
"s": 864,
"text": "Java"
},
{
"code": null,
"e": 877,
"s": 869,
"text": "Python3"
},
{
"code": null,
"e": 880,
"s": 877,
"text": "C#"
},
{
"code": null,
"e": 891,
"s": 880,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// previous perfect square and cube// smaller than the given number #include <cmath>#include <iostream> using namespace std; // Function to find the previous// perfect square of the number Nint previousPerfectSquare(int N){ int prevN = floor(sqrt(N)); // If N is already a perfect square // decrease prevN by 1. if (prevN * prevN == N) prevN -= 1; return prevN * prevN;} // Function to find the// previous perfect cubeint previousPerfectCube(int N){ int prevN = floor(cbrt(N)); // If N is already a perfect cube // decrease prevN by 1. if (prevN * prevN * prevN == N) prevN -= 1; return prevN * prevN * prevN;} // Driver Codeint main(){ int n = 30; cout << previousPerfectSquare(n) << \"\\n\"; cout << previousPerfectCube(n) << \"\\n\"; return 0;}",
"e": 1742,
"s": 891,
"text": null
},
{
"code": "// Java implementation to find the// previous perfect square and cube// smaller than the given numberimport java.util.*; class GFG{ // Function to find the previous// perfect square of the number Nstatic int previousPerfectSquare(int N){ int prevN = (int)Math.floor(Math.sqrt(N)); // If N is already a perfect square // decrease prevN by 1. if (prevN * prevN == N) prevN -= 1; return prevN * prevN;} // Function to find the// previous perfect cubestatic int previousPerfectCube(int N){ int prevN = (int)Math.floor(Math.cbrt(N)); // If N is already a perfect cube // decrease prevN by 1. if (prevN * prevN * prevN == N) prevN -= 1; return prevN * prevN * prevN;} // Driver Codepublic static void main(String[] args){ int n = 30; System.out.println(previousPerfectSquare(n)); System.out.println(previousPerfectCube(n));}} // This code is contributed by Rohit_ranjan",
"e": 2679,
"s": 1742,
"text": null
},
{
"code": "# Python3 implementation to find the# previous perfect square and cube# smaller than the given numberimport mathimport numpy as np # Function to find the previous# perfect square of the number Ndef previousPerfectSquare(N): prevN = math.floor(math.sqrt(N)); # If N is already a perfect square # decrease prevN by 1. if (prevN * prevN == N): prevN -= 1; return prevN * prevN; # Function to find the# previous perfect cubedef previousPerfectCube(N): prevN = math.floor(np.cbrt(N)); # If N is already a perfect cube # decrease prevN by 1. if (prevN * prevN * prevN == N): prevN -= 1; return prevN * prevN * prevN; # Driver Coden = 30; print(previousPerfectSquare(n));print(previousPerfectCube(n)); # This code is contributed by Code_Mech",
"e": 3480,
"s": 2679,
"text": null
},
{
"code": "// C# implementation to find the// previous perfect square and cube// smaller than the given numberusing System; class GFG{ // Function to find the previous// perfect square of the number Nstatic int previousPerfectSquare(int N){ int prevN = (int)Math.Floor(Math.Sqrt(N)); // If N is already a perfect square // decrease prevN by 1. if (prevN * prevN == N) prevN -= 1; return prevN * prevN;} // Function to find the// previous perfect cubestatic int previousPerfectCube(int N){ int prevN = (int)Math.Floor(Math.Cbrt(N)); // If N is already a perfect cube // decrease prevN by 1. if (prevN * prevN * prevN == N) prevN -= 1; return prevN * prevN * prevN;} // Driver Codepublic static void Main(String[] args){ int n = 30; Console.WriteLine(previousPerfectSquare(n)); Console.WriteLine(previousPerfectCube(n));}} // This code is contributed by sapnasingh4991",
"e": 4414,
"s": 3480,
"text": null
},
{
"code": "<script>// JavaScript implementation to find the// previous perfect square and cube// smaller than the given number // Function to find the previous// perfect square of the number Nfunction previousPerfectSquare(N){ let prevN = Math.floor(Math.sqrt(N)); // If N is already a perfect square // decrease prevN by 1. if (prevN * prevN == N) prevN -= 1; return prevN * prevN;} // Function to find the// previous perfect cubefunction previousPerfectCube(N){ let prevN = Math.floor(Math.cbrt(N)); // If N is already a perfect cube // decrease prevN by 1. if (prevN * prevN * prevN == N) prevN -= 1; return prevN * prevN * prevN;} // Driver Code let n = 30; document.write(previousPerfectSquare(n) + \"<br>\"); document.write(previousPerfectCube(n) + \"<br>\"); // This code is contributed by Manoj.</script>",
"e": 5285,
"s": 4414,
"text": null
},
{
"code": null,
"e": 5291,
"s": 5285,
"text": "25\n27"
},
{
"code": null,
"e": 5321,
"s": 5293,
"text": "Time Complexity: O(sqrt(n))"
},
{
"code": null,
"e": 5343,
"s": 5321,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5356,
"s": 5343,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 5371,
"s": 5356,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 5381,
"s": 5371,
"text": "Code_Mech"
},
{
"code": null,
"e": 5397,
"s": 5381,
"text": "subhammahato348"
},
{
"code": null,
"e": 5406,
"s": 5397,
"text": "mank1083"
},
{
"code": null,
"e": 5425,
"s": 5406,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5444,
"s": 5425,
"text": "maths-perfect-cube"
},
{
"code": null,
"e": 5465,
"s": 5444,
"text": "maths-perfect-square"
},
{
"code": null,
"e": 5478,
"s": 5465,
"text": "Mathematical"
},
{
"code": null,
"e": 5497,
"s": 5478,
"text": "School Programming"
},
{
"code": null,
"e": 5510,
"s": 5497,
"text": "Mathematical"
},
{
"code": null,
"e": 5608,
"s": 5510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5640,
"s": 5608,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 5686,
"s": 5640,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 5730,
"s": 5686,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 5779,
"s": 5730,
"text": "Find next greater number with same set of digits"
},
{
"code": null,
"e": 5821,
"s": 5779,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 5839,
"s": 5821,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5864,
"s": 5839,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5880,
"s": 5864,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5903,
"s": 5880,
"text": "Introduction To PYTHON"
}
] |
Matplotlib.axes.Axes.set_frame_on() in Python
|
19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_frame_on() function in axes module of matplotlib library is used to set whether the axes rectangle patch is drawn or not.
Syntax: Axes.set_axis_on(self)
Parameters: This method accept only one parameters.
b: This parameter contains a boolean value and it is used for drawing the axes rectangle patch.
Returns:This method does not returns anything.
Note: If True is used, it does not effect any thing.Below examples illustrate the matplotlib.axes.Axes.set_frame_on() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x fig, ax = plt.subplots()ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8)ax.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax.set_frame_on(False)ax.set_title('matplotlib.axes.Axes.set_frame_on() Example')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(16)y = np.sin(x / 3) fig, ax = plt.subplots() ax.step(x, y + 2, label ='pre (default)')ax.plot(x, y + 2, 'o--', color ='black', alpha = 0.3) ax.step(x, y + 1, where ='mid', label ='mid')ax.plot(x, y + 1, 'o--', color ='black', alpha = 0.3) ax.step(x, y, where ='post', label ='post')ax.plot(x, y, 'o--', color ='black', alpha = 0.3) ax.grid(axis ='x', color ='0.95')ax.legend(title ='Parameter where:')ax.set_frame_on(False)ax.set_title('matplotlib.axes.Axes.set_frame_on() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 463,
"s": 328,
"text": "The Axes.set_frame_on() function in axes module of matplotlib library is used to set whether the axes rectangle patch is drawn or not."
},
{
"code": null,
"e": 494,
"s": 463,
"text": "Syntax: Axes.set_axis_on(self)"
},
{
"code": null,
"e": 546,
"s": 494,
"text": "Parameters: This method accept only one parameters."
},
{
"code": null,
"e": 642,
"s": 546,
"text": "b: This parameter contains a boolean value and it is used for drawing the axes rectangle patch."
},
{
"code": null,
"e": 689,
"s": 642,
"text": "Returns:This method does not returns anything."
},
{
"code": null,
"e": 836,
"s": 689,
"text": "Note: If True is used, it does not effect any thing.Below examples illustrate the matplotlib.axes.Axes.set_frame_on() function in matplotlib.axes:"
},
{
"code": null,
"e": 847,
"s": 836,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x fig, ax = plt.subplots()ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8)ax.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax.set_frame_on(False)ax.set_title('matplotlib.axes.Axes.set_frame_on() Example')plt.show()",
"e": 1345,
"s": 847,
"text": null
},
{
"code": null,
"e": 1353,
"s": 1345,
"text": "Output:"
},
{
"code": null,
"e": 1364,
"s": 1353,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(16)y = np.sin(x / 3) fig, ax = plt.subplots() ax.step(x, y + 2, label ='pre (default)')ax.plot(x, y + 2, 'o--', color ='black', alpha = 0.3) ax.step(x, y + 1, where ='mid', label ='mid')ax.plot(x, y + 1, 'o--', color ='black', alpha = 0.3) ax.step(x, y, where ='post', label ='post')ax.plot(x, y, 'o--', color ='black', alpha = 0.3) ax.grid(axis ='x', color ='0.95')ax.legend(title ='Parameter where:')ax.set_frame_on(False)ax.set_title('matplotlib.axes.Axes.set_frame_on() Example')plt.show()",
"e": 1973,
"s": 1364,
"text": null
},
{
"code": null,
"e": 1981,
"s": 1973,
"text": "Output:"
},
{
"code": null,
"e": 1999,
"s": 1981,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2006,
"s": 1999,
"text": "Python"
},
{
"code": null,
"e": 2104,
"s": 2006,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2136,
"s": 2104,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2163,
"s": 2136,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2184,
"s": 2163,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2207,
"s": 2184,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2263,
"s": 2207,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2294,
"s": 2263,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2336,
"s": 2294,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2378,
"s": 2336,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2417,
"s": 2378,
"text": "Python | Get unique values from a list"
}
] |
Remove Leading Zeroes from a String in Java using regular expressions
|
The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String.
Following is the regular expression to match the leading zeros of a string −
The ^0+(?!$)";
To remove the leading zeros from a string pass this as first parameter and “” as second parameter.
The following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the Regular expressions.
Live Demo
import java.util.Scanner;
public class LeadingZeroesRE {
public static String removeLeadingZeroes(String str) {
String strPattern = "^0+(?!$)";
str = str.replaceAll(strPattern, "");
return str;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = LeadingZeroesRE.removeLeadingZeroes(num);
System.out.println(result);
}
}
Enter an integer:
000012336000
12336000
|
[
{
"code": null,
"e": 1361,
"s": 1187,
"text": "The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String."
},
{
"code": null,
"e": 1438,
"s": 1361,
"text": "Following is the regular expression to match the leading zeros of a string −"
},
{
"code": null,
"e": 1453,
"s": 1438,
"text": "The ^0+(?!$)\";"
},
{
"code": null,
"e": 1552,
"s": 1453,
"text": "To remove the leading zeros from a string pass this as first parameter and “” as second parameter."
},
{
"code": null,
"e": 1700,
"s": 1552,
"text": "The following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the Regular expressions."
},
{
"code": null,
"e": 1711,
"s": 1700,
"text": " Live Demo"
},
{
"code": null,
"e": 2200,
"s": 1711,
"text": "import java.util.Scanner;\npublic class LeadingZeroesRE {\n public static String removeLeadingZeroes(String str) {\n String strPattern = \"^0+(?!$)\";\n str = str.replaceAll(strPattern, \"\");\n return str;\n }\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter an integer: \");\n String num = sc.next();\n String result = LeadingZeroesRE.removeLeadingZeroes(num);\n System.out.println(result);\n }\n}"
},
{
"code": null,
"e": 2240,
"s": 2200,
"text": "Enter an integer:\n000012336000\n12336000"
}
] |
Keras.Conv2D Class
|
18 May, 2020
Keras Conv2D is a 2D Convolution Layer, this layer creates a convolution kernel that is wind with layers input which helps produce a tensor of outputs.
Kernel: In image processing kernel is a convolution matrix or masks which can be used for blurring, sharpening, embossing, edge detection, and more by doing a convolution between a kernel and an image.
The Keras Conv2D class constructor has the following arguments:
keras.layers.Conv2D(filters, kernel_size, strides=(1, 1),
padding='valid', data_format=None, dilation_rate=(1, 1),
activation=None, use_bias=True, kernel_initializer='glorot_uniform',
bias_initializer='zeros', kernel_regularizer=None,
bias_regularizer=None, activity_regularizer=None,
kernel_constraint=None, bias_constraint=None)
Now let us examine each of these parameters individually:filters
Mandatory Conv2D parameter is the numbers of filters that convolutional layers will learn from.
It is an integer value and also determines the number of output filters in the convolution.
model.add(Conv2D(32, (3, 3), padding="same", activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
Here we are learning a total of 32 filters and then we use Max Pooling to reduce the spatial dimensions of the output volume.
As far as choosing the appropriate value for no. of filters, it is always recommended to use powers of 2 as the values.
kernel_size
This parameter determines the dimensions of the kernel. Common dimensions include 1×1, 3×3, 5×5, and 7×7 which can be passed as (1, 1), (3, 3), (5, 5), or (7, 7) tuples.
It is an integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window.
This parameter must be an odd integer.
model.add(Conv2D(32, (7, 7), activation="relu"))
strides
This parameter is an integer or tuple/list of 2 integers, specifying the “step” of the convolution along with the height and width of the input volume.
Its default value is always set to (1, 1) which means that the given Conv2D filter is applied to the current location of the input volume and the given filter takes a 1-pixel step to the right and again the filter is applied to the input volume and it is performed until we reach the far right border of the volume in which we are moving our filter.
model.add(Conv2D(128, (3, 3), strides=(1, 1), activation="relu"))
model.add(Conv2D(128, (3, 3), strides=(2, 2), activation="relu"))
padding
The padding parameter of the Keras Conv2D class can take one of two values: ‘valid’ or ‘same’.
Setting the value to “valid” parameter means that the input volume is not zero-padded and the spatial dimensions are allowed to reduce via the natural application of convolution.
model.add(Conv2D(32, (3, 3), padding="valid"))
You can instead preserve spatial dimensions of the volume such that the output volume size matches the input volume size, by setting the value to the “same”.
model.add(Conv2D(32, (3, 3), padding="same"))
data_format
This parameter of the Conv2D class can be either set to “channels_last” or “channels_first” value.
The TensorFlow backend to Keras uses channels last ordering whereas the Theano backend uses channels first ordering.
Usually we are not going to touch this value as Keras as most of the times we will be using TensorFlow backend to Keras.
It defaults to the image_data_format value found in your Keras config file at ~/.keras/Keras.json.
dilation_rate
The dilation_rate parameter of the Conv2D class is a 2-tuple of integers, which controls the dilation rate for dilated convolution.
The Dilated Convolution is the basic convolution applied to the input volume with defined gaps.
You may use this parameter when working with higher resolution images and fine-grained details are important to you or when you are constructing a network with fewer parameters.
activation
The activation parameter to the Conv2D class is simply a convenience parameter which allows you to supply a string, which specifies the name of the activation function you want to apply after performing the convolution.
model.add(Conv2D(32, (3, 3), activation="relu"))
OR
model.add(Conv2D(32, (3, 3)))
model.add(Activation("relu"))
If you don’t specify anything, no activation is applied and won’t have an impact on the performance of your Convolutional Neural Network.
use_bias
This parameter of the Conv2D class is used to determine whether a bias vector will be added to the convolutional layer.
By default, its value is set as True.
kernel_initializer
This parameter controls the initialization method which is used to initialize all the values in the Conv2D class before actually training the model.
It is the initializer for the kernel weights matrix.
bias_initializer
Whereas the bias_initializer controls how the bias vector is actually initialized before the training starts.
It is the initializer for the bias vector.
kernel_regularizer, bias_regularizer and activity_regularizer
kernel_regularizer is the Regularizer function which is applied to the kernel weights matrix.
bias_regularizer is the Regularizer function which is applied to the bias vector.
activity_regularizer is the Regularizer function which is applied to the output of the layer(i.e activation).
Regularizations are techniques used to reduce the error by fitting a function appropriately on the given training set and avoid overfitting.
It controls the type and amount of regularization method applied to the Conv2D layer.
Using regularization is a must when working with large datasets and deep neural networks.
Using regularization helps us to reduce the effects of overfitting and also to increase the ability of our model to generalize.
There are two types of regularization: L1 and L2 regularization, both are used to reduce overfitting of our model.
from keras.regularizers import l2
...
model.add(Conv2D(128, (3, 3), activation="relu"),
kernel_regularizer=l2(0.0002))
The value of regularization which you apply is the hyperparameter you will need to tune for your own dataset and its value usually ranges from 0.0001 to 0.001.
It is always recommended to leave the bias_regularizer alone as it has very less impact on reducing the overfitting.
It is also recommended to leave the activity_regularizer to its default value.
kernel_constraint and bias_constraint
kernel_constraint is the Constraint function which is applied to the kernel matrix.
bias_constraint is the Constraint function which is applied to the bias vector.
A constraint is a condition of an optimization problem that the solution must satisfy.There are several types of constraints—primarily equality constraints, inequality constraints, and integer constraints.
These parameters allow you to impose constraints on the Conv2D layers.
These parameters are usually left alone unless you have a specific reason to apply a constraint on the Con2D layers.
Here is a simple code example to show you the working of different parameters of Conv2D class:
# build the modelmodel = Sequential()model.add(Conv2D(32, kernel_size =(5, 5), strides =(1, 1), activation ='relu'))model.add(MaxPooling2D(pool_size =(2, 2), strides =(2, 2)))model.add(Conv2D(64, (5, 5), activation ='relu'))model.add(MaxPooling2D(pool_size =(2, 2)))model.add(Flatten())model.add(Dense(1000, activation ='relu'))model.add(Dense(num_classes, activation ='softmax')) # training the modelmodel.compile(loss = keras.losses.categorical_crossentropy, optimizer = keras.optimizers.SGD(lr = 0.01), metrics =['accuracy']) # fitting the modelmodel.fit(x_train, y_train, batch_size = batch_size, epochs = epochs, verbose = 1, validation_data =(x_test, y_test), callbacks =[history]) # evaluating and printing resultsscore = model.evaluate(x_test, y_test, verbose = 0)print('Test loss:', score[0])print('Test accuracy:', score[1])
Understanding the Code:
When adding the Conv2D layers using Sequential.model.add() method, there are numerous parameters we can use which we have read about earlier in our blog.
The first parameter tells us about the number of filters used in our convolution operation.
Then the second parameter specifies the size of the convolutional filter in pixels. Filter size may be determined by the CNN architecture you are using – for example, VGGNet exclusively uses (3, 3) filters. If not, use a 5×5 or 7×7 filter to learn larger features and then quickly reduce to 3×3.
The Third parameter specifies how the convolutional filter should step along the x-axis and the y-axis of the source image. In most cases, it’s okay to leave the strides parameter with the default (1, 1). However, you may increase it to (2, 2) to reduce the size of the output volume.
The Fourth parameter is the activation parameter which specifies the name of the activation function you want to apply after performing convolution.
Similar Code using Functional API
#build the modelinputs = Input(shape = ())conv1 = Conv2D(32, kernel_size = (5,5), strides = (1,1), activation = 'relu'))(inputs)max1 = MaxPooling2D(pool_size=(2,2), strides=(2,2)))(conv1)conv2 = Conv2D(64, (5,5), activation = 'relu'))(max1)max2 = MaxPooling2D(pool_size=(2,2)))(conv2)flat = Flatten()(max2)den1 = Dense(100, activation = 'relu'))(flat)out1 = Dense(num_classes, activation ='softmax'))(den1) model = Model(inputs = inputs, output =out1 ) # training the model model.compile(loss = keras.losses.categorical_crossentropy, optimizer = keras.optimizers.SGD(lr = 0.01), metrics =['accuracy']) # fitting the model model.fit(x_train, y_train, batch_size = batch_size, epochs = epochs, verbose = 1, validation_data =(x_test, y_test), callbacks =[history]) # evaluating and printing results score = model.evaluate(x_test, y_test, verbose = 0)print('Test loss:', score[0])print('Test accuracy:', score[1])
Most of the time you will be using filters, kernel_size, strides, padding.
How to properly use Keras Conv2D class to create our own Convolution Neural Network and determine if we need to utilize a specific parameter to the Keras Conv2D class.
ayushmankumar7
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 May, 2020"
},
{
"code": null,
"e": 206,
"s": 54,
"text": "Keras Conv2D is a 2D Convolution Layer, this layer creates a convolution kernel that is wind with layers input which helps produce a tensor of outputs."
},
{
"code": null,
"e": 408,
"s": 206,
"text": "Kernel: In image processing kernel is a convolution matrix or masks which can be used for blurring, sharpening, embossing, edge detection, and more by doing a convolution between a kernel and an image."
},
{
"code": null,
"e": 472,
"s": 408,
"text": "The Keras Conv2D class constructor has the following arguments:"
},
{
"code": null,
"e": 813,
"s": 472,
"text": "keras.layers.Conv2D(filters, kernel_size, strides=(1, 1),\n padding='valid', data_format=None, dilation_rate=(1, 1),\n activation=None, use_bias=True, kernel_initializer='glorot_uniform',\n bias_initializer='zeros', kernel_regularizer=None,\n bias_regularizer=None, activity_regularizer=None,\n kernel_constraint=None, bias_constraint=None)"
},
{
"code": null,
"e": 878,
"s": 813,
"text": "Now let us examine each of these parameters individually:filters"
},
{
"code": null,
"e": 974,
"s": 878,
"text": "Mandatory Conv2D parameter is the numbers of filters that convolutional layers will learn from."
},
{
"code": null,
"e": 1066,
"s": 974,
"text": "It is an integer value and also determines the number of output filters in the convolution."
},
{
"code": null,
"e": 1173,
"s": 1066,
"text": "model.add(Conv2D(32, (3, 3), padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))"
},
{
"code": null,
"e": 1299,
"s": 1173,
"text": "Here we are learning a total of 32 filters and then we use Max Pooling to reduce the spatial dimensions of the output volume."
},
{
"code": null,
"e": 1419,
"s": 1299,
"text": "As far as choosing the appropriate value for no. of filters, it is always recommended to use powers of 2 as the values."
},
{
"code": null,
"e": 1431,
"s": 1419,
"text": "kernel_size"
},
{
"code": null,
"e": 1601,
"s": 1431,
"text": "This parameter determines the dimensions of the kernel. Common dimensions include 1×1, 3×3, 5×5, and 7×7 which can be passed as (1, 1), (3, 3), (5, 5), or (7, 7) tuples."
},
{
"code": null,
"e": 1709,
"s": 1601,
"text": "It is an integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window."
},
{
"code": null,
"e": 1748,
"s": 1709,
"text": "This parameter must be an odd integer."
},
{
"code": null,
"e": 1797,
"s": 1748,
"text": "model.add(Conv2D(32, (7, 7), activation=\"relu\"))"
},
{
"code": null,
"e": 1805,
"s": 1797,
"text": "strides"
},
{
"code": null,
"e": 1957,
"s": 1805,
"text": "This parameter is an integer or tuple/list of 2 integers, specifying the “step” of the convolution along with the height and width of the input volume."
},
{
"code": null,
"e": 2307,
"s": 1957,
"text": "Its default value is always set to (1, 1) which means that the given Conv2D filter is applied to the current location of the input volume and the given filter takes a 1-pixel step to the right and again the filter is applied to the input volume and it is performed until we reach the far right border of the volume in which we are moving our filter."
},
{
"code": null,
"e": 2439,
"s": 2307,
"text": "model.add(Conv2D(128, (3, 3), strides=(1, 1), activation=\"relu\"))\nmodel.add(Conv2D(128, (3, 3), strides=(2, 2), activation=\"relu\"))"
},
{
"code": null,
"e": 2447,
"s": 2439,
"text": "padding"
},
{
"code": null,
"e": 2542,
"s": 2447,
"text": "The padding parameter of the Keras Conv2D class can take one of two values: ‘valid’ or ‘same’."
},
{
"code": null,
"e": 2721,
"s": 2542,
"text": "Setting the value to “valid” parameter means that the input volume is not zero-padded and the spatial dimensions are allowed to reduce via the natural application of convolution."
},
{
"code": null,
"e": 2768,
"s": 2721,
"text": "model.add(Conv2D(32, (3, 3), padding=\"valid\"))"
},
{
"code": null,
"e": 2926,
"s": 2768,
"text": "You can instead preserve spatial dimensions of the volume such that the output volume size matches the input volume size, by setting the value to the “same”."
},
{
"code": null,
"e": 2972,
"s": 2926,
"text": "model.add(Conv2D(32, (3, 3), padding=\"same\"))"
},
{
"code": null,
"e": 2984,
"s": 2972,
"text": "data_format"
},
{
"code": null,
"e": 3083,
"s": 2984,
"text": "This parameter of the Conv2D class can be either set to “channels_last” or “channels_first” value."
},
{
"code": null,
"e": 3200,
"s": 3083,
"text": "The TensorFlow backend to Keras uses channels last ordering whereas the Theano backend uses channels first ordering."
},
{
"code": null,
"e": 3321,
"s": 3200,
"text": "Usually we are not going to touch this value as Keras as most of the times we will be using TensorFlow backend to Keras."
},
{
"code": null,
"e": 3420,
"s": 3321,
"text": "It defaults to the image_data_format value found in your Keras config file at ~/.keras/Keras.json."
},
{
"code": null,
"e": 3434,
"s": 3420,
"text": "dilation_rate"
},
{
"code": null,
"e": 3566,
"s": 3434,
"text": "The dilation_rate parameter of the Conv2D class is a 2-tuple of integers, which controls the dilation rate for dilated convolution."
},
{
"code": null,
"e": 3662,
"s": 3566,
"text": "The Dilated Convolution is the basic convolution applied to the input volume with defined gaps."
},
{
"code": null,
"e": 3840,
"s": 3662,
"text": "You may use this parameter when working with higher resolution images and fine-grained details are important to you or when you are constructing a network with fewer parameters."
},
{
"code": null,
"e": 3851,
"s": 3840,
"text": "activation"
},
{
"code": null,
"e": 4071,
"s": 3851,
"text": "The activation parameter to the Conv2D class is simply a convenience parameter which allows you to supply a string, which specifies the name of the activation function you want to apply after performing the convolution."
},
{
"code": null,
"e": 4120,
"s": 4071,
"text": "model.add(Conv2D(32, (3, 3), activation=\"relu\"))"
},
{
"code": null,
"e": 4123,
"s": 4120,
"text": "OR"
},
{
"code": null,
"e": 4183,
"s": 4123,
"text": "model.add(Conv2D(32, (3, 3)))\nmodel.add(Activation(\"relu\"))"
},
{
"code": null,
"e": 4321,
"s": 4183,
"text": "If you don’t specify anything, no activation is applied and won’t have an impact on the performance of your Convolutional Neural Network."
},
{
"code": null,
"e": 4330,
"s": 4321,
"text": "use_bias"
},
{
"code": null,
"e": 4450,
"s": 4330,
"text": "This parameter of the Conv2D class is used to determine whether a bias vector will be added to the convolutional layer."
},
{
"code": null,
"e": 4488,
"s": 4450,
"text": "By default, its value is set as True."
},
{
"code": null,
"e": 4507,
"s": 4488,
"text": "kernel_initializer"
},
{
"code": null,
"e": 4656,
"s": 4507,
"text": "This parameter controls the initialization method which is used to initialize all the values in the Conv2D class before actually training the model."
},
{
"code": null,
"e": 4709,
"s": 4656,
"text": "It is the initializer for the kernel weights matrix."
},
{
"code": null,
"e": 4726,
"s": 4709,
"text": "bias_initializer"
},
{
"code": null,
"e": 4836,
"s": 4726,
"text": "Whereas the bias_initializer controls how the bias vector is actually initialized before the training starts."
},
{
"code": null,
"e": 4879,
"s": 4836,
"text": "It is the initializer for the bias vector."
},
{
"code": null,
"e": 4941,
"s": 4879,
"text": "kernel_regularizer, bias_regularizer and activity_regularizer"
},
{
"code": null,
"e": 5035,
"s": 4941,
"text": "kernel_regularizer is the Regularizer function which is applied to the kernel weights matrix."
},
{
"code": null,
"e": 5117,
"s": 5035,
"text": "bias_regularizer is the Regularizer function which is applied to the bias vector."
},
{
"code": null,
"e": 5227,
"s": 5117,
"text": "activity_regularizer is the Regularizer function which is applied to the output of the layer(i.e activation)."
},
{
"code": null,
"e": 5368,
"s": 5227,
"text": "Regularizations are techniques used to reduce the error by fitting a function appropriately on the given training set and avoid overfitting."
},
{
"code": null,
"e": 5454,
"s": 5368,
"text": "It controls the type and amount of regularization method applied to the Conv2D layer."
},
{
"code": null,
"e": 5544,
"s": 5454,
"text": "Using regularization is a must when working with large datasets and deep neural networks."
},
{
"code": null,
"e": 5672,
"s": 5544,
"text": "Using regularization helps us to reduce the effects of overfitting and also to increase the ability of our model to generalize."
},
{
"code": null,
"e": 5787,
"s": 5672,
"text": "There are two types of regularization: L1 and L2 regularization, both are used to reduce overfitting of our model."
},
{
"code": null,
"e": 5910,
"s": 5787,
"text": "from keras.regularizers import l2\n...\nmodel.add(Conv2D(128, (3, 3), activation=\"relu\"),\n kernel_regularizer=l2(0.0002))"
},
{
"code": null,
"e": 6070,
"s": 5910,
"text": "The value of regularization which you apply is the hyperparameter you will need to tune for your own dataset and its value usually ranges from 0.0001 to 0.001."
},
{
"code": null,
"e": 6187,
"s": 6070,
"text": "It is always recommended to leave the bias_regularizer alone as it has very less impact on reducing the overfitting."
},
{
"code": null,
"e": 6266,
"s": 6187,
"text": "It is also recommended to leave the activity_regularizer to its default value."
},
{
"code": null,
"e": 6304,
"s": 6266,
"text": "kernel_constraint and bias_constraint"
},
{
"code": null,
"e": 6388,
"s": 6304,
"text": "kernel_constraint is the Constraint function which is applied to the kernel matrix."
},
{
"code": null,
"e": 6468,
"s": 6388,
"text": "bias_constraint is the Constraint function which is applied to the bias vector."
},
{
"code": null,
"e": 6674,
"s": 6468,
"text": "A constraint is a condition of an optimization problem that the solution must satisfy.There are several types of constraints—primarily equality constraints, inequality constraints, and integer constraints."
},
{
"code": null,
"e": 6745,
"s": 6674,
"text": "These parameters allow you to impose constraints on the Conv2D layers."
},
{
"code": null,
"e": 6862,
"s": 6745,
"text": "These parameters are usually left alone unless you have a specific reason to apply a constraint on the Con2D layers."
},
{
"code": null,
"e": 6957,
"s": 6862,
"text": "Here is a simple code example to show you the working of different parameters of Conv2D class:"
},
{
"code": "# build the modelmodel = Sequential()model.add(Conv2D(32, kernel_size =(5, 5), strides =(1, 1), activation ='relu'))model.add(MaxPooling2D(pool_size =(2, 2), strides =(2, 2)))model.add(Conv2D(64, (5, 5), activation ='relu'))model.add(MaxPooling2D(pool_size =(2, 2)))model.add(Flatten())model.add(Dense(1000, activation ='relu'))model.add(Dense(num_classes, activation ='softmax')) # training the modelmodel.compile(loss = keras.losses.categorical_crossentropy, optimizer = keras.optimizers.SGD(lr = 0.01), metrics =['accuracy']) # fitting the modelmodel.fit(x_train, y_train, batch_size = batch_size, epochs = epochs, verbose = 1, validation_data =(x_test, y_test), callbacks =[history]) # evaluating and printing resultsscore = model.evaluate(x_test, y_test, verbose = 0)print('Test loss:', score[0])print('Test accuracy:', score[1])",
"e": 7882,
"s": 6957,
"text": null
},
{
"code": null,
"e": 7906,
"s": 7882,
"text": "Understanding the Code:"
},
{
"code": null,
"e": 8060,
"s": 7906,
"text": "When adding the Conv2D layers using Sequential.model.add() method, there are numerous parameters we can use which we have read about earlier in our blog."
},
{
"code": null,
"e": 8152,
"s": 8060,
"text": "The first parameter tells us about the number of filters used in our convolution operation."
},
{
"code": null,
"e": 8448,
"s": 8152,
"text": "Then the second parameter specifies the size of the convolutional filter in pixels. Filter size may be determined by the CNN architecture you are using – for example, VGGNet exclusively uses (3, 3) filters. If not, use a 5×5 or 7×7 filter to learn larger features and then quickly reduce to 3×3."
},
{
"code": null,
"e": 8733,
"s": 8448,
"text": "The Third parameter specifies how the convolutional filter should step along the x-axis and the y-axis of the source image. In most cases, it’s okay to leave the strides parameter with the default (1, 1). However, you may increase it to (2, 2) to reduce the size of the output volume."
},
{
"code": null,
"e": 8882,
"s": 8733,
"text": "The Fourth parameter is the activation parameter which specifies the name of the activation function you want to apply after performing convolution."
},
{
"code": null,
"e": 8916,
"s": 8882,
"text": "Similar Code using Functional API"
},
{
"code": "#build the modelinputs = Input(shape = ())conv1 = Conv2D(32, kernel_size = (5,5), strides = (1,1), activation = 'relu'))(inputs)max1 = MaxPooling2D(pool_size=(2,2), strides=(2,2)))(conv1)conv2 = Conv2D(64, (5,5), activation = 'relu'))(max1)max2 = MaxPooling2D(pool_size=(2,2)))(conv2)flat = Flatten()(max2)den1 = Dense(100, activation = 'relu'))(flat)out1 = Dense(num_classes, activation ='softmax'))(den1) model = Model(inputs = inputs, output =out1 ) # training the model model.compile(loss = keras.losses.categorical_crossentropy, optimizer = keras.optimizers.SGD(lr = 0.01), metrics =['accuracy']) # fitting the model model.fit(x_train, y_train, batch_size = batch_size, epochs = epochs, verbose = 1, validation_data =(x_test, y_test), callbacks =[history]) # evaluating and printing results score = model.evaluate(x_test, y_test, verbose = 0)print('Test loss:', score[0])print('Test accuracy:', score[1])",
"e": 9903,
"s": 8916,
"text": null
},
{
"code": null,
"e": 9978,
"s": 9903,
"text": "Most of the time you will be using filters, kernel_size, strides, padding."
},
{
"code": null,
"e": 10146,
"s": 9978,
"text": "How to properly use Keras Conv2D class to create our own Convolution Neural Network and determine if we need to utilize a specific parameter to the Keras Conv2D class."
},
{
"code": null,
"e": 10161,
"s": 10146,
"text": "ayushmankumar7"
},
{
"code": null,
"e": 10178,
"s": 10161,
"text": "Machine Learning"
},
{
"code": null,
"e": 10185,
"s": 10178,
"text": "Python"
},
{
"code": null,
"e": 10202,
"s": 10185,
"text": "Machine Learning"
}
] |
How to Add Icons at the Bottom of Tab Navigation in React Native ?
|
13 Jul, 2021
Adding Icons at the Bottom of Tab Navigation in React Native is a fairly easy task. In this article, we will implement a basic application to learn to use icons in our tab navigation. For this, we first need to set up the application and install some packages.
Implementation: Now let’s start with the implementation:
Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
Step 2: Now create a project by the following command.expo init tab-navigation-icons
Step 2: Now create a project by the following command.
expo init tab-navigation-icons
Step 3: Now go into your project folder i.e. tab-navigation-iconscd tab-navigation-icons
Step 3: Now go into your project folder i.e. tab-navigation-icons
cd tab-navigation-icons
Step 4: Install the required packages using the following command:
npm install --save react-navigation react-native-gesture-handler
npm install --save react-native-vector-icons
Project Structure: It will look like the following.
Example: Now, let’s set up the Tab Navigator and add icons, along with some basic CSS styles to make the icons look presentable. There will be 3 screens in our demo application, namely- Home Screen, User Screen, and Settings Screen. Thus, we will have 3 tabs to navigate between these 3 screens, with our Home Screen being the default Screen.
App.js
import React from "react";import { Ionicons } from "@expo/vector-icons";import { createAppContainer } from "react-navigation";import { createBottomTabNavigator } from "react-navigation-tabs"; import HomeScreen from "./screens/HomeScreen";import UserScreen from "./screens/UserScreen";import SettingScreen from "./screens/SettingScreen"; const TabNavigator = createBottomTabNavigator({ Home: { screen: HomeScreen, navigationOptions: { tabBarLabel: "Home", tabBarOptions: { activeTintColor: "#006600", }, tabBarIcon: (tabInfo) => { return ( <Ionicons name="md-home" size={24} color={tabInfo.focused ? "#006600" : "#8e8e93"} /> ); }, }, }, User: { screen: UserScreen, navigationOptions: { tabBarLabel: "User", tabBarOptions: { activeTintColor: "#006600", }, tabBarIcon: (tabInfo) => { return ( <Ionicons name="md-person-circle-outline" size={24} color={tabInfo.focused ? "#006600" : "#8e8e93"} /> ); }, }, }, Setting: { screen: SettingScreen, navigationOptions: { tabBarLabel: "Setting", tabBarOptions: { activeTintColor: "#006600", }, tabBarIcon: (tabInfo) => { return ( <Ionicons name="md-settings-outline" size={24} color={tabInfo.focused ? "#006600" : "#8e8e93"} /> ); }, }, },}); const Navigator = createAppContainer(TabNavigator); export default function App() { return ( <Navigator> <HomeScreen /> </Navigator> );}
The above code contains the logic for our Tab Navigator with icons at the Bottom of Tab Navigation. Now, we need the screens we need to navigate to.
HomeScreen.js
import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Home = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Home Screen!</Text> <Ionicons name="md-home" size={80} color="#006600" /> </View> );}; export default Home;
UserScreen
import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const User = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>User Screen!</Text> <Ionicons name="md-person-circle-outline" size={80} color="#006600" /> </View> );}; export default User;
SettingsScreen.js
import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Settings = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Settings Screen!</Text> <Ionicons name="md-settings-outline" size={80} color="#006600" /> </View> );}; export default Settings;
Start the server by using the following command.
npm run android
Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again.
Reference: https://reactnavigation.org/docs/tab-based-navigation/
Picked
React-Native
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Difference Between PUT and PATCH Request
ReactJS | Router
How to float three div side by side using CSS?
Design a Tribute Page using HTML & CSS
Roadmap to Learn JavaScript For Beginners
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 289,
"s": 28,
"text": "Adding Icons at the Bottom of Tab Navigation in React Native is a fairly easy task. In this article, we will implement a basic application to learn to use icons in our tab navigation. For this, we first need to set up the application and install some packages."
},
{
"code": null,
"e": 346,
"s": 289,
"text": "Implementation: Now let’s start with the implementation:"
},
{
"code": null,
"e": 443,
"s": 346,
"text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli"
},
{
"code": null,
"e": 517,
"s": 443,
"text": "Step 1: Open your terminal and install expo-cli by the following command."
},
{
"code": null,
"e": 541,
"s": 517,
"text": "npm install -g expo-cli"
},
{
"code": null,
"e": 626,
"s": 541,
"text": "Step 2: Now create a project by the following command.expo init tab-navigation-icons"
},
{
"code": null,
"e": 681,
"s": 626,
"text": "Step 2: Now create a project by the following command."
},
{
"code": null,
"e": 712,
"s": 681,
"text": "expo init tab-navigation-icons"
},
{
"code": null,
"e": 803,
"s": 714,
"text": "Step 3: Now go into your project folder i.e. tab-navigation-iconscd tab-navigation-icons"
},
{
"code": null,
"e": 869,
"s": 803,
"text": "Step 3: Now go into your project folder i.e. tab-navigation-icons"
},
{
"code": null,
"e": 893,
"s": 869,
"text": "cd tab-navigation-icons"
},
{
"code": null,
"e": 960,
"s": 893,
"text": "Step 4: Install the required packages using the following command:"
},
{
"code": null,
"e": 1073,
"s": 960,
"text": "npm install --save react-navigation react-native-gesture-handler \nnpm install --save react-native-vector-icons "
},
{
"code": null,
"e": 1125,
"s": 1073,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1468,
"s": 1125,
"text": "Example: Now, let’s set up the Tab Navigator and add icons, along with some basic CSS styles to make the icons look presentable. There will be 3 screens in our demo application, namely- Home Screen, User Screen, and Settings Screen. Thus, we will have 3 tabs to navigate between these 3 screens, with our Home Screen being the default Screen."
},
{
"code": null,
"e": 1475,
"s": 1468,
"text": "App.js"
},
{
"code": "import React from \"react\";import { Ionicons } from \"@expo/vector-icons\";import { createAppContainer } from \"react-navigation\";import { createBottomTabNavigator } from \"react-navigation-tabs\"; import HomeScreen from \"./screens/HomeScreen\";import UserScreen from \"./screens/UserScreen\";import SettingScreen from \"./screens/SettingScreen\"; const TabNavigator = createBottomTabNavigator({ Home: { screen: HomeScreen, navigationOptions: { tabBarLabel: \"Home\", tabBarOptions: { activeTintColor: \"#006600\", }, tabBarIcon: (tabInfo) => { return ( <Ionicons name=\"md-home\" size={24} color={tabInfo.focused ? \"#006600\" : \"#8e8e93\"} /> ); }, }, }, User: { screen: UserScreen, navigationOptions: { tabBarLabel: \"User\", tabBarOptions: { activeTintColor: \"#006600\", }, tabBarIcon: (tabInfo) => { return ( <Ionicons name=\"md-person-circle-outline\" size={24} color={tabInfo.focused ? \"#006600\" : \"#8e8e93\"} /> ); }, }, }, Setting: { screen: SettingScreen, navigationOptions: { tabBarLabel: \"Setting\", tabBarOptions: { activeTintColor: \"#006600\", }, tabBarIcon: (tabInfo) => { return ( <Ionicons name=\"md-settings-outline\" size={24} color={tabInfo.focused ? \"#006600\" : \"#8e8e93\"} /> ); }, }, },}); const Navigator = createAppContainer(TabNavigator); export default function App() { return ( <Navigator> <HomeScreen /> </Navigator> );}",
"e": 3135,
"s": 1475,
"text": null
},
{
"code": null,
"e": 3284,
"s": 3135,
"text": "The above code contains the logic for our Tab Navigator with icons at the Bottom of Tab Navigation. Now, we need the screens we need to navigate to."
},
{
"code": null,
"e": 3298,
"s": 3284,
"text": "HomeScreen.js"
},
{
"code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Home = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Home Screen!</Text> <Ionicons name=\"md-home\" size={80} color=\"#006600\" /> </View> );}; export default Home;",
"e": 3695,
"s": 3298,
"text": null
},
{
"code": null,
"e": 3706,
"s": 3695,
"text": "UserScreen"
},
{
"code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const User = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>User Screen!</Text> <Ionicons name=\"md-person-circle-outline\" size={80} color=\"#006600\" /> </View> );}; export default User;",
"e": 4120,
"s": 3706,
"text": null
},
{
"code": null,
"e": 4138,
"s": 4120,
"text": "SettingsScreen.js"
},
{
"code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Settings = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Settings Screen!</Text> <Ionicons name=\"md-settings-outline\" size={80} color=\"#006600\" /> </View> );}; export default Settings;",
"e": 4559,
"s": 4138,
"text": null
},
{
"code": null,
"e": 4608,
"s": 4559,
"text": "Start the server by using the following command."
},
{
"code": null,
"e": 4624,
"s": 4608,
"text": "npm run android"
},
{
"code": null,
"e": 4792,
"s": 4624,
"text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again."
},
{
"code": null,
"e": 4858,
"s": 4792,
"text": "Reference: https://reactnavigation.org/docs/tab-based-navigation/"
},
{
"code": null,
"e": 4865,
"s": 4858,
"text": "Picked"
},
{
"code": null,
"e": 4878,
"s": 4865,
"text": "React-Native"
},
{
"code": null,
"e": 4895,
"s": 4878,
"text": "Web Technologies"
},
{
"code": null,
"e": 4993,
"s": 4895,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5054,
"s": 4993,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5097,
"s": 5054,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 5169,
"s": 5097,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5209,
"s": 5169,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5233,
"s": 5209,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5274,
"s": 5233,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5291,
"s": 5274,
"text": "ReactJS | Router"
},
{
"code": null,
"e": 5338,
"s": 5291,
"text": "How to float three div side by side using CSS?"
},
{
"code": null,
"e": 5377,
"s": 5338,
"text": "Design a Tribute Page using HTML & CSS"
}
] |
p5.js | tint() Function
|
27 Feb, 2020
The tint() function is used to set a fill value for images. It can be used to tint an image with the specified color or make it transparent by using an alpha value. Several parameters can be used to specify the tint color.
Syntax:
tint(v1, v2, v3, alpha)
tint(value)
tint(gray, alpha)
tint(values)
tint(color)
Parameters: This function accept eight parameters as mentioned above and described below:
v1: It is a number which determines the red or hue value relative to the current color range.
v2: It is a number which determines the green or saturation value relative to the current color range.
v3: It is a number which determines the blue or brightness value relative to the current color range.
alpha: It is a number which defines the alpha value for the color of the tint.
value: It is a string which defines the color to be used for the tint.
gray: It is a number which defines the gray value of the tint.
values: It is an array of numbers which define the red, green, blue and alpha components of the tint color.
color: It is a p5.Color which defines the color of the tint.
The examples below illustrate the tint() function in p5.js:
Example 1:
function preload() { img = loadImage('sample-image.png'); currTintColor = color('gray');} function setup() { createCanvas(600, 300); textSize(22); // Create a color picker for // the tint color colPicker = createColorPicker('green'); colPicker.position(30, 180) colPicker.input(changeTint);} function draw() { clear(); text("Select the color below to tint the"+ " image with that color", 20, 20); text("Original Image", 20, 50); // Draw image without tint image(img, 20, 60); text("Tinted Image", 200, 50); // Draw image with tint tint(currTintColor); image(img, 200, 60); // Disable tint for the next // draw cycle noTint();} function changeTint() { // Update the current tint color currTintColor = colPicker.color();}
Output:
Example 2:
function preload() { img = loadImage('sample-image.png'); currTintAlpha = 128;} function setup() { createCanvas(600, 300); textSize(22); // Create a slider for // the alpha value of the tint alphaSlider = createSlider(0, 255, 128); alphaSlider.position(30, 180) alphaSlider.size(300); alphaSlider.input(changeTintAlpha);} function draw() { clear(); text("Move the slider to change the alpha"+ " value of the tint", 20, 20); text("Original Image", 20, 50); // Draw image without tint image(img, 20, 60); text("Tinted Image", 200, 50); // Draw image with tint and // current alpha value tint(0, 128, 210, currTintAlpha); image(img, 200, 60); // Disable tint for the next // draw cycle noTint();} function changeTintAlpha() { // Update the current alpha value currTintAlpha = alphaSlider.value();}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/tint
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 251,
"s": 28,
"text": "The tint() function is used to set a fill value for images. It can be used to tint an image with the specified color or make it transparent by using an alpha value. Several parameters can be used to specify the tint color."
},
{
"code": null,
"e": 259,
"s": 251,
"text": "Syntax:"
},
{
"code": null,
"e": 283,
"s": 259,
"text": "tint(v1, v2, v3, alpha)"
},
{
"code": null,
"e": 295,
"s": 283,
"text": "tint(value)"
},
{
"code": null,
"e": 313,
"s": 295,
"text": "tint(gray, alpha)"
},
{
"code": null,
"e": 326,
"s": 313,
"text": "tint(values)"
},
{
"code": null,
"e": 338,
"s": 326,
"text": "tint(color)"
},
{
"code": null,
"e": 428,
"s": 338,
"text": "Parameters: This function accept eight parameters as mentioned above and described below:"
},
{
"code": null,
"e": 522,
"s": 428,
"text": "v1: It is a number which determines the red or hue value relative to the current color range."
},
{
"code": null,
"e": 625,
"s": 522,
"text": "v2: It is a number which determines the green or saturation value relative to the current color range."
},
{
"code": null,
"e": 727,
"s": 625,
"text": "v3: It is a number which determines the blue or brightness value relative to the current color range."
},
{
"code": null,
"e": 806,
"s": 727,
"text": "alpha: It is a number which defines the alpha value for the color of the tint."
},
{
"code": null,
"e": 877,
"s": 806,
"text": "value: It is a string which defines the color to be used for the tint."
},
{
"code": null,
"e": 940,
"s": 877,
"text": "gray: It is a number which defines the gray value of the tint."
},
{
"code": null,
"e": 1048,
"s": 940,
"text": "values: It is an array of numbers which define the red, green, blue and alpha components of the tint color."
},
{
"code": null,
"e": 1109,
"s": 1048,
"text": "color: It is a p5.Color which defines the color of the tint."
},
{
"code": null,
"e": 1169,
"s": 1109,
"text": "The examples below illustrate the tint() function in p5.js:"
},
{
"code": null,
"e": 1180,
"s": 1169,
"text": "Example 1:"
},
{
"code": "function preload() { img = loadImage('sample-image.png'); currTintColor = color('gray');} function setup() { createCanvas(600, 300); textSize(22); // Create a color picker for // the tint color colPicker = createColorPicker('green'); colPicker.position(30, 180) colPicker.input(changeTint);} function draw() { clear(); text(\"Select the color below to tint the\"+ \" image with that color\", 20, 20); text(\"Original Image\", 20, 50); // Draw image without tint image(img, 20, 60); text(\"Tinted Image\", 200, 50); // Draw image with tint tint(currTintColor); image(img, 200, 60); // Disable tint for the next // draw cycle noTint();} function changeTint() { // Update the current tint color currTintColor = colPicker.color();}",
"e": 1947,
"s": 1180,
"text": null
},
{
"code": null,
"e": 1955,
"s": 1947,
"text": "Output:"
},
{
"code": null,
"e": 1966,
"s": 1955,
"text": "Example 2:"
},
{
"code": "function preload() { img = loadImage('sample-image.png'); currTintAlpha = 128;} function setup() { createCanvas(600, 300); textSize(22); // Create a slider for // the alpha value of the tint alphaSlider = createSlider(0, 255, 128); alphaSlider.position(30, 180) alphaSlider.size(300); alphaSlider.input(changeTintAlpha);} function draw() { clear(); text(\"Move the slider to change the alpha\"+ \" value of the tint\", 20, 20); text(\"Original Image\", 20, 50); // Draw image without tint image(img, 20, 60); text(\"Tinted Image\", 200, 50); // Draw image with tint and // current alpha value tint(0, 128, 210, currTintAlpha); image(img, 200, 60); // Disable tint for the next // draw cycle noTint();} function changeTintAlpha() { // Update the current alpha value currTintAlpha = alphaSlider.value();}",
"e": 2810,
"s": 1966,
"text": null
},
{
"code": null,
"e": 2818,
"s": 2810,
"text": "Output:"
},
{
"code": null,
"e": 2858,
"s": 2818,
"text": "Online editor: https://editor.p5js.org/"
},
{
"code": null,
"e": 2956,
"s": 2858,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 3004,
"s": 2956,
"text": "Reference: https://p5js.org/reference/#/p5/tint"
},
{
"code": null,
"e": 3021,
"s": 3004,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 3032,
"s": 3021,
"text": "JavaScript"
},
{
"code": null,
"e": 3049,
"s": 3032,
"text": "Web Technologies"
},
{
"code": null,
"e": 3147,
"s": 3049,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3208,
"s": 3147,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3280,
"s": 3208,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3320,
"s": 3280,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3373,
"s": 3320,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3414,
"s": 3373,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3447,
"s": 3414,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3509,
"s": 3447,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3570,
"s": 3509,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3620,
"s": 3570,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Matcher group(int) method in Java with Examples
|
26 Nov, 2018
The group(int group) method of Matcher Class is used to get the group index of the match result already done, from the specified group.
Syntax:
public String group(int group)
Parameters: This method takes a parameter group which is the group from which the group index of the matched pattern is required.
Return Value: This method returns the index of the first character matched from the specified group.
Exception: This method throws:
IllegalStateException if no match has yet been attempted, or if the previous match operation failed.
IndexOutOfBoundsException if there is no capturing group in the pattern with the given index.
Below examples illustrate the Matcher.group() method:
Example 1:
// Java code to illustrate group() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(G*s)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println("Current Matcher: " + result); while (matcher.find()) { // Get the group matched using group() method System.out.println(matcher.group(1)); } }}
Current Matcher: java.util.regex.Matcher[pattern=(G*s) region=0,13 lastmatch=]ss
Example 2:
// Java code to illustrate group() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(G*G)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println("Current Matcher: " + result); while (matcher.find()) { // Get the group matched using group() method System.out.println(matcher.group(0)); } }}
Current Matcher: java.util.regex.Matcher[pattern=(G*G) region=0,19 lastmatch=]GGGGGGGGGG
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#group-int-
Java - util package
Java-Functions
Java-Matcher
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
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 164,
"s": 28,
"text": "The group(int group) method of Matcher Class is used to get the group index of the match result already done, from the specified group."
},
{
"code": null,
"e": 172,
"s": 164,
"text": "Syntax:"
},
{
"code": null,
"e": 204,
"s": 172,
"text": "public String group(int group)\n"
},
{
"code": null,
"e": 334,
"s": 204,
"text": "Parameters: This method takes a parameter group which is the group from which the group index of the matched pattern is required."
},
{
"code": null,
"e": 435,
"s": 334,
"text": "Return Value: This method returns the index of the first character matched from the specified group."
},
{
"code": null,
"e": 466,
"s": 435,
"text": "Exception: This method throws:"
},
{
"code": null,
"e": 567,
"s": 466,
"text": "IllegalStateException if no match has yet been attempted, or if the previous match operation failed."
},
{
"code": null,
"e": 661,
"s": 567,
"text": "IndexOutOfBoundsException if there is no capturing group in the pattern with the given index."
},
{
"code": null,
"e": 715,
"s": 661,
"text": "Below examples illustrate the Matcher.group() method:"
},
{
"code": null,
"e": 726,
"s": 715,
"text": "Example 1:"
},
{
"code": "// Java code to illustrate group() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"(G*s)\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println(\"Current Matcher: \" + result); while (matcher.find()) { // Get the group matched using group() method System.out.println(matcher.group(1)); } }}",
"e": 1620,
"s": 726,
"text": null
},
{
"code": null,
"e": 1701,
"s": 1620,
"text": "Current Matcher: java.util.regex.Matcher[pattern=(G*s) region=0,13 lastmatch=]ss"
},
{
"code": null,
"e": 1712,
"s": 1701,
"text": "Example 2:"
},
{
"code": "// Java code to illustrate group() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"(G*G)\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFGFGFGFGFGFGFGFGFG\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println(\"Current Matcher: \" + result); while (matcher.find()) { // Get the group matched using group() method System.out.println(matcher.group(0)); } }}",
"e": 2612,
"s": 1712,
"text": null
},
{
"code": null,
"e": 2701,
"s": 2612,
"text": "Current Matcher: java.util.regex.Matcher[pattern=(G*G) region=0,19 lastmatch=]GGGGGGGGGG"
},
{
"code": null,
"e": 2794,
"s": 2701,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#group-int-"
},
{
"code": null,
"e": 2814,
"s": 2794,
"text": "Java - util package"
},
{
"code": null,
"e": 2829,
"s": 2814,
"text": "Java-Functions"
},
{
"code": null,
"e": 2842,
"s": 2829,
"text": "Java-Matcher"
},
{
"code": null,
"e": 2847,
"s": 2842,
"text": "Java"
},
{
"code": null,
"e": 2852,
"s": 2847,
"text": "Java"
},
{
"code": null,
"e": 2950,
"s": 2852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3001,
"s": 2950,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3032,
"s": 3001,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3051,
"s": 3032,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3081,
"s": 3051,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3099,
"s": 3081,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3119,
"s": 3099,
"text": "Collections in Java"
},
{
"code": null,
"e": 3134,
"s": 3119,
"text": "Stream In Java"
},
{
"code": null,
"e": 3166,
"s": 3134,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3186,
"s": 3166,
"text": "Stack Class in Java"
}
] |
Program to Change RGB color model to HSV color model
|
10 May, 2021
Given RGB color range, our task is to convert RGB color to HSV color.RGB Color Model : The RGB color model is an additive color model in which red, green and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive primary colors, red, green, and blue. HSV Color Model : HSV – (hue, saturation, value), also known as HSB (hue, saturation, brightness), is often used by artists because it is often more natural to think about a color in terms of hue and saturation than in terms of additive or subtractive color components. HSV is a transformation of an RGB colorspace, and its components and colorimetry are relative to the RGB colorspace from which it was derived. Examples :
Input : r, g, b = 45, 215, 0
Output :
h, s, v = 107.44186046511628, 100.0, 84.31372549019608
Input : r, g, v = 31, 52, 29
Output :
h, s, v = 114.78260869565217, 44.230769230769226, 20.392156862745097
Approach :
Divide r, g, b by 255Compute cmax, cmin, differenceHue calculation : if cmax and cmin equal 0, then h = 0if cmax equal r then compute h = (60 * ((g – b) / diff) + 360) % 360if cmax equal g then compute h = (60 * ((b – r) / diff) + 120) % 360if cmax equal b then compute h = (60 * ((r – g) / diff) + 240) % 360Saturation computation : if cmax = 0, then s = 0if cmax does not equal 0 then compute s = (diff/cmax)*100Value computation : v = cmax*100
Divide r, g, b by 255
Compute cmax, cmin, difference
Hue calculation : if cmax and cmin equal 0, then h = 0if cmax equal r then compute h = (60 * ((g – b) / diff) + 360) % 360if cmax equal g then compute h = (60 * ((b – r) / diff) + 120) % 360if cmax equal b then compute h = (60 * ((r – g) / diff) + 240) % 360
if cmax and cmin equal 0, then h = 0
if cmax equal r then compute h = (60 * ((g – b) / diff) + 360) % 360
if cmax equal g then compute h = (60 * ((b – r) / diff) + 120) % 360
if cmax equal b then compute h = (60 * ((r – g) / diff) + 240) % 360
Saturation computation : if cmax = 0, then s = 0if cmax does not equal 0 then compute s = (diff/cmax)*100
if cmax = 0, then s = 0
if cmax does not equal 0 then compute s = (diff/cmax)*100
Value computation : v = cmax*100
v = cmax*100
Below is the implementation of above approach :
Java
Python3
C#
Javascript
// Java program change RGB Color// Model to HSV Color Modelclass GFG{ static void rgb_to_hsv(double r, double g, double b) { // R, G, B values are divided by 255 // to change the range from 0..255 to 0..1 r = r / 255.0; g = g / 255.0; b = b / 255.0; // h, s, v = hue, saturation, value double cmax = Math.max(r, Math.max(g, b)); // maximum of r, g, b double cmin = Math.min(r, Math.min(g, b)); // minimum of r, g, b double diff = cmax - cmin; // diff of cmax and cmin. double h = -1, s = -1; // if cmax and cmax are equal then h = 0 if (cmax == cmin) h = 0; // if cmax equal r then compute h else if (cmax == r) h = (60 * ((g - b) / diff) + 360) % 360; // if cmax equal g then compute h else if (cmax == g) h = (60 * ((b - r) / diff) + 120) % 360; // if cmax equal b then compute h else if (cmax == b) h = (60 * ((r - g) / diff) + 240) % 360; // if cmax equal zero if (cmax == 0) s = 0; else s = (diff / cmax) * 100; // compute v double v = cmax * 100; System.out.println("(" + h + " " + s + " " + v + ")"); } // Driver Code public static void main(String[] args) { // rgb_to_hsv(45, 215, 0); // rgb_to_hsv(31, 52, 29); rgb_to_hsv(129, 88, 47); }} // This code is contributed by PrinciRaj1992
# Python3 program change RGB Color# Model to HSV Color Model def rgb_to_hsv(r, g, b): # R, G, B values are divided by 255 # to change the range from 0..255 to 0..1: r, g, b = r / 255.0, g / 255.0, b / 255.0 # h, s, v = hue, saturation, value cmax = max(r, g, b) # maximum of r, g, b cmin = min(r, g, b) # minimum of r, g, b diff = cmax-cmin # diff of cmax and cmin. # if cmax and cmax are equal then h = 0 if cmax == cmin: h = 0 # if cmax equal r then compute h elif cmax == r: h = (60 * ((g - b) / diff) + 360) % 360 # if cmax equal g then compute h elif cmax == g: h = (60 * ((b - r) / diff) + 120) % 360 # if cmax equal b then compute h elif cmax == b: h = (60 * ((r - g) / diff) + 240) % 360 # if cmax equal zero if cmax == 0: s = 0 else: s = (diff / cmax) * 100 # compute v v = cmax * 100 return h, s, v ''' Driver Code '''# print(rgb_to_hsv(45, 215, 0))# print(rgb_to_hsv(31, 52, 29)) print(rgb_to_hsv(129, 88, 47))
// C# program change RGB Color// Model to HSV Color Modelusing System; class GFG{ static void rgb_to_hsv(double r, double g, double b) { // R, G, B values are divided by 255 // to change the range from 0..255 to 0..1 r = r / 255.0; g = g / 255.0; b = b / 255.0; // h, s, v = hue, saturation, value double cmax = Math.Max(r, Math.Max(g, b)); // maximum of r, g, b double cmin = Math.Min(r, Math.Min(g, b)); // minimum of r, g, b double diff = cmax - cmin; // diff of cmax and cmin. double h = -1, s = -1; // if cmax and cmax are equal then h = 0 if (cmax == cmin) h = 0; // if cmax equal r then compute h else if (cmax == r) h = (60 * ((g - b) / diff) + 360) % 360; // if cmax equal g then compute h else if (cmax == g) h = (60 * ((b - r) / diff) + 120) % 360; // if cmax equal b then compute h else if (cmax == b) h = (60 * ((r - g) / diff) + 240) % 360; // if cmax equal zero if (cmax == 0) s = 0; else s = (diff / cmax) * 100; // compute v double v = cmax * 100; Console.WriteLine("(" + h + " " + s + " " + v + ")"); } // Driver Code public static void Main(String[] args) { // rgb_to_hsv(45, 215, 0); // rgb_to_hsv(31, 52, 29); rgb_to_hsv(129, 88, 47); }} // This code is contributed by Rajput-Ji
<script>// javascript program change RGB Color// Model to HSV Color Model function rgb_to_hsv(r , g , b) { // R, G, B values are divided by 255 // to change the range from 0..255 to 0..1 r = r / 255.0; g = g / 255.0; b = b / 255.0; // h, s, v = hue, saturation, value var cmax = Math.max(r, Math.max(g, b)); // maximum of r, g, b var cmin = Math.min(r, Math.min(g, b)); // minimum of r, g, b var diff = cmax - cmin; // diff of cmax and cmin. var h = -1, s = -1; // if cmax and cmax are equal then h = 0 if (cmax == cmin) h = 0; // if cmax equal r then compute h else if (cmax == r) h = (60 * ((g - b) / diff) + 360) % 360; // if cmax equal g then compute h else if (cmax == g) h = (60 * ((b - r) / diff) + 120) % 360; // if cmax equal b then compute h else if (cmax == b) h = (60 * ((r - g) / diff) + 240) % 360; // if cmax equal zero if (cmax == 0) s = 0; else s = (diff / cmax) * 100; // compute v var v = cmax * 100; document.write("(" + h.toFixed(1) + ", " + s + ", " + v + ")"); } // Driver Code // rgb_to_hsv(45, 215, 0); // rgb_to_hsv(31, 52, 29); rgb_to_hsv(129, 88, 47); // This code is contributed by todaysgaurav</script>
Output :
(30.0, 63.56589147286821, 50.588235294117645)
princiraj1992
Rajput-Ji
todaysgaurav
Mathematical
School Programming
Technical Scripter
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 828,
"s": 52,
"text": "Given RGB color range, our task is to convert RGB color to HSV color.RGB Color Model : The RGB color model is an additive color model in which red, green and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive primary colors, red, green, and blue. HSV Color Model : HSV – (hue, saturation, value), also known as HSB (hue, saturation, brightness), is often used by artists because it is often more natural to think about a color in terms of hue and saturation than in terms of additive or subtractive color components. HSV is a transformation of an RGB colorspace, and its components and colorimetry are relative to the RGB colorspace from which it was derived. Examples : "
},
{
"code": null,
"e": 1030,
"s": 828,
"text": "Input : r, g, b = 45, 215, 0\nOutput :\nh, s, v = 107.44186046511628, 100.0, 84.31372549019608\n\n\nInput : r, g, v = 31, 52, 29\nOutput :\nh, s, v = 114.78260869565217, 44.230769230769226, 20.392156862745097"
},
{
"code": null,
"e": 1044,
"s": 1032,
"text": "Approach : "
},
{
"code": null,
"e": 1491,
"s": 1044,
"text": "Divide r, g, b by 255Compute cmax, cmin, differenceHue calculation : if cmax and cmin equal 0, then h = 0if cmax equal r then compute h = (60 * ((g – b) / diff) + 360) % 360if cmax equal g then compute h = (60 * ((b – r) / diff) + 120) % 360if cmax equal b then compute h = (60 * ((r – g) / diff) + 240) % 360Saturation computation : if cmax = 0, then s = 0if cmax does not equal 0 then compute s = (diff/cmax)*100Value computation : v = cmax*100"
},
{
"code": null,
"e": 1513,
"s": 1491,
"text": "Divide r, g, b by 255"
},
{
"code": null,
"e": 1544,
"s": 1513,
"text": "Compute cmax, cmin, difference"
},
{
"code": null,
"e": 1803,
"s": 1544,
"text": "Hue calculation : if cmax and cmin equal 0, then h = 0if cmax equal r then compute h = (60 * ((g – b) / diff) + 360) % 360if cmax equal g then compute h = (60 * ((b – r) / diff) + 120) % 360if cmax equal b then compute h = (60 * ((r – g) / diff) + 240) % 360"
},
{
"code": null,
"e": 1840,
"s": 1803,
"text": "if cmax and cmin equal 0, then h = 0"
},
{
"code": null,
"e": 1909,
"s": 1840,
"text": "if cmax equal r then compute h = (60 * ((g – b) / diff) + 360) % 360"
},
{
"code": null,
"e": 1978,
"s": 1909,
"text": "if cmax equal g then compute h = (60 * ((b – r) / diff) + 120) % 360"
},
{
"code": null,
"e": 2047,
"s": 1978,
"text": "if cmax equal b then compute h = (60 * ((r – g) / diff) + 240) % 360"
},
{
"code": null,
"e": 2153,
"s": 2047,
"text": "Saturation computation : if cmax = 0, then s = 0if cmax does not equal 0 then compute s = (diff/cmax)*100"
},
{
"code": null,
"e": 2177,
"s": 2153,
"text": "if cmax = 0, then s = 0"
},
{
"code": null,
"e": 2235,
"s": 2177,
"text": "if cmax does not equal 0 then compute s = (diff/cmax)*100"
},
{
"code": null,
"e": 2268,
"s": 2235,
"text": "Value computation : v = cmax*100"
},
{
"code": null,
"e": 2281,
"s": 2268,
"text": "v = cmax*100"
},
{
"code": null,
"e": 2333,
"s": 2283,
"text": " Below is the implementation of above approach : "
},
{
"code": null,
"e": 2342,
"s": 2337,
"text": "Java"
},
{
"code": null,
"e": 2350,
"s": 2342,
"text": "Python3"
},
{
"code": null,
"e": 2353,
"s": 2350,
"text": "C#"
},
{
"code": null,
"e": 2364,
"s": 2353,
"text": "Javascript"
},
{
"code": "// Java program change RGB Color// Model to HSV Color Modelclass GFG{ static void rgb_to_hsv(double r, double g, double b) { // R, G, B values are divided by 255 // to change the range from 0..255 to 0..1 r = r / 255.0; g = g / 255.0; b = b / 255.0; // h, s, v = hue, saturation, value double cmax = Math.max(r, Math.max(g, b)); // maximum of r, g, b double cmin = Math.min(r, Math.min(g, b)); // minimum of r, g, b double diff = cmax - cmin; // diff of cmax and cmin. double h = -1, s = -1; // if cmax and cmax are equal then h = 0 if (cmax == cmin) h = 0; // if cmax equal r then compute h else if (cmax == r) h = (60 * ((g - b) / diff) + 360) % 360; // if cmax equal g then compute h else if (cmax == g) h = (60 * ((b - r) / diff) + 120) % 360; // if cmax equal b then compute h else if (cmax == b) h = (60 * ((r - g) / diff) + 240) % 360; // if cmax equal zero if (cmax == 0) s = 0; else s = (diff / cmax) * 100; // compute v double v = cmax * 100; System.out.println(\"(\" + h + \" \" + s + \" \" + v + \")\"); } // Driver Code public static void main(String[] args) { // rgb_to_hsv(45, 215, 0); // rgb_to_hsv(31, 52, 29); rgb_to_hsv(129, 88, 47); }} // This code is contributed by PrinciRaj1992",
"e": 3853,
"s": 2364,
"text": null
},
{
"code": "# Python3 program change RGB Color# Model to HSV Color Model def rgb_to_hsv(r, g, b): # R, G, B values are divided by 255 # to change the range from 0..255 to 0..1: r, g, b = r / 255.0, g / 255.0, b / 255.0 # h, s, v = hue, saturation, value cmax = max(r, g, b) # maximum of r, g, b cmin = min(r, g, b) # minimum of r, g, b diff = cmax-cmin # diff of cmax and cmin. # if cmax and cmax are equal then h = 0 if cmax == cmin: h = 0 # if cmax equal r then compute h elif cmax == r: h = (60 * ((g - b) / diff) + 360) % 360 # if cmax equal g then compute h elif cmax == g: h = (60 * ((b - r) / diff) + 120) % 360 # if cmax equal b then compute h elif cmax == b: h = (60 * ((r - g) / diff) + 240) % 360 # if cmax equal zero if cmax == 0: s = 0 else: s = (diff / cmax) * 100 # compute v v = cmax * 100 return h, s, v ''' Driver Code '''# print(rgb_to_hsv(45, 215, 0))# print(rgb_to_hsv(31, 52, 29)) print(rgb_to_hsv(129, 88, 47))",
"e": 4905,
"s": 3853,
"text": null
},
{
"code": "// C# program change RGB Color// Model to HSV Color Modelusing System; class GFG{ static void rgb_to_hsv(double r, double g, double b) { // R, G, B values are divided by 255 // to change the range from 0..255 to 0..1 r = r / 255.0; g = g / 255.0; b = b / 255.0; // h, s, v = hue, saturation, value double cmax = Math.Max(r, Math.Max(g, b)); // maximum of r, g, b double cmin = Math.Min(r, Math.Min(g, b)); // minimum of r, g, b double diff = cmax - cmin; // diff of cmax and cmin. double h = -1, s = -1; // if cmax and cmax are equal then h = 0 if (cmax == cmin) h = 0; // if cmax equal r then compute h else if (cmax == r) h = (60 * ((g - b) / diff) + 360) % 360; // if cmax equal g then compute h else if (cmax == g) h = (60 * ((b - r) / diff) + 120) % 360; // if cmax equal b then compute h else if (cmax == b) h = (60 * ((r - g) / diff) + 240) % 360; // if cmax equal zero if (cmax == 0) s = 0; else s = (diff / cmax) * 100; // compute v double v = cmax * 100; Console.WriteLine(\"(\" + h + \" \" + s + \" \" + v + \")\"); } // Driver Code public static void Main(String[] args) { // rgb_to_hsv(45, 215, 0); // rgb_to_hsv(31, 52, 29); rgb_to_hsv(129, 88, 47); }} // This code is contributed by Rajput-Ji",
"e": 6401,
"s": 4905,
"text": null
},
{
"code": "<script>// javascript program change RGB Color// Model to HSV Color Model function rgb_to_hsv(r , g , b) { // R, G, B values are divided by 255 // to change the range from 0..255 to 0..1 r = r / 255.0; g = g / 255.0; b = b / 255.0; // h, s, v = hue, saturation, value var cmax = Math.max(r, Math.max(g, b)); // maximum of r, g, b var cmin = Math.min(r, Math.min(g, b)); // minimum of r, g, b var diff = cmax - cmin; // diff of cmax and cmin. var h = -1, s = -1; // if cmax and cmax are equal then h = 0 if (cmax == cmin) h = 0; // if cmax equal r then compute h else if (cmax == r) h = (60 * ((g - b) / diff) + 360) % 360; // if cmax equal g then compute h else if (cmax == g) h = (60 * ((b - r) / diff) + 120) % 360; // if cmax equal b then compute h else if (cmax == b) h = (60 * ((r - g) / diff) + 240) % 360; // if cmax equal zero if (cmax == 0) s = 0; else s = (diff / cmax) * 100; // compute v var v = cmax * 100; document.write(\"(\" + h.toFixed(1) + \", \" + s + \", \" + v + \")\"); } // Driver Code // rgb_to_hsv(45, 215, 0); // rgb_to_hsv(31, 52, 29); rgb_to_hsv(129, 88, 47); // This code is contributed by todaysgaurav</script>",
"e": 7813,
"s": 6401,
"text": null
},
{
"code": null,
"e": 7823,
"s": 7813,
"text": "Output : "
},
{
"code": null,
"e": 7870,
"s": 7823,
"text": "(30.0, 63.56589147286821, 50.588235294117645) "
},
{
"code": null,
"e": 7886,
"s": 7872,
"text": "princiraj1992"
},
{
"code": null,
"e": 7896,
"s": 7886,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7909,
"s": 7896,
"text": "todaysgaurav"
},
{
"code": null,
"e": 7922,
"s": 7909,
"text": "Mathematical"
},
{
"code": null,
"e": 7941,
"s": 7922,
"text": "School Programming"
},
{
"code": null,
"e": 7960,
"s": 7941,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7973,
"s": 7960,
"text": "Mathematical"
},
{
"code": null,
"e": 8071,
"s": 7973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8103,
"s": 8071,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 8149,
"s": 8103,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 8193,
"s": 8149,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 8235,
"s": 8193,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 8267,
"s": 8235,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 8285,
"s": 8267,
"text": "Python Dictionary"
},
{
"code": null,
"e": 8310,
"s": 8285,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 8326,
"s": 8310,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 8349,
"s": 8326,
"text": "Introduction To PYTHON"
}
] |
Lexicographically largest string using at most K swaps at same parity indices
|
05 Jul, 2021
Given string S and a positive integer K, the task is to find lexicographically the largest possible string using at most K swaps with the condition that the indices that are swapped must be either both odd or both even.
Examples:
Input: S = “ancqz”, K = 2Output: “zqcna“Explanation: In one swap, we can swap characters ‘n’ and ‘q’ as they both are at even indices (2 and 4 assuming 1-based indexing). The string becomes “aqcnz”. In the second swap we can swap characters ‘a’ and ‘z’ as both have odd indices. The final string “zqcna” is the largest lexicographically possible using 2 swap operations.
Note: We cannot swap for instance ‘a’ and ‘n’ or ‘n’ and ‘z’ as one of them would be at an odd index while the other at even index.
Input: S = “geeksforgeeks”, K = 3Output: “sreksfoegeekg“
Naive approach: The naive approach is trivial. Use the greedy algorithm to make the current index maximum starting from left by picking the maximum possible character that is to the right of the current index and is also with the same parity of index i.e. (odd if the current index is odd and even if the current index is even). Repeat the same procedure atmost K times. The time complexity of the approach will be O(N2).
Efficient Approach: The above approach can be improved using a priority queue. Follow the steps below to solve the problem:
Create two priority queue one for odd index characters and another for even index characters.
Iterate over characters in the string, if the even index character comes then search the index which is greater than the current index and character bigger than the current character in the priority queue which is holding even characters. If there is any, swap the two characters push the current character and the index that we found in the priority queue.
The same procedure is to be followed when the odd character comes.
If K becomes 0, terminate the loop.
The resultant string will be the answer.
Below is the implementation of the above approach:
C++
// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function which returns// the largest possible stringstring lexicographicallyLargest(string S, int K){ // Finding length of the string int n = S.length(); // Creating two priority queues of pairs // for odd and even indices separately priority_queue<pair<char, int> > pqOdd, pqEven; // Storing all possible even // indexed values as pairs for (int i = 2; i < n; i = i + 2) { // Stores pair as {character, index} pqEven.push(make_pair(S[i], i)); } // Storing all possible odd indexed // values as pairs for (int i = 3; i < n; i = i + 2) { // Stores pair as {character, index} pqOdd.push(make_pair(S[i], i)); } for (int i = 0; i < n; i++) { // For even indices if (i % 2 == 0) { // Removing pairs which // cannot be used further while (!pqEven.empty() and pqEven.top().second <= i) pqEven.pop(); // If a pair is found whose index comes after // the current index and its character is // greater than the current character if (!pqEven.empty() and pqEven.top().first > S[i]) { // Swap the current index with index of // maximum found character next to it swap(S[i], S[pqEven.top().second]); int idx = pqEven.top().second; pqEven.pop(); // Push the updated character at idx index pqEven.push({ S[idx], idx }); K--; } } // For odd indices else { // Removing pairs which cannot // be used further while (!pqOdd.empty() and pqOdd.top().second <= i) pqOdd.pop(); // If a pair is found whose index comes after // the current index and its character is // greater than the current character if (!pqOdd.empty() and pqOdd.top().first > S[i]) { // Swap the current index with index of // maximum found character next to it swap(S[i], S[pqOdd.top().second]); int idx = pqOdd.top().second; pqOdd.pop(); // Push the updated character at idx index pqOdd.push({ S[idx], idx }); K--; } } // Breaking out of the loop if K=0 if (K == 0) break; } return S;} // Driver Codeint main(){ // Input string S = "geeksforgeeks"; int K = 2; // Function Call cout << lexicographicallyLargest(S, K); return 0;}
sreksfoegeekg
Time Complexity: O(NlogN)Auxiliary Space: O(N)
lexicographic-ordering
Greedy
Queue
Strings
Strings
Greedy
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Policemen catch thieves
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Maximize difference between the Sum of the two halves of the Array after removal of N elements
Minimize Cash Flow among a given set of friends who have borrowed money from each other
Minimum time taken by each job to be completed given by a Directed Acyclic Graph
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue in Python
Queue Interface In Java
Introduction to Data Structures
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 248,
"s": 28,
"text": "Given string S and a positive integer K, the task is to find lexicographically the largest possible string using at most K swaps with the condition that the indices that are swapped must be either both odd or both even."
},
{
"code": null,
"e": 259,
"s": 248,
"text": "Examples: "
},
{
"code": null,
"e": 631,
"s": 259,
"text": "Input: S = “ancqz”, K = 2Output: “zqcna“Explanation: In one swap, we can swap characters ‘n’ and ‘q’ as they both are at even indices (2 and 4 assuming 1-based indexing). The string becomes “aqcnz”. In the second swap we can swap characters ‘a’ and ‘z’ as both have odd indices. The final string “zqcna” is the largest lexicographically possible using 2 swap operations."
},
{
"code": null,
"e": 765,
"s": 631,
"text": "Note: We cannot swap for instance ‘a’ and ‘n’ or ‘n’ and ‘z’ as one of them would be at an odd index while the other at even index. "
},
{
"code": null,
"e": 823,
"s": 765,
"text": "Input: S = “geeksforgeeks”, K = 3Output: “sreksfoegeekg“"
},
{
"code": null,
"e": 1245,
"s": 823,
"text": "Naive approach: The naive approach is trivial. Use the greedy algorithm to make the current index maximum starting from left by picking the maximum possible character that is to the right of the current index and is also with the same parity of index i.e. (odd if the current index is odd and even if the current index is even). Repeat the same procedure atmost K times. The time complexity of the approach will be O(N2)."
},
{
"code": null,
"e": 1369,
"s": 1245,
"text": "Efficient Approach: The above approach can be improved using a priority queue. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1463,
"s": 1369,
"text": "Create two priority queue one for odd index characters and another for even index characters."
},
{
"code": null,
"e": 1821,
"s": 1463,
"text": "Iterate over characters in the string, if the even index character comes then search the index which is greater than the current index and character bigger than the current character in the priority queue which is holding even characters. If there is any, swap the two characters push the current character and the index that we found in the priority queue."
},
{
"code": null,
"e": 1888,
"s": 1821,
"text": "The same procedure is to be followed when the odd character comes."
},
{
"code": null,
"e": 1924,
"s": 1888,
"text": "If K becomes 0, terminate the loop."
},
{
"code": null,
"e": 1965,
"s": 1924,
"text": "The resultant string will be the answer."
},
{
"code": null,
"e": 2016,
"s": 1965,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2020,
"s": 2016,
"text": "C++"
},
{
"code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function which returns// the largest possible stringstring lexicographicallyLargest(string S, int K){ // Finding length of the string int n = S.length(); // Creating two priority queues of pairs // for odd and even indices separately priority_queue<pair<char, int> > pqOdd, pqEven; // Storing all possible even // indexed values as pairs for (int i = 2; i < n; i = i + 2) { // Stores pair as {character, index} pqEven.push(make_pair(S[i], i)); } // Storing all possible odd indexed // values as pairs for (int i = 3; i < n; i = i + 2) { // Stores pair as {character, index} pqOdd.push(make_pair(S[i], i)); } for (int i = 0; i < n; i++) { // For even indices if (i % 2 == 0) { // Removing pairs which // cannot be used further while (!pqEven.empty() and pqEven.top().second <= i) pqEven.pop(); // If a pair is found whose index comes after // the current index and its character is // greater than the current character if (!pqEven.empty() and pqEven.top().first > S[i]) { // Swap the current index with index of // maximum found character next to it swap(S[i], S[pqEven.top().second]); int idx = pqEven.top().second; pqEven.pop(); // Push the updated character at idx index pqEven.push({ S[idx], idx }); K--; } } // For odd indices else { // Removing pairs which cannot // be used further while (!pqOdd.empty() and pqOdd.top().second <= i) pqOdd.pop(); // If a pair is found whose index comes after // the current index and its character is // greater than the current character if (!pqOdd.empty() and pqOdd.top().first > S[i]) { // Swap the current index with index of // maximum found character next to it swap(S[i], S[pqOdd.top().second]); int idx = pqOdd.top().second; pqOdd.pop(); // Push the updated character at idx index pqOdd.push({ S[idx], idx }); K--; } } // Breaking out of the loop if K=0 if (K == 0) break; } return S;} // Driver Codeint main(){ // Input string S = \"geeksforgeeks\"; int K = 2; // Function Call cout << lexicographicallyLargest(S, K); return 0;}",
"e": 4785,
"s": 2020,
"text": null
},
{
"code": null,
"e": 4800,
"s": 4785,
"text": "sreksfoegeekg\n"
},
{
"code": null,
"e": 4852,
"s": 4800,
"text": "Time Complexity: O(NlogN)Auxiliary Space: O(N) "
},
{
"code": null,
"e": 4875,
"s": 4852,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 4882,
"s": 4875,
"text": "Greedy"
},
{
"code": null,
"e": 4888,
"s": 4882,
"text": "Queue"
},
{
"code": null,
"e": 4896,
"s": 4888,
"text": "Strings"
},
{
"code": null,
"e": 4904,
"s": 4896,
"text": "Strings"
},
{
"code": null,
"e": 4911,
"s": 4904,
"text": "Greedy"
},
{
"code": null,
"e": 4917,
"s": 4911,
"text": "Queue"
},
{
"code": null,
"e": 5015,
"s": 4917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5039,
"s": 5015,
"text": "Policemen catch thieves"
},
{
"code": null,
"e": 5096,
"s": 5039,
"text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)"
},
{
"code": null,
"e": 5191,
"s": 5096,
"text": "Maximize difference between the Sum of the two halves of the Array after removal of N elements"
},
{
"code": null,
"e": 5279,
"s": 5191,
"text": "Minimize Cash Flow among a given set of friends who have borrowed money from each other"
},
{
"code": null,
"e": 5360,
"s": 5279,
"text": "Minimum time taken by each job to be completed given by a Directed Acyclic Graph"
},
{
"code": null,
"e": 5400,
"s": 5360,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 5434,
"s": 5400,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 5450,
"s": 5434,
"text": "Queue in Python"
},
{
"code": null,
"e": 5474,
"s": 5450,
"text": "Queue Interface In Java"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.