title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to return the data type of variable in JavaScript ? - GeeksforGeeks | 09 Apr, 2021
In JavaScript, unlike many other programming languages, we do not specify the type of a variable while declaring it, rather the variable’s type is automatically inferred based on the value it holds. In other words, JavaScript is a “dynamically typed” programming language. In such languages, the type of a variable can change throughout the program.
Example
Javascript
<script> // x is a number var x = 4242; console.log(x); // x is a string x = "GeeksforGeeks"; console.log(x) // x is an object x = { k: 4245, a: "geeks" }; console.log(x)</script>
Output:
4242
GeeksforGeeks
{k: 4245, a: "geeks"}
As seen in the above example, x was initialized to a number, then we initialized it to a string and then an object. This makes it difficult to keep track of the type of variable ‘x’ throughout the program.
typeof: The typeof keyword helps to determine the type of a variable in Javascript. Since Javascript is a dynamically typed programming language, typeof can be used to find the variable type.
It can be used within a function to check the data type of a variable or to check if a variable is declared.
Let’s consider the following examples to understand this better.
Example 1:
Javascript
<script> var x = 12345; console.log(typeof(x)); </script>
Output:
number
Example 2:
Javascript
<script> var x = "GeeksforGeeks"; console.log(typeof(x)); </script>
Output:
string
Example 3:
Javascript
<script> var x = { k : 12, m : "geeky stuff"} console.log(typeof(x)) console.log(typeof(x.k)) console.log(typeof(x.m)) console.log(typeof(x.s)) </script>
Output:
object
number
string
undefined
A common use of typeof operator is to determine the variable type and perform actions accordingly within a function.
Example:
Javascript
<script> function doX(x) { if (typeof(x) === "number") { console.log("x is a number") } if (typeof(x) === "string") { console.log("x is a string") } if (typeof(x) === "undefined") { console.log("x is undefined") } } doX(12) doX("hello gfg")</script>
Invoke the above function with number and string as an argument.
Output:
x is a number
x is a string
Another use of typeof operator is to check if a variable is declared before it’s usage.
Example:
Javascript
<script> function checkX(x) { if (typeof(x) === "undefined") { console.log( "x is undefined. Please declare it"); } else { console.log("We can process x!") } } checkX() checkX("hello")</script>
Invoking the above function without passing an argument and by passing a string as an argument.
Output:
x is undefined. Please declare it
We can process x!
One small caveat with typeof is that typeof(NaN) returns a number. When we multiply a string with a number we get NaN, as seen in the below example.
Example:
Javascript
<script> var x = "hello" console.log(x) var y = 10 console.log(y) z = x * y console.log(z) console.log(typeof(z))</script>
Output:
hello
10
NaN
number
javascript-operators
JavaScript-Questions
Picked
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 26895,
"s": 26545,
"text": "In JavaScript, unlike many other programming languages, we do not specify the type of a variable while declaring it, rather the variable’s type is automatically inferred based on the value it holds. In other words, JavaScript is a “dynamically typed” programming language. In such languages, the type of a variable can change throughout the program."
},
{
"code": null,
"e": 26903,
"s": 26895,
"text": "Example"
},
{
"code": null,
"e": 26914,
"s": 26903,
"text": "Javascript"
},
{
"code": "<script> // x is a number var x = 4242; console.log(x); // x is a string x = \"GeeksforGeeks\"; console.log(x) // x is an object x = { k: 4245, a: \"geeks\" }; console.log(x)</script>",
"e": 27145,
"s": 26914,
"text": null
},
{
"code": null,
"e": 27153,
"s": 27145,
"text": "Output:"
},
{
"code": null,
"e": 27194,
"s": 27153,
"text": "4242\nGeeksforGeeks\n{k: 4245, a: \"geeks\"}"
},
{
"code": null,
"e": 27400,
"s": 27194,
"text": "As seen in the above example, x was initialized to a number, then we initialized it to a string and then an object. This makes it difficult to keep track of the type of variable ‘x’ throughout the program."
},
{
"code": null,
"e": 27592,
"s": 27400,
"text": "typeof: The typeof keyword helps to determine the type of a variable in Javascript. Since Javascript is a dynamically typed programming language, typeof can be used to find the variable type."
},
{
"code": null,
"e": 27701,
"s": 27592,
"text": "It can be used within a function to check the data type of a variable or to check if a variable is declared."
},
{
"code": null,
"e": 27766,
"s": 27701,
"text": "Let’s consider the following examples to understand this better."
},
{
"code": null,
"e": 27777,
"s": 27766,
"text": "Example 1:"
},
{
"code": null,
"e": 27788,
"s": 27777,
"text": "Javascript"
},
{
"code": "<script> var x = 12345; console.log(typeof(x)); </script>",
"e": 27859,
"s": 27788,
"text": null
},
{
"code": null,
"e": 27867,
"s": 27859,
"text": "Output:"
},
{
"code": null,
"e": 27874,
"s": 27867,
"text": "number"
},
{
"code": null,
"e": 27885,
"s": 27874,
"text": "Example 2:"
},
{
"code": null,
"e": 27896,
"s": 27885,
"text": "Javascript"
},
{
"code": "<script> var x = \"GeeksforGeeks\"; console.log(typeof(x)); </script>",
"e": 27973,
"s": 27896,
"text": null
},
{
"code": null,
"e": 27981,
"s": 27973,
"text": "Output:"
},
{
"code": null,
"e": 27988,
"s": 27981,
"text": "string"
},
{
"code": null,
"e": 27999,
"s": 27988,
"text": "Example 3:"
},
{
"code": null,
"e": 28010,
"s": 27999,
"text": "Javascript"
},
{
"code": "<script> var x = { k : 12, m : \"geeky stuff\"} console.log(typeof(x)) console.log(typeof(x.k)) console.log(typeof(x.m)) console.log(typeof(x.s)) </script>",
"e": 28174,
"s": 28010,
"text": null
},
{
"code": null,
"e": 28182,
"s": 28174,
"text": "Output:"
},
{
"code": null,
"e": 28213,
"s": 28182,
"text": "object\nnumber\nstring\nundefined"
},
{
"code": null,
"e": 28330,
"s": 28213,
"text": "A common use of typeof operator is to determine the variable type and perform actions accordingly within a function."
},
{
"code": null,
"e": 28339,
"s": 28330,
"text": "Example:"
},
{
"code": null,
"e": 28350,
"s": 28339,
"text": "Javascript"
},
{
"code": "<script> function doX(x) { if (typeof(x) === \"number\") { console.log(\"x is a number\") } if (typeof(x) === \"string\") { console.log(\"x is a string\") } if (typeof(x) === \"undefined\") { console.log(\"x is undefined\") } } doX(12) doX(\"hello gfg\")</script>",
"e": 28689,
"s": 28350,
"text": null
},
{
"code": null,
"e": 28755,
"s": 28689,
"text": "Invoke the above function with number and string as an argument."
},
{
"code": null,
"e": 28763,
"s": 28755,
"text": "Output:"
},
{
"code": null,
"e": 28791,
"s": 28763,
"text": "x is a number\nx is a string"
},
{
"code": null,
"e": 28879,
"s": 28791,
"text": "Another use of typeof operator is to check if a variable is declared before it’s usage."
},
{
"code": null,
"e": 28888,
"s": 28879,
"text": "Example:"
},
{
"code": null,
"e": 28899,
"s": 28888,
"text": "Javascript"
},
{
"code": "<script> function checkX(x) { if (typeof(x) === \"undefined\") { console.log( \"x is undefined. Please declare it\"); } else { console.log(\"We can process x!\") } } checkX() checkX(\"hello\")</script>",
"e": 29153,
"s": 28899,
"text": null
},
{
"code": null,
"e": 29249,
"s": 29153,
"text": "Invoking the above function without passing an argument and by passing a string as an argument."
},
{
"code": null,
"e": 29257,
"s": 29249,
"text": "Output:"
},
{
"code": null,
"e": 29309,
"s": 29257,
"text": "x is undefined. Please declare it\nWe can process x!"
},
{
"code": null,
"e": 29459,
"s": 29309,
"text": "One small caveat with typeof is that typeof(NaN) returns a number. When we multiply a string with a number we get NaN, as seen in the below example."
},
{
"code": null,
"e": 29468,
"s": 29459,
"text": "Example:"
},
{
"code": null,
"e": 29479,
"s": 29468,
"text": "Javascript"
},
{
"code": "<script> var x = \"hello\" console.log(x) var y = 10 console.log(y) z = x * y console.log(z) console.log(typeof(z))</script>",
"e": 29631,
"s": 29479,
"text": null
},
{
"code": null,
"e": 29639,
"s": 29631,
"text": "Output:"
},
{
"code": null,
"e": 29659,
"s": 29639,
"text": "hello\n10\nNaN\nnumber"
},
{
"code": null,
"e": 29680,
"s": 29659,
"text": "javascript-operators"
},
{
"code": null,
"e": 29701,
"s": 29680,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 29708,
"s": 29701,
"text": "Picked"
},
{
"code": null,
"e": 29719,
"s": 29708,
"text": "JavaScript"
},
{
"code": null,
"e": 29736,
"s": 29719,
"text": "Web Technologies"
},
{
"code": null,
"e": 29834,
"s": 29736,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29874,
"s": 29834,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29935,
"s": 29874,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29976,
"s": 29935,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29998,
"s": 29976,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 30052,
"s": 29998,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30092,
"s": 30052,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30125,
"s": 30092,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30168,
"s": 30125,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30230,
"s": 30168,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How To Make Histogram with Median Line using Altair in Python? - GeeksforGeeks | 26 Nov, 2020
In this article, we will learn about how to make the histogram with the median line using Altair in python. This article is also a great example of Altair’s grammar of graphics.
Altair is one of the latest interactive data visualizations library in python. Altair is based on vega and vegalite- A grammar of interactive graphics. Here we will use the import keyword to use Altair library for using it.
First, we will load the packages of python that are used to make a histogram with a mean and median line using Altair.
Python3
# import required modulesimport altair as altimport numpy as npimport pandas as pd
Now we will generate the data to make a histogram with the median line. Here, we will use Numpy to generate random numbers from a normal distribution and create panda data frames.
Python3
# generating datanp.random.seed(42)df = pd.DataFrame({'height': np.random.normal(150, 10, 1000)})
Basically here we tend to build the bar chart with the median line which can produce two layers of double star image object and combine them. Using Altair’s chart function, we create the base plot of the data frames of data.
Python3
# initialize chartbase=alt.Chart(df)
Now we use Altair’s mark_bar() function and create the base object to make a histogram. Also, here we mention which variable we are interested to make a histogram.
Python3
# generate histogramhist = base.mark_bar().encode( x=alt.X('height:Q', bin=alt.BinParams(), axis=None), y='count()')
Using mark_rule() function in the Altair library, we use the base object with the data again to create a median line.
Python3
# generate median linemedian_line = base.mark_rule().encode( x=alt.X('mean(height):Q', title='Height'), size=alt.value(5))
Now to form the fundamental histogram with the median line we have a tendency to merely combine the bar graph object and median line object as follows:
Python3
# depict illustrationhist+median_line
Output:
Therefore, here we get the histogram with the median line using Altair in python.
Let us now understand to get the Customized histogram.
In the basic histogram with the median line, Altair library uses the default parameters to plot the histogram. Like, Altair has chosen a blue color for the histogram and the number of bins for us. Similarly, Altair chose the black color for the median line. But we can easily customize the histogram with the median line using Altair.
First, we will increase the number of bins in the histogram, and then we will change the color of the median line to red.
We will use maxbins=100 argument within the coordinate axis parameter, to form the histogram with 100 bins. Then we can change the color of the median line to red using color=red inside mark_rule() function. And lastly, let us combine both histogram and median line object. And then we will improve the version of the histogram with a median line in Altair.
Python3
# import required modulesimport altair as altimport numpy as npimport pandas as pd # generating datanp.random.seed(42)df = pd.DataFrame({'height': np.random.normal(150, 10, 1000)}) # initialize chartbase = alt.Chart(df) # generate histogramhist = base.mark_bar().encode( x=alt.X('height:Q', bin=alt.BinParams(maxbins=100), axis=None), y='count()') # generate median linered_median_line = base.mark_rule(color='red').encode( x=alt.X('mean(height):Q', title='Height'), size=alt.value(5)) # depict illustrationhist+red_median_line
Output:
Therefore, the above figure shows the histogram with 100 bins and a red median line using Altair in python.
Python-Altair
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 25716,
"s": 25537,
"text": "In this article, we will learn about how to make the histogram with the median line using Altair in python. This article is also a great example of Altair’s grammar of graphics. "
},
{
"code": null,
"e": 25941,
"s": 25716,
"text": "Altair is one of the latest interactive data visualizations library in python. Altair is based on vega and vegalite- A grammar of interactive graphics. Here we will use the import keyword to use Altair library for using it. "
},
{
"code": null,
"e": 26061,
"s": 25941,
"text": "First, we will load the packages of python that are used to make a histogram with a mean and median line using Altair. "
},
{
"code": null,
"e": 26069,
"s": 26061,
"text": "Python3"
},
{
"code": "# import required modulesimport altair as altimport numpy as npimport pandas as pd",
"e": 26152,
"s": 26069,
"text": null
},
{
"code": null,
"e": 26333,
"s": 26152,
"text": "Now we will generate the data to make a histogram with the median line. Here, we will use Numpy to generate random numbers from a normal distribution and create panda data frames. "
},
{
"code": null,
"e": 26341,
"s": 26333,
"text": "Python3"
},
{
"code": "# generating datanp.random.seed(42)df = pd.DataFrame({'height': np.random.normal(150, 10, 1000)})",
"e": 26439,
"s": 26341,
"text": null
},
{
"code": null,
"e": 26665,
"s": 26439,
"text": "Basically here we tend to build the bar chart with the median line which can produce two layers of double star image object and combine them. Using Altair’s chart function, we create the base plot of the data frames of data. "
},
{
"code": null,
"e": 26673,
"s": 26665,
"text": "Python3"
},
{
"code": "# initialize chartbase=alt.Chart(df)",
"e": 26710,
"s": 26673,
"text": null
},
{
"code": null,
"e": 26875,
"s": 26710,
"text": "Now we use Altair’s mark_bar() function and create the base object to make a histogram. Also, here we mention which variable we are interested to make a histogram. "
},
{
"code": null,
"e": 26883,
"s": 26875,
"text": "Python3"
},
{
"code": "# generate histogramhist = base.mark_bar().encode( x=alt.X('height:Q', bin=alt.BinParams(), axis=None), y='count()')",
"e": 27003,
"s": 26883,
"text": null
},
{
"code": null,
"e": 27121,
"s": 27003,
"text": "Using mark_rule() function in the Altair library, we use the base object with the data again to create a median line."
},
{
"code": null,
"e": 27129,
"s": 27121,
"text": "Python3"
},
{
"code": "# generate median linemedian_line = base.mark_rule().encode( x=alt.X('mean(height):Q', title='Height'), size=alt.value(5))",
"e": 27255,
"s": 27129,
"text": null
},
{
"code": null,
"e": 27407,
"s": 27255,
"text": "Now to form the fundamental histogram with the median line we have a tendency to merely combine the bar graph object and median line object as follows:"
},
{
"code": null,
"e": 27415,
"s": 27407,
"text": "Python3"
},
{
"code": "# depict illustrationhist+median_line",
"e": 27453,
"s": 27415,
"text": null
},
{
"code": null,
"e": 27461,
"s": 27453,
"text": "Output:"
},
{
"code": null,
"e": 27544,
"s": 27461,
"text": "Therefore, here we get the histogram with the median line using Altair in python. "
},
{
"code": null,
"e": 27599,
"s": 27544,
"text": "Let us now understand to get the Customized histogram."
},
{
"code": null,
"e": 27935,
"s": 27599,
"text": "In the basic histogram with the median line, Altair library uses the default parameters to plot the histogram. Like, Altair has chosen a blue color for the histogram and the number of bins for us. Similarly, Altair chose the black color for the median line. But we can easily customize the histogram with the median line using Altair. "
},
{
"code": null,
"e": 28058,
"s": 27935,
"text": "First, we will increase the number of bins in the histogram, and then we will change the color of the median line to red. "
},
{
"code": null,
"e": 28416,
"s": 28058,
"text": "We will use maxbins=100 argument within the coordinate axis parameter, to form the histogram with 100 bins. Then we can change the color of the median line to red using color=red inside mark_rule() function. And lastly, let us combine both histogram and median line object. And then we will improve the version of the histogram with a median line in Altair."
},
{
"code": null,
"e": 28424,
"s": 28416,
"text": "Python3"
},
{
"code": "# import required modulesimport altair as altimport numpy as npimport pandas as pd # generating datanp.random.seed(42)df = pd.DataFrame({'height': np.random.normal(150, 10, 1000)}) # initialize chartbase = alt.Chart(df) # generate histogramhist = base.mark_bar().encode( x=alt.X('height:Q', bin=alt.BinParams(maxbins=100), axis=None), y='count()') # generate median linered_median_line = base.mark_rule(color='red').encode( x=alt.X('mean(height):Q', title='Height'), size=alt.value(5)) # depict illustrationhist+red_median_line",
"e": 28963,
"s": 28424,
"text": null
},
{
"code": null,
"e": 28971,
"s": 28963,
"text": "Output:"
},
{
"code": null,
"e": 29079,
"s": 28971,
"text": "Therefore, the above figure shows the histogram with 100 bins and a red median line using Altair in python."
},
{
"code": null,
"e": 29093,
"s": 29079,
"text": "Python-Altair"
},
{
"code": null,
"e": 29117,
"s": 29093,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29124,
"s": 29117,
"text": "Python"
},
{
"code": null,
"e": 29143,
"s": 29124,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29241,
"s": 29143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29273,
"s": 29241,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29315,
"s": 29273,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29357,
"s": 29315,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29384,
"s": 29357,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29440,
"s": 29384,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29462,
"s": 29440,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29501,
"s": 29462,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29532,
"s": 29501,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29561,
"s": 29532,
"text": "Create a directory in Python"
}
] |
Python Number fabs() Method | Python number method fabs() returns the absolute value of x.
Following is the syntax for fabs() method −
import math
math.fabs( x )
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This is a numeric value.
x − This is a numeric value.
This method returns absolute value of x.
The following example shows the usage of fabs() method.
#!/usr/bin/python
import math # This will import math module
print "math.fabs(-45.17) : ", math.fabs(-45.17)
print "math.fabs(100.12) : ", math.fabs(100.12)
print "math.fabs(100.72) : ", math.fabs(100.72)
print "math.fabs(119L) : ", math.fabs(119L)
print "math.fabs(math.pi) : ", math.fabs(math.pi)
When we run above program, it produces following result −
math.fabs(-45.17) : 45.17
math.fabs(100.12) : 100.12
math.fabs(100.72) : 100.72
math.fabs(119L) : 119.0
math.fabs(math.pi) : 3.14159265359
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2306,
"s": 2244,
"text": "Python number method fabs() returns the absolute value of x."
},
{
"code": null,
"e": 2350,
"s": 2306,
"text": "Following is the syntax for fabs() method −"
},
{
"code": null,
"e": 2378,
"s": 2350,
"text": "import math\n\nmath.fabs( x )"
},
{
"code": null,
"e": 2525,
"s": 2378,
"text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object."
},
{
"code": null,
"e": 2554,
"s": 2525,
"text": "x − This is a numeric value."
},
{
"code": null,
"e": 2583,
"s": 2554,
"text": "x − This is a numeric value."
},
{
"code": null,
"e": 2624,
"s": 2583,
"text": "This method returns absolute value of x."
},
{
"code": null,
"e": 2680,
"s": 2624,
"text": "The following example shows the usage of fabs() method."
},
{
"code": null,
"e": 2982,
"s": 2680,
"text": "#!/usr/bin/python\nimport math # This will import math module\n\nprint \"math.fabs(-45.17) : \", math.fabs(-45.17)\nprint \"math.fabs(100.12) : \", math.fabs(100.12)\nprint \"math.fabs(100.72) : \", math.fabs(100.72)\nprint \"math.fabs(119L) : \", math.fabs(119L)\nprint \"math.fabs(math.pi) : \", math.fabs(math.pi)"
},
{
"code": null,
"e": 3040,
"s": 2982,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3185,
"s": 3040,
"text": "math.fabs(-45.17) : 45.17\nmath.fabs(100.12) : 100.12\nmath.fabs(100.72) : 100.72\nmath.fabs(119L) : 119.0\nmath.fabs(math.pi) : 3.14159265359\n"
},
{
"code": null,
"e": 3222,
"s": 3185,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3238,
"s": 3222,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3271,
"s": 3238,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3290,
"s": 3271,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3325,
"s": 3290,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3347,
"s": 3325,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3381,
"s": 3347,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3409,
"s": 3381,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3444,
"s": 3409,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3458,
"s": 3444,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3491,
"s": 3458,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3508,
"s": 3491,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3515,
"s": 3508,
"text": " Print"
},
{
"code": null,
"e": 3526,
"s": 3515,
"text": " Add Notes"
}
] |
Create Dataset for Sentiment Analysis by Scraping Google Play App Reviews using Python | by Venelin Valkov | Towards Data Science | TL;DR Learn how to create a dataset for Sentiment Analysis by scraping user reviews for Android apps. You’ll convert the app and review information into Data Frames and save that to CSV files.
Run the notebook in your browser (Google Colab)
Complete project on GitHub
leanpub.com
You’ll learn how to:
Set a goal and inclusion criteria for your dataset
Get real-world user reviews by scraping Google Play
Use Pandas to convert and save the dataset into CSV files
Let’s install the required packages and set up the imports:
You want to get feedback for your app. Both negative and positive are good. But the negative one can reveal critical features that are missing or downtime of your service (when it is much more frequent).
Lucky for us, Google Play has plenty of apps, reviews, and scores. We can scrape app info and reviews using the google-play-scraper package.
You can choose plenty of apps to analyze. But different app categories contain different audiences, domain-specific quirks, and more. We’ll start simple.
We want apps that have been around some time, so opinion is collected organically. We want to mitigate advertising strategies as much as possible. Apps are constantly being updated, so the time of the review is an important factor.
Ideally, you would want to collect every possible review and work with that. However, in the real world data is often limited (too large, inaccessible, etc). So, we’ll do the best we can.
Let’s choose some apps that fit the criteria from the Productivity category. We’ll use AppAnnie to select some of the top US apps:
Let’s scrape the info for each app:
We got the info for all 15 apps. Let’s write a helper function that prints JSON objects a bit better:
Here is a sample app information from the list:
This contains lots of information including the number of ratings, number of reviews and number of ratings for each score (1 to 5). Let’s ignore all of that and have a look at their beautiful icons:
We’ll store the app information for later by converting the JSON objects into a Pandas dataframe and saving the result into a CSV file:
In an ideal world, we would get all the reviews. But there are lots of them and we’re scraping the data. That wouldn’t be very polite. What should we do?
We want:
Balanced dataset — roughly the same number of reviews for each score (1–5)
A representative sample of the reviews for each app
We can satisfy the first requirement by using the scraping package option to filter the review score. For the second, we’ll sort the reviews by their helpfulness, which are the reviews that Google Play thinks are most important. Just in case, we’ll get a subset from the newest, too:
Note that we’re adding the app id and sort order to each review. Here’s an example for one:
repliedAt and replyContent contain the developer's response to the review. Of course, they can be missing.
How many app reviews did we get?
15750
Let’s save the reviews to a CSV file:
Well done! You now have a dataset with more than 15k user reviews from 15 productivity apps. Of course, you can go crazy and get much much more.
Run the notebook in your browser (Google Colab)
Complete project on GitHub
leanpub.com
You learned how to:
Set goals and expectations for your dataset
Scrape Google Play app information
Scrape user reviews for Google Play apps
Save the dataset to CSV files
Next, we’re going to use the reviews for sentiment analysis with BERT. But first, we’ll have to do some text preprocessing!
Google Play Scraper for Python
Originally published at https://www.curiousily.com. | [
{
"code": null,
"e": 364,
"s": 171,
"text": "TL;DR Learn how to create a dataset for Sentiment Analysis by scraping user reviews for Android apps. You’ll convert the app and review information into Data Frames and save that to CSV files."
},
{
"code": null,
"e": 412,
"s": 364,
"text": "Run the notebook in your browser (Google Colab)"
},
{
"code": null,
"e": 439,
"s": 412,
"text": "Complete project on GitHub"
},
{
"code": null,
"e": 451,
"s": 439,
"text": "leanpub.com"
},
{
"code": null,
"e": 472,
"s": 451,
"text": "You’ll learn how to:"
},
{
"code": null,
"e": 523,
"s": 472,
"text": "Set a goal and inclusion criteria for your dataset"
},
{
"code": null,
"e": 575,
"s": 523,
"text": "Get real-world user reviews by scraping Google Play"
},
{
"code": null,
"e": 633,
"s": 575,
"text": "Use Pandas to convert and save the dataset into CSV files"
},
{
"code": null,
"e": 693,
"s": 633,
"text": "Let’s install the required packages and set up the imports:"
},
{
"code": null,
"e": 897,
"s": 693,
"text": "You want to get feedback for your app. Both negative and positive are good. But the negative one can reveal critical features that are missing or downtime of your service (when it is much more frequent)."
},
{
"code": null,
"e": 1038,
"s": 897,
"text": "Lucky for us, Google Play has plenty of apps, reviews, and scores. We can scrape app info and reviews using the google-play-scraper package."
},
{
"code": null,
"e": 1192,
"s": 1038,
"text": "You can choose plenty of apps to analyze. But different app categories contain different audiences, domain-specific quirks, and more. We’ll start simple."
},
{
"code": null,
"e": 1424,
"s": 1192,
"text": "We want apps that have been around some time, so opinion is collected organically. We want to mitigate advertising strategies as much as possible. Apps are constantly being updated, so the time of the review is an important factor."
},
{
"code": null,
"e": 1612,
"s": 1424,
"text": "Ideally, you would want to collect every possible review and work with that. However, in the real world data is often limited (too large, inaccessible, etc). So, we’ll do the best we can."
},
{
"code": null,
"e": 1743,
"s": 1612,
"text": "Let’s choose some apps that fit the criteria from the Productivity category. We’ll use AppAnnie to select some of the top US apps:"
},
{
"code": null,
"e": 1779,
"s": 1743,
"text": "Let’s scrape the info for each app:"
},
{
"code": null,
"e": 1881,
"s": 1779,
"text": "We got the info for all 15 apps. Let’s write a helper function that prints JSON objects a bit better:"
},
{
"code": null,
"e": 1929,
"s": 1881,
"text": "Here is a sample app information from the list:"
},
{
"code": null,
"e": 2128,
"s": 1929,
"text": "This contains lots of information including the number of ratings, number of reviews and number of ratings for each score (1 to 5). Let’s ignore all of that and have a look at their beautiful icons:"
},
{
"code": null,
"e": 2264,
"s": 2128,
"text": "We’ll store the app information for later by converting the JSON objects into a Pandas dataframe and saving the result into a CSV file:"
},
{
"code": null,
"e": 2418,
"s": 2264,
"text": "In an ideal world, we would get all the reviews. But there are lots of them and we’re scraping the data. That wouldn’t be very polite. What should we do?"
},
{
"code": null,
"e": 2427,
"s": 2418,
"text": "We want:"
},
{
"code": null,
"e": 2502,
"s": 2427,
"text": "Balanced dataset — roughly the same number of reviews for each score (1–5)"
},
{
"code": null,
"e": 2554,
"s": 2502,
"text": "A representative sample of the reviews for each app"
},
{
"code": null,
"e": 2838,
"s": 2554,
"text": "We can satisfy the first requirement by using the scraping package option to filter the review score. For the second, we’ll sort the reviews by their helpfulness, which are the reviews that Google Play thinks are most important. Just in case, we’ll get a subset from the newest, too:"
},
{
"code": null,
"e": 2930,
"s": 2838,
"text": "Note that we’re adding the app id and sort order to each review. Here’s an example for one:"
},
{
"code": null,
"e": 3037,
"s": 2930,
"text": "repliedAt and replyContent contain the developer's response to the review. Of course, they can be missing."
},
{
"code": null,
"e": 3070,
"s": 3037,
"text": "How many app reviews did we get?"
},
{
"code": null,
"e": 3076,
"s": 3070,
"text": "15750"
},
{
"code": null,
"e": 3114,
"s": 3076,
"text": "Let’s save the reviews to a CSV file:"
},
{
"code": null,
"e": 3259,
"s": 3114,
"text": "Well done! You now have a dataset with more than 15k user reviews from 15 productivity apps. Of course, you can go crazy and get much much more."
},
{
"code": null,
"e": 3307,
"s": 3259,
"text": "Run the notebook in your browser (Google Colab)"
},
{
"code": null,
"e": 3334,
"s": 3307,
"text": "Complete project on GitHub"
},
{
"code": null,
"e": 3346,
"s": 3334,
"text": "leanpub.com"
},
{
"code": null,
"e": 3366,
"s": 3346,
"text": "You learned how to:"
},
{
"code": null,
"e": 3410,
"s": 3366,
"text": "Set goals and expectations for your dataset"
},
{
"code": null,
"e": 3445,
"s": 3410,
"text": "Scrape Google Play app information"
},
{
"code": null,
"e": 3486,
"s": 3445,
"text": "Scrape user reviews for Google Play apps"
},
{
"code": null,
"e": 3516,
"s": 3486,
"text": "Save the dataset to CSV files"
},
{
"code": null,
"e": 3640,
"s": 3516,
"text": "Next, we’re going to use the reviews for sentiment analysis with BERT. But first, we’ll have to do some text preprocessing!"
},
{
"code": null,
"e": 3671,
"s": 3640,
"text": "Google Play Scraper for Python"
}
] |
PPC - Introduction | We have the Internet that provides a huge platform for advertising products and services online. Advertisers around the world have shown a keen interest in making good use of the Internet that is omnipresent these days to market various products and speed up their business activities by reaching out to numerous users.
You might be aware of the conventional methods of push marketing that involves the use of brochures, television ads, radio ads, banners, bills, balloons, etc. where people are driven to hear, listen, and view the product or service they can get.
Quite contrary to the traditional model, the recent methods of internet marketing involve innovative techniques to catch more eyeballs and pull online traffic to visit, listen, view, or buy a product or a service that is on offer. It is done through a model that is now being widely regarded as Pay Per Click (PPC). It is a successful model for internet advertising that directs online traffic to particular websites, where the advertisers pay the publishers a certain amount when their ad is clicked.
Here, in this introductory chapter, we will provide an overview of PPC as a concept and explain the role of its entities involved in the entire workflow of PPC advertising.
PPC stands for Pay Per Click. It is an internet marketing model where the advertisers use the publishers’ website to market their products or services through ads. The publisher gets paid by the particular advertisers when a user clicks on their ads. It is a pull-type internet marketing of buying user visits to a site.
One of the most popular forms of PPC marketing is Search Engine Advertising (SEA). It allows advertisers to bid for placement of ads in the search engine’s sponsored link, when a user searches for a keyword that is relevant to a product or a service.
Whenever a user clicks on an ad, the link directs the user to the product’s website. At the same time, the product or service provider needs to pay some amount to the search engine, such as Google.
Behind every successful PPC campaign lies a catchy ad that can attract the attention of online users. Advertisers focus on the following aspects while creating an online ad:
Research for effective keywords related to a product or a service
Choose the right keywords
Group the keywords relevantly
Arrange the keywords to create an advertise
More often than not, the ads that are useful and relevant are charged less fees per click by the search engines. This is rewarding for the advertisers, as they get more business in exchange of minimal fees.
Google AdWords is an example of a popular advertising system. It facilitates businesses to publish ads on Google’s search engine.
The following entities are involved in PPC Advertising:
Product or Service Seller
PPC Advertiser
Landing Page Provider
Landing Page
Viewer or the Visitor
Take a close look at the illustrations below that depict the general roles of the entities involved in PPC advertising:
A product/service seller contacts advertisers for PPC based Ad programs.
PPC Advertiser creates Ads and provides landing pages for Ads.
Users click the Ads and visit the landing pages.
PPC – Bird's eye view
The workflow of a PPC ad is as follows:
First of all, the advertiser creates an online account and loads her account with some money – say Rs 5000. Note that some organizations allocate their PPC budgets in hundreds, thousands, or even millions of rupees per month.
First of all, the advertiser creates an online account and loads her account with some money – say Rs 5000. Note that some organizations allocate their PPC budgets in hundreds, thousands, or even millions of rupees per month.
The advertiser creates a small text ad. In some cases, a PPC ad can include images.
The advertiser creates a small text ad. In some cases, a PPC ad can include images.
The advertiser specifies a list of keywords associated with the ad.
The advertiser specifies a list of keywords associated with the ad.
The advertiser determines how much she is ready to pay each time someone clicks on the ad.
The advertiser determines how much she is ready to pay each time someone clicks on the ad.
On the buyer’s side, a user visits the search engine – say Google.com, enters one of the keywords or keyword phrases - say “Kindle Paper white” and clicks the Search button.
On the buyer’s side, a user visits the search engine – say Google.com, enters one of the keywords or keyword phrases - say “Kindle Paper white” and clicks the Search button.
The search engine finds the matching ads and places them on the results page.
The search engine finds the matching ads and places them on the results page.
If a user clicks on the ad, she is taken to the advertiser's website, and the advertiser is charged for the click.
If a user clicks on the ad, she is taken to the advertiser's website, and the advertiser is charged for the click.
PPC ads have been in existence over a decade now. The term PPC came into existence during the year 1990 when organizations started conducting their business on the Internet. One of the companies that pioneered the concept was goto.com. Yahoo took it over in 2003.
When Google launched its AdWords solution for PPC marketing, heavy activities started in the domain of PPC. In addition to Google, a number of search engines such as Yahoo, Bing, 7Search, ABCSearch, and Findology provide PPC ad hosting.
A compelling PPC ad has the following properties:
It is a part of a closely-knit ad-groups.
It can address the desired search queried by the users.
It takes the user to an appropriate landing page.
It drives the users to click on it and explore.
The basic formula of calculating PPC is:
Pay per click ($) = Advertising cost ($) ÷ Number of ad clicks
PPC helps in branding and creating leads as well, both in parallel. PPC provides quick results in contrast to SEO results that are equally important but may take months or even years to materialize.
Quick Actions - PPC gives immense traffic, quick results, and more hype branding in a short span of time.
Quick Actions - PPC gives immense traffic, quick results, and more hype branding in a short span of time.
Negligible Initial Investment - Search engines do not charge fees to insert a PPC ad or to set up an account. The user pays only when someone actually clicks on his ad.
Negligible Initial Investment - Search engines do not charge fees to insert a PPC ad or to set up an account. The user pays only when someone actually clicks on his ad.
Business Gets Noticed Globally - A business can get global recognition, even if it has a small local setup.
Business Gets Noticed Globally - A business can get global recognition, even if it has a small local setup.
Instant Results - As compared to SEO methods, PPC ads can deliver faster response, if quality ads are posted.
Instant Results - As compared to SEO methods, PPC ads can deliver faster response, if quality ads are posted.
20 Lectures
3.5 hours
Asif Hussain
19 Lectures
58 mins
Zach Miller
12 Lectures
1.5 hours
Alan Sharpe
13 Lectures
1.5 hours
Alan Sharpe
16 Lectures
1.5 hours
Global FinTech Academy
28 Lectures
1.5 hours
Gautham Vijayan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1774,
"s": 1454,
"text": "We have the Internet that provides a huge platform for advertising products and services online. Advertisers around the world have shown a keen interest in making good use of the Internet that is omnipresent these days to market various products and speed up their business activities by reaching out to numerous users."
},
{
"code": null,
"e": 2020,
"s": 1774,
"text": "You might be aware of the conventional methods of push marketing that involves the use of brochures, television ads, radio ads, banners, bills, balloons, etc. where people are driven to hear, listen, and view the product or service they can get."
},
{
"code": null,
"e": 2522,
"s": 2020,
"text": "Quite contrary to the traditional model, the recent methods of internet marketing involve innovative techniques to catch more eyeballs and pull online traffic to visit, listen, view, or buy a product or a service that is on offer. It is done through a model that is now being widely regarded as Pay Per Click (PPC). It is a successful model for internet advertising that directs online traffic to particular websites, where the advertisers pay the publishers a certain amount when their ad is clicked."
},
{
"code": null,
"e": 2695,
"s": 2522,
"text": "Here, in this introductory chapter, we will provide an overview of PPC as a concept and explain the role of its entities involved in the entire workflow of PPC advertising."
},
{
"code": null,
"e": 3016,
"s": 2695,
"text": "PPC stands for Pay Per Click. It is an internet marketing model where the advertisers use the publishers’ website to market their products or services through ads. The publisher gets paid by the particular advertisers when a user clicks on their ads. It is a pull-type internet marketing of buying user visits to a site."
},
{
"code": null,
"e": 3267,
"s": 3016,
"text": "One of the most popular forms of PPC marketing is Search Engine Advertising (SEA). It allows advertisers to bid for placement of ads in the search engine’s sponsored link, when a user searches for a keyword that is relevant to a product or a service."
},
{
"code": null,
"e": 3465,
"s": 3267,
"text": "Whenever a user clicks on an ad, the link directs the user to the product’s website. At the same time, the product or service provider needs to pay some amount to the search engine, such as Google."
},
{
"code": null,
"e": 3639,
"s": 3465,
"text": "Behind every successful PPC campaign lies a catchy ad that can attract the attention of online users. Advertisers focus on the following aspects while creating an online ad:"
},
{
"code": null,
"e": 3705,
"s": 3639,
"text": "Research for effective keywords related to a product or a service"
},
{
"code": null,
"e": 3731,
"s": 3705,
"text": "Choose the right keywords"
},
{
"code": null,
"e": 3761,
"s": 3731,
"text": "Group the keywords relevantly"
},
{
"code": null,
"e": 3805,
"s": 3761,
"text": "Arrange the keywords to create an advertise"
},
{
"code": null,
"e": 4012,
"s": 3805,
"text": "More often than not, the ads that are useful and relevant are charged less fees per click by the search engines. This is rewarding for the advertisers, as they get more business in exchange of minimal fees."
},
{
"code": null,
"e": 4142,
"s": 4012,
"text": "Google AdWords is an example of a popular advertising system. It facilitates businesses to publish ads on Google’s search engine."
},
{
"code": null,
"e": 4198,
"s": 4142,
"text": "The following entities are involved in PPC Advertising:"
},
{
"code": null,
"e": 4224,
"s": 4198,
"text": "Product or Service Seller"
},
{
"code": null,
"e": 4239,
"s": 4224,
"text": "PPC Advertiser"
},
{
"code": null,
"e": 4261,
"s": 4239,
"text": "Landing Page Provider"
},
{
"code": null,
"e": 4274,
"s": 4261,
"text": "Landing Page"
},
{
"code": null,
"e": 4296,
"s": 4274,
"text": "Viewer or the Visitor"
},
{
"code": null,
"e": 4416,
"s": 4296,
"text": "Take a close look at the illustrations below that depict the general roles of the entities involved in PPC advertising:"
},
{
"code": null,
"e": 4489,
"s": 4416,
"text": "A product/service seller contacts advertisers for PPC based Ad programs."
},
{
"code": null,
"e": 4552,
"s": 4489,
"text": "PPC Advertiser creates Ads and provides landing pages for Ads."
},
{
"code": null,
"e": 4601,
"s": 4552,
"text": "Users click the Ads and visit the landing pages."
},
{
"code": null,
"e": 4623,
"s": 4601,
"text": "PPC – Bird's eye view"
},
{
"code": null,
"e": 4663,
"s": 4623,
"text": "The workflow of a PPC ad is as follows:"
},
{
"code": null,
"e": 4889,
"s": 4663,
"text": "First of all, the advertiser creates an online account and loads her account with some money – say Rs 5000. Note that some organizations allocate their PPC budgets in hundreds, thousands, or even millions of rupees per month."
},
{
"code": null,
"e": 5115,
"s": 4889,
"text": "First of all, the advertiser creates an online account and loads her account with some money – say Rs 5000. Note that some organizations allocate their PPC budgets in hundreds, thousands, or even millions of rupees per month."
},
{
"code": null,
"e": 5199,
"s": 5115,
"text": "The advertiser creates a small text ad. In some cases, a PPC ad can include images."
},
{
"code": null,
"e": 5283,
"s": 5199,
"text": "The advertiser creates a small text ad. In some cases, a PPC ad can include images."
},
{
"code": null,
"e": 5351,
"s": 5283,
"text": "The advertiser specifies a list of keywords associated with the ad."
},
{
"code": null,
"e": 5419,
"s": 5351,
"text": "The advertiser specifies a list of keywords associated with the ad."
},
{
"code": null,
"e": 5510,
"s": 5419,
"text": "The advertiser determines how much she is ready to pay each time someone clicks on the ad."
},
{
"code": null,
"e": 5601,
"s": 5510,
"text": "The advertiser determines how much she is ready to pay each time someone clicks on the ad."
},
{
"code": null,
"e": 5775,
"s": 5601,
"text": "On the buyer’s side, a user visits the search engine – say Google.com, enters one of the keywords or keyword phrases - say “Kindle Paper white” and clicks the Search button."
},
{
"code": null,
"e": 5949,
"s": 5775,
"text": "On the buyer’s side, a user visits the search engine – say Google.com, enters one of the keywords or keyword phrases - say “Kindle Paper white” and clicks the Search button."
},
{
"code": null,
"e": 6027,
"s": 5949,
"text": "The search engine finds the matching ads and places them on the results page."
},
{
"code": null,
"e": 6105,
"s": 6027,
"text": "The search engine finds the matching ads and places them on the results page."
},
{
"code": null,
"e": 6220,
"s": 6105,
"text": "If a user clicks on the ad, she is taken to the advertiser's website, and the advertiser is charged for the click."
},
{
"code": null,
"e": 6335,
"s": 6220,
"text": "If a user clicks on the ad, she is taken to the advertiser's website, and the advertiser is charged for the click."
},
{
"code": null,
"e": 6599,
"s": 6335,
"text": "PPC ads have been in existence over a decade now. The term PPC came into existence during the year 1990 when organizations started conducting their business on the Internet. One of the companies that pioneered the concept was goto.com. Yahoo took it over in 2003."
},
{
"code": null,
"e": 6836,
"s": 6599,
"text": "When Google launched its AdWords solution for PPC marketing, heavy activities started in the domain of PPC. In addition to Google, a number of search engines such as Yahoo, Bing, 7Search, ABCSearch, and Findology provide PPC ad hosting."
},
{
"code": null,
"e": 6886,
"s": 6836,
"text": "A compelling PPC ad has the following properties:"
},
{
"code": null,
"e": 6928,
"s": 6886,
"text": "It is a part of a closely-knit ad-groups."
},
{
"code": null,
"e": 6984,
"s": 6928,
"text": "It can address the desired search queried by the users."
},
{
"code": null,
"e": 7034,
"s": 6984,
"text": "It takes the user to an appropriate landing page."
},
{
"code": null,
"e": 7082,
"s": 7034,
"text": "It drives the users to click on it and explore."
},
{
"code": null,
"e": 7123,
"s": 7082,
"text": "The basic formula of calculating PPC is:"
},
{
"code": null,
"e": 7187,
"s": 7123,
"text": "Pay per click ($) = Advertising cost ($) ÷ Number of ad clicks\n"
},
{
"code": null,
"e": 7386,
"s": 7187,
"text": "PPC helps in branding and creating leads as well, both in parallel. PPC provides quick results in contrast to SEO results that are equally important but may take months or even years to materialize."
},
{
"code": null,
"e": 7492,
"s": 7386,
"text": "Quick Actions - PPC gives immense traffic, quick results, and more hype branding in a short span of time."
},
{
"code": null,
"e": 7598,
"s": 7492,
"text": "Quick Actions - PPC gives immense traffic, quick results, and more hype branding in a short span of time."
},
{
"code": null,
"e": 7767,
"s": 7598,
"text": "Negligible Initial Investment - Search engines do not charge fees to insert a PPC ad or to set up an account. The user pays only when someone actually clicks on his ad."
},
{
"code": null,
"e": 7936,
"s": 7767,
"text": "Negligible Initial Investment - Search engines do not charge fees to insert a PPC ad or to set up an account. The user pays only when someone actually clicks on his ad."
},
{
"code": null,
"e": 8044,
"s": 7936,
"text": "Business Gets Noticed Globally - A business can get global recognition, even if it has a small local setup."
},
{
"code": null,
"e": 8152,
"s": 8044,
"text": "Business Gets Noticed Globally - A business can get global recognition, even if it has a small local setup."
},
{
"code": null,
"e": 8262,
"s": 8152,
"text": "Instant Results - As compared to SEO methods, PPC ads can deliver faster response, if quality ads are posted."
},
{
"code": null,
"e": 8372,
"s": 8262,
"text": "Instant Results - As compared to SEO methods, PPC ads can deliver faster response, if quality ads are posted."
},
{
"code": null,
"e": 8407,
"s": 8372,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8421,
"s": 8407,
"text": " Asif Hussain"
},
{
"code": null,
"e": 8453,
"s": 8421,
"text": "\n 19 Lectures \n 58 mins\n"
},
{
"code": null,
"e": 8466,
"s": 8453,
"text": " Zach Miller"
},
{
"code": null,
"e": 8501,
"s": 8466,
"text": "\n 12 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8514,
"s": 8501,
"text": " Alan Sharpe"
},
{
"code": null,
"e": 8549,
"s": 8514,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8562,
"s": 8549,
"text": " Alan Sharpe"
},
{
"code": null,
"e": 8597,
"s": 8562,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8621,
"s": 8597,
"text": " Global FinTech Academy"
},
{
"code": null,
"e": 8656,
"s": 8621,
"text": "\n 28 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8673,
"s": 8656,
"text": " Gautham Vijayan"
},
{
"code": null,
"e": 8680,
"s": 8673,
"text": " Print"
},
{
"code": null,
"e": 8691,
"s": 8680,
"text": " Add Notes"
}
] |
The tale of missing values in Python | by HAFEEZ JIMOH | Towards Data Science | Imagine buying a chocolate box with 60 chocolate samples where there are 15 different unique shapes of chocolates. Unfortunately, on opening the chocolate box, you find two empty segments of chocolate. Can you accurately find a way out off handling the missing chocolate segments. Should one just pretend as if the missing chocolate isn’t missing.? Should one return the chocolate box to the seller? Should one go and buy two other chocolates to fill the missing portion. Or can one just predict the shape of the missing chocolate based on previous experience of arrangement and shapes of chocolate in the box and then buy a chocolate of such predicted shape.
The above and some others are mind throbbing questions a data scientist need to answer in order to handle missing data correctly. Hence, this write-up aims to elucidate on several approaches available for handling missing values in our data exploration journey.
Data in real world are rarely clean and homogeneous. Data can either be missing during data extraction or collection. Missing values need to be handled because they reduce the quality for any of our performance metric. It can also lead to wrong prediction or classification and can also cause a high bias for any given model being used.
Depending on data sources, missing data are identified differently. Pandas always identify missing values as NaN. However, unless the data has been pre-processed to a degree that an analyst will encounter missing values as NaN. Missing values can appear as a question mark (?) or a zero (0) or minus one (-1) or a blank. As a result, it is always important that a data scientist always perform exploratory data analysis(EDA) first before writing any machine learning algorithm. EDA is simply a litmus for understanding and knowing the behaviour of our data.
Exploratory data analysis can never be the whole story, but nothing else can serve as the foundation stone. — John Tukey
For example, if we have a data set that should be used to to predict average salary based on years of experience and in our years of experience column, a value of -1 is indiscriminately found, then we can flag such value as a missing value. Else, it could be that we have a continuous variable feature (observed or independent variable) of height/weight/age and our EDA shows us a value of 0 or -1 or values less than 1 for some observation; then one can conclude that such value is a missing value. Missing values could also be blank. This will usually occur when there is no observed measurement for such feature either by respondents or instruments used for capturing such data.
There are several options for handling missing values each with its own PROS and CONS. However, the choice of what should be done is largely dependent on the nature of our data and the missing values. Below is a summary highlight of several options we have for handling missing values.
DROP MISSING VALUESFILL MISSING VALUES WITH TEST STATISTICPREDICT MISSING VALUE WITH A MACHINE LEARNING ALGORITHM
DROP MISSING VALUES
FILL MISSING VALUES WITH TEST STATISTIC
PREDICT MISSING VALUE WITH A MACHINE LEARNING ALGORITHM
Below is a few list of commands to detect missing values with EDA.
data_name.info()
This will tell us the total number of non null observations present including the total number of entries. Once number of entries isn’t equal to number of non null observations, we can begin to suspect missing values.
data_name.describe()
This will display a summary statistics of all observed features and labels. The most important to note here is the min value. Once we see -1/0 in an observation like age/height/weight, then we have been able to detect missing value.
data_name.head(x)
This will output the first x rows of our data. Viewing this will give one a quick view on the presence of NaN/-1/0/blank/? among others.
data_name.isnull().sum()
This will tell us the total number of NaN in or data.
If the missing value isn’t identified as NaN , then we have to first convert or replace such non NaN entry with a NaN.
data_name[‘column_name’].replace(0, np.nan, inplace= True)
This will replace values of zero with NaN in the column named column_name of our data_name .
This is the fastest and easiest step to handle missing values. However, it is not generally advised. This method reduces the quality of our model as it reduces sample size because it works by deleting all other observations where any of the variable is missing. The process can be done by:
data_name.dropna()
The code snippet shows the danger of dropping missing values.
It will be observed that of 891 entries will be reduced to 183 just by dropping NaN values.!!! Dropping is only advised to be used if missing values are few (say 0.01–0.5% of our data). Percent is just a rule of thumb.
This is the most common method of handling missing values. This is a process whereby missing values are replaced with a test statistic like mean, median or mode of the particular feature the missing value belongs to. One can also specify a forward-fill or back-fill to propagate the next values backward or previous value forward.
Filling missing values with a test statistic
#Age is a column name for our train datamean_value=train['Age'].mean()train['Age']=train['Age'].fillna(mean_value)#this will replace all NaN values with the mean of the non null values#For Medianmeadian_value=train['Age'].median()train['Age']=train['Age'].fillna(median_value)
Alternative way of filling missing value with test statistic is by using our Imputer method found in sklearn.preprocessing.
In [1]: from sklearn.preprocessing import ImputerIn [2]: imp = Imputer(missing_values='NaN', strategy='mean', axis=0)In [3]: imp.fit(train)In [4]: train= imp.transform(train)#This will look for all columns where we have NaN value and replace the NaN value with specified test statistic.#for mode we specify strategy='most_frequent'
For Back-fill or forward-fill to propagate next or previous values respectively:
#for back fill train.fillna(method='bfill')#for forward-filltrain.fillna(method=''ffill)#one can also specify an axis to propagate (1 is for rows and 0 is for columns)train.fillna(method='bfill', axis=1)
Please note that if a previous or next value isn’t available or rather if it is also a NaN value, then, the NaN remains even after back-filling or forward-filling.
Also, the disadvantage of using mean is that the mean is greatly affected by outliers in our data. As a result, if outliers are present in our data, then median will be the best out of the box tool to use.
Data pipelines allow one to transform data from one representation to another through a series of steps. Pipelines allow one to apply and chain intermediate steps of transform to our data. For example, one can fill missing values, pass the output to cross validation and grid search and then fit the model in series of steps chained together where the output of one is the input to another.
You can learn more about pipelines here.
This is an example of a pipeline that imputes data with most frequent value of each column, and then fit to a logistic regression.
from sklearn.pipeline import Pipelinefrom sklearn.preprocessing import Imputerimp = Imputer(missing_values='NaN', strategy='mean', axis=0)logreg = LogisticRegression()steps = [('imputation', imp),('logistic_regression', logreg)]pipeline = Pipeline(steps)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)pipeline.fit(X_train, y_train)y_pred = pipeline.predict(X_test)pipeline.score(X_test, y_test)
This is by far one of the best and most efficient method for handling missing data. Depending on the class of data that is missing, one can either use a regression model or classification to predict missing data. This works by turning missing features to labels themselves and now using columns without missing values to predict columns with missing values
The process goes thus:
Call the variable where you have missing values as y.
Split data into sets with missing values and without missing values, name the missing set X_text and the one without missing values X_train and take y (variable or feature where there is missing values) off the second set, naming it y_train.
Use one of classification methods to predict y_pred.
Add it to X_test as your y_test column. Then combine sets together.
For a beginner or newbie in machine learning, this approach might seem more difficult. The only drawback to this approach is that if there is no correlation between attributes with missing data and other attributes in the data set, then the model will be bias for predicting missing values.
Apart from using isnull() to check for missing values as done above, one can use assert to programmatically check that no missing or unexpected ‘0’ value is present. This gives confidence that code is running properly.
The following and some other boolean operations can be carried out on assert. Assert will return nothing is the assert statement is true and will return an AssertionError if statement is false.
#fill null values with 0df=train.fillna(value=0)#assert that there are no missing valuesassert pd.notnull(df).all().all()#or for a particular column in dfassert df.column_name.notall().all()#assert all values are greater than 0assert (df >=0).all().all()#assert no entry in a column is equal to 0assert (df['column_name']!=0).all().all()
In conclusion, the approach to deal with missing values is heavily dependent on the nature of such data. Therefore, the more different types of data you work with the better the experience you have with different solutions for different data classes.
Thank you for reading and please do drop your comments and do not forget to share.
P.S: Watch out for my next article that discusses various alternatives for handling categorical variable
*all images are from web** | [
{
"code": null,
"e": 831,
"s": 171,
"text": "Imagine buying a chocolate box with 60 chocolate samples where there are 15 different unique shapes of chocolates. Unfortunately, on opening the chocolate box, you find two empty segments of chocolate. Can you accurately find a way out off handling the missing chocolate segments. Should one just pretend as if the missing chocolate isn’t missing.? Should one return the chocolate box to the seller? Should one go and buy two other chocolates to fill the missing portion. Or can one just predict the shape of the missing chocolate based on previous experience of arrangement and shapes of chocolate in the box and then buy a chocolate of such predicted shape."
},
{
"code": null,
"e": 1093,
"s": 831,
"text": "The above and some others are mind throbbing questions a data scientist need to answer in order to handle missing data correctly. Hence, this write-up aims to elucidate on several approaches available for handling missing values in our data exploration journey."
},
{
"code": null,
"e": 1430,
"s": 1093,
"text": "Data in real world are rarely clean and homogeneous. Data can either be missing during data extraction or collection. Missing values need to be handled because they reduce the quality for any of our performance metric. It can also lead to wrong prediction or classification and can also cause a high bias for any given model being used."
},
{
"code": null,
"e": 1988,
"s": 1430,
"text": "Depending on data sources, missing data are identified differently. Pandas always identify missing values as NaN. However, unless the data has been pre-processed to a degree that an analyst will encounter missing values as NaN. Missing values can appear as a question mark (?) or a zero (0) or minus one (-1) or a blank. As a result, it is always important that a data scientist always perform exploratory data analysis(EDA) first before writing any machine learning algorithm. EDA is simply a litmus for understanding and knowing the behaviour of our data."
},
{
"code": null,
"e": 2109,
"s": 1988,
"text": "Exploratory data analysis can never be the whole story, but nothing else can serve as the foundation stone. — John Tukey"
},
{
"code": null,
"e": 2791,
"s": 2109,
"text": "For example, if we have a data set that should be used to to predict average salary based on years of experience and in our years of experience column, a value of -1 is indiscriminately found, then we can flag such value as a missing value. Else, it could be that we have a continuous variable feature (observed or independent variable) of height/weight/age and our EDA shows us a value of 0 or -1 or values less than 1 for some observation; then one can conclude that such value is a missing value. Missing values could also be blank. This will usually occur when there is no observed measurement for such feature either by respondents or instruments used for capturing such data."
},
{
"code": null,
"e": 3077,
"s": 2791,
"text": "There are several options for handling missing values each with its own PROS and CONS. However, the choice of what should be done is largely dependent on the nature of our data and the missing values. Below is a summary highlight of several options we have for handling missing values."
},
{
"code": null,
"e": 3191,
"s": 3077,
"text": "DROP MISSING VALUESFILL MISSING VALUES WITH TEST STATISTICPREDICT MISSING VALUE WITH A MACHINE LEARNING ALGORITHM"
},
{
"code": null,
"e": 3211,
"s": 3191,
"text": "DROP MISSING VALUES"
},
{
"code": null,
"e": 3251,
"s": 3211,
"text": "FILL MISSING VALUES WITH TEST STATISTIC"
},
{
"code": null,
"e": 3307,
"s": 3251,
"text": "PREDICT MISSING VALUE WITH A MACHINE LEARNING ALGORITHM"
},
{
"code": null,
"e": 3374,
"s": 3307,
"text": "Below is a few list of commands to detect missing values with EDA."
},
{
"code": null,
"e": 3392,
"s": 3374,
"text": "data_name.info() "
},
{
"code": null,
"e": 3610,
"s": 3392,
"text": "This will tell us the total number of non null observations present including the total number of entries. Once number of entries isn’t equal to number of non null observations, we can begin to suspect missing values."
},
{
"code": null,
"e": 3631,
"s": 3610,
"text": "data_name.describe()"
},
{
"code": null,
"e": 3864,
"s": 3631,
"text": "This will display a summary statistics of all observed features and labels. The most important to note here is the min value. Once we see -1/0 in an observation like age/height/weight, then we have been able to detect missing value."
},
{
"code": null,
"e": 3882,
"s": 3864,
"text": "data_name.head(x)"
},
{
"code": null,
"e": 4019,
"s": 3882,
"text": "This will output the first x rows of our data. Viewing this will give one a quick view on the presence of NaN/-1/0/blank/? among others."
},
{
"code": null,
"e": 4044,
"s": 4019,
"text": "data_name.isnull().sum()"
},
{
"code": null,
"e": 4098,
"s": 4044,
"text": "This will tell us the total number of NaN in or data."
},
{
"code": null,
"e": 4217,
"s": 4098,
"text": "If the missing value isn’t identified as NaN , then we have to first convert or replace such non NaN entry with a NaN."
},
{
"code": null,
"e": 4276,
"s": 4217,
"text": "data_name[‘column_name’].replace(0, np.nan, inplace= True)"
},
{
"code": null,
"e": 4369,
"s": 4276,
"text": "This will replace values of zero with NaN in the column named column_name of our data_name ."
},
{
"code": null,
"e": 4659,
"s": 4369,
"text": "This is the fastest and easiest step to handle missing values. However, it is not generally advised. This method reduces the quality of our model as it reduces sample size because it works by deleting all other observations where any of the variable is missing. The process can be done by:"
},
{
"code": null,
"e": 4678,
"s": 4659,
"text": "data_name.dropna()"
},
{
"code": null,
"e": 4740,
"s": 4678,
"text": "The code snippet shows the danger of dropping missing values."
},
{
"code": null,
"e": 4959,
"s": 4740,
"text": "It will be observed that of 891 entries will be reduced to 183 just by dropping NaN values.!!! Dropping is only advised to be used if missing values are few (say 0.01–0.5% of our data). Percent is just a rule of thumb."
},
{
"code": null,
"e": 5290,
"s": 4959,
"text": "This is the most common method of handling missing values. This is a process whereby missing values are replaced with a test statistic like mean, median or mode of the particular feature the missing value belongs to. One can also specify a forward-fill or back-fill to propagate the next values backward or previous value forward."
},
{
"code": null,
"e": 5335,
"s": 5290,
"text": "Filling missing values with a test statistic"
},
{
"code": null,
"e": 5612,
"s": 5335,
"text": "#Age is a column name for our train datamean_value=train['Age'].mean()train['Age']=train['Age'].fillna(mean_value)#this will replace all NaN values with the mean of the non null values#For Medianmeadian_value=train['Age'].median()train['Age']=train['Age'].fillna(median_value)"
},
{
"code": null,
"e": 5736,
"s": 5612,
"text": "Alternative way of filling missing value with test statistic is by using our Imputer method found in sklearn.preprocessing."
},
{
"code": null,
"e": 6068,
"s": 5736,
"text": "In [1]: from sklearn.preprocessing import ImputerIn [2]: imp = Imputer(missing_values='NaN', strategy='mean', axis=0)In [3]: imp.fit(train)In [4]: train= imp.transform(train)#This will look for all columns where we have NaN value and replace the NaN value with specified test statistic.#for mode we specify strategy='most_frequent'"
},
{
"code": null,
"e": 6149,
"s": 6068,
"text": "For Back-fill or forward-fill to propagate next or previous values respectively:"
},
{
"code": null,
"e": 6353,
"s": 6149,
"text": "#for back fill train.fillna(method='bfill')#for forward-filltrain.fillna(method=''ffill)#one can also specify an axis to propagate (1 is for rows and 0 is for columns)train.fillna(method='bfill', axis=1)"
},
{
"code": null,
"e": 6517,
"s": 6353,
"text": "Please note that if a previous or next value isn’t available or rather if it is also a NaN value, then, the NaN remains even after back-filling or forward-filling."
},
{
"code": null,
"e": 6723,
"s": 6517,
"text": "Also, the disadvantage of using mean is that the mean is greatly affected by outliers in our data. As a result, if outliers are present in our data, then median will be the best out of the box tool to use."
},
{
"code": null,
"e": 7114,
"s": 6723,
"text": "Data pipelines allow one to transform data from one representation to another through a series of steps. Pipelines allow one to apply and chain intermediate steps of transform to our data. For example, one can fill missing values, pass the output to cross validation and grid search and then fit the model in series of steps chained together where the output of one is the input to another."
},
{
"code": null,
"e": 7155,
"s": 7114,
"text": "You can learn more about pipelines here."
},
{
"code": null,
"e": 7286,
"s": 7155,
"text": "This is an example of a pipeline that imputes data with most frequent value of each column, and then fit to a logistic regression."
},
{
"code": null,
"e": 7755,
"s": 7286,
"text": "from sklearn.pipeline import Pipelinefrom sklearn.preprocessing import Imputerimp = Imputer(missing_values='NaN', strategy='mean', axis=0)logreg = LogisticRegression()steps = [('imputation', imp),('logistic_regression', logreg)]pipeline = Pipeline(steps)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)pipeline.fit(X_train, y_train)y_pred = pipeline.predict(X_test)pipeline.score(X_test, y_test)"
},
{
"code": null,
"e": 8112,
"s": 7755,
"text": "This is by far one of the best and most efficient method for handling missing data. Depending on the class of data that is missing, one can either use a regression model or classification to predict missing data. This works by turning missing features to labels themselves and now using columns without missing values to predict columns with missing values"
},
{
"code": null,
"e": 8135,
"s": 8112,
"text": "The process goes thus:"
},
{
"code": null,
"e": 8189,
"s": 8135,
"text": "Call the variable where you have missing values as y."
},
{
"code": null,
"e": 8431,
"s": 8189,
"text": "Split data into sets with missing values and without missing values, name the missing set X_text and the one without missing values X_train and take y (variable or feature where there is missing values) off the second set, naming it y_train."
},
{
"code": null,
"e": 8484,
"s": 8431,
"text": "Use one of classification methods to predict y_pred."
},
{
"code": null,
"e": 8552,
"s": 8484,
"text": "Add it to X_test as your y_test column. Then combine sets together."
},
{
"code": null,
"e": 8843,
"s": 8552,
"text": "For a beginner or newbie in machine learning, this approach might seem more difficult. The only drawback to this approach is that if there is no correlation between attributes with missing data and other attributes in the data set, then the model will be bias for predicting missing values."
},
{
"code": null,
"e": 9062,
"s": 8843,
"text": "Apart from using isnull() to check for missing values as done above, one can use assert to programmatically check that no missing or unexpected ‘0’ value is present. This gives confidence that code is running properly."
},
{
"code": null,
"e": 9256,
"s": 9062,
"text": "The following and some other boolean operations can be carried out on assert. Assert will return nothing is the assert statement is true and will return an AssertionError if statement is false."
},
{
"code": null,
"e": 9594,
"s": 9256,
"text": "#fill null values with 0df=train.fillna(value=0)#assert that there are no missing valuesassert pd.notnull(df).all().all()#or for a particular column in dfassert df.column_name.notall().all()#assert all values are greater than 0assert (df >=0).all().all()#assert no entry in a column is equal to 0assert (df['column_name']!=0).all().all()"
},
{
"code": null,
"e": 9845,
"s": 9594,
"text": "In conclusion, the approach to deal with missing values is heavily dependent on the nature of such data. Therefore, the more different types of data you work with the better the experience you have with different solutions for different data classes."
},
{
"code": null,
"e": 9928,
"s": 9845,
"text": "Thank you for reading and please do drop your comments and do not forget to share."
},
{
"code": null,
"e": 10033,
"s": 9928,
"text": "P.S: Watch out for my next article that discusses various alternatives for handling categorical variable"
}
] |
Quick Recommendation-Based Data Exploration with Lux | by Cornellius Yudha Wijaya | Towards Data Science | As a Data Scientist, data exploration, or EDA, is our everyday work and the thing we get paid to do. There is no other skill more important to a data scientist than the data exploration skill (in my opinion). While it is important, we know that the process is a hassle and sometimes a time-exhauster. Moreover, a lot of times, we do not know where to start exploring the data.
Take the example of the mpg dataset below:
import pandas as pdimport seaborn as snsmpg = sns.load_dataset('mpg')mpg.head()
Where do we start exploring data if we are not an expert in the car field, like me? In this case, we can try the recommender-based EDA using the lux package.
If you want to check out another open-source EDA package, you can check out my article here as well.
towardsdatascience.com
Anyway, let’s see how we can use the lux package to help us explore our data.
Lux is an open-source package in Python designed to help us explore data more intelligently with their recommendation. The package was aimed at people who did not know where to start when exploring the data.
Let’s start by installing the package.
pip install lux-api
When you have finished installing the package, we need to enable the lux widget in our jupyter notebook.
jupyter nbextension install --py luxwidgetjupyter nbextension enable --py luxwidget
Now, let’s try using the Lux package to explore our data. First, we need to import the package to automatically setting up the widget in our notebook.
import lux
Just like that, we already set up the Lux package to be integrated with the Pandas Data Frame. Next, let’s try to open any of our Data Frame; let’s try with the previously used mpg dataset.
With the Lux package, we can see a new button called “Toggle Pandas/Lux” we could press. Try to press that button.
Automatically, a set of visualization is created based on our dataset. in default, there are three visualization categories created; Correlation, Distribution, and Occurrence.
The Correlation tab comprised all the numerical relationships between two variables, which were visualized by the scatter plot. You can see the example in the above picture.
The Distribution tab shows a single numerical variable where the variables are visualized using a histogram plot. You can see the example in the below picture.
The Occurrence tab shows the count plot of the categorical variable. It shows each class frequency in the categorical variable, just like in the picture below.
In addition to data frame visualizations, we can specify in Lux the attributes and values we are interested in for Lux to guide our data exploration's potential next steps.
Ler’s say that I am interested in both ‘mpg’ and ‘horsepower’ attributes because I know it was related. We can specify it both in the Lux package to guide us with the .intent method, just like the line below.
mpg.intent = ['mpg', 'horsepower']
With the intent set to our data frame, the Lux package gives us the visualization recommendation. There are three different options we can see; Enhance, Filter, and Generalize.
The Enhance tab shows the visualization recommendation by adding additional variables to our current intent. Essentially it shows how another variable affecting the variables we are interested in. You can see the example in the above picture.
The Filter tab adds a filter to the current intent you have set; this is done while keeping the attributes (on the X and Y axes) fixed. The recommendation would show us the relationship between our variable filtered from another variable. You can see from the image below that the scatter plot is filtered by the model_year variable for each class the column has.
The generalize tab removes an attribute to display a more general trend, showing the attribute's distributions. The purpose is to focus on the current attribute we are interested in.
You could try a variable combination between numerical and categorical as well. Although the maximum variables for the intent, you can specify is three variables. Nevertheless, it is enough for you to explore the data easily.
If you want to separate one of the visualization charts into another variable, you could do that in Lux. Let’s take a look at the image below.
We only need to click on our intended chart from the image above until they show the tick mark. After that, click on the export button (the one that I gave a red circle). With this, we are already successfully exporting the chart.
So, where to access the chart? The exported chart is actually stored in our own data frame variable. Let’s try to access it then.
#The visualization is stored in the .exported attribute we could access any timevis = mpg.exported[0]vis
With that, we have already stored our plot to a different variable.
Lux is a recommendation-based system EDA to help us quickly get around our data. The package helps us by giving us all the possible data combinations and exploring the data based on our own intention.
If you are not subscribed as a Medium Member, please consider subscribing through my referral. | [
{
"code": null,
"e": 548,
"s": 171,
"text": "As a Data Scientist, data exploration, or EDA, is our everyday work and the thing we get paid to do. There is no other skill more important to a data scientist than the data exploration skill (in my opinion). While it is important, we know that the process is a hassle and sometimes a time-exhauster. Moreover, a lot of times, we do not know where to start exploring the data."
},
{
"code": null,
"e": 591,
"s": 548,
"text": "Take the example of the mpg dataset below:"
},
{
"code": null,
"e": 671,
"s": 591,
"text": "import pandas as pdimport seaborn as snsmpg = sns.load_dataset('mpg')mpg.head()"
},
{
"code": null,
"e": 829,
"s": 671,
"text": "Where do we start exploring data if we are not an expert in the car field, like me? In this case, we can try the recommender-based EDA using the lux package."
},
{
"code": null,
"e": 930,
"s": 829,
"text": "If you want to check out another open-source EDA package, you can check out my article here as well."
},
{
"code": null,
"e": 953,
"s": 930,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1031,
"s": 953,
"text": "Anyway, let’s see how we can use the lux package to help us explore our data."
},
{
"code": null,
"e": 1239,
"s": 1031,
"text": "Lux is an open-source package in Python designed to help us explore data more intelligently with their recommendation. The package was aimed at people who did not know where to start when exploring the data."
},
{
"code": null,
"e": 1278,
"s": 1239,
"text": "Let’s start by installing the package."
},
{
"code": null,
"e": 1298,
"s": 1278,
"text": "pip install lux-api"
},
{
"code": null,
"e": 1403,
"s": 1298,
"text": "When you have finished installing the package, we need to enable the lux widget in our jupyter notebook."
},
{
"code": null,
"e": 1487,
"s": 1403,
"text": "jupyter nbextension install --py luxwidgetjupyter nbextension enable --py luxwidget"
},
{
"code": null,
"e": 1638,
"s": 1487,
"text": "Now, let’s try using the Lux package to explore our data. First, we need to import the package to automatically setting up the widget in our notebook."
},
{
"code": null,
"e": 1649,
"s": 1638,
"text": "import lux"
},
{
"code": null,
"e": 1839,
"s": 1649,
"text": "Just like that, we already set up the Lux package to be integrated with the Pandas Data Frame. Next, let’s try to open any of our Data Frame; let’s try with the previously used mpg dataset."
},
{
"code": null,
"e": 1954,
"s": 1839,
"text": "With the Lux package, we can see a new button called “Toggle Pandas/Lux” we could press. Try to press that button."
},
{
"code": null,
"e": 2130,
"s": 1954,
"text": "Automatically, a set of visualization is created based on our dataset. in default, there are three visualization categories created; Correlation, Distribution, and Occurrence."
},
{
"code": null,
"e": 2304,
"s": 2130,
"text": "The Correlation tab comprised all the numerical relationships between two variables, which were visualized by the scatter plot. You can see the example in the above picture."
},
{
"code": null,
"e": 2464,
"s": 2304,
"text": "The Distribution tab shows a single numerical variable where the variables are visualized using a histogram plot. You can see the example in the below picture."
},
{
"code": null,
"e": 2624,
"s": 2464,
"text": "The Occurrence tab shows the count plot of the categorical variable. It shows each class frequency in the categorical variable, just like in the picture below."
},
{
"code": null,
"e": 2797,
"s": 2624,
"text": "In addition to data frame visualizations, we can specify in Lux the attributes and values we are interested in for Lux to guide our data exploration's potential next steps."
},
{
"code": null,
"e": 3006,
"s": 2797,
"text": "Ler’s say that I am interested in both ‘mpg’ and ‘horsepower’ attributes because I know it was related. We can specify it both in the Lux package to guide us with the .intent method, just like the line below."
},
{
"code": null,
"e": 3041,
"s": 3006,
"text": "mpg.intent = ['mpg', 'horsepower']"
},
{
"code": null,
"e": 3218,
"s": 3041,
"text": "With the intent set to our data frame, the Lux package gives us the visualization recommendation. There are three different options we can see; Enhance, Filter, and Generalize."
},
{
"code": null,
"e": 3461,
"s": 3218,
"text": "The Enhance tab shows the visualization recommendation by adding additional variables to our current intent. Essentially it shows how another variable affecting the variables we are interested in. You can see the example in the above picture."
},
{
"code": null,
"e": 3825,
"s": 3461,
"text": "The Filter tab adds a filter to the current intent you have set; this is done while keeping the attributes (on the X and Y axes) fixed. The recommendation would show us the relationship between our variable filtered from another variable. You can see from the image below that the scatter plot is filtered by the model_year variable for each class the column has."
},
{
"code": null,
"e": 4008,
"s": 3825,
"text": "The generalize tab removes an attribute to display a more general trend, showing the attribute's distributions. The purpose is to focus on the current attribute we are interested in."
},
{
"code": null,
"e": 4234,
"s": 4008,
"text": "You could try a variable combination between numerical and categorical as well. Although the maximum variables for the intent, you can specify is three variables. Nevertheless, it is enough for you to explore the data easily."
},
{
"code": null,
"e": 4377,
"s": 4234,
"text": "If you want to separate one of the visualization charts into another variable, you could do that in Lux. Let’s take a look at the image below."
},
{
"code": null,
"e": 4608,
"s": 4377,
"text": "We only need to click on our intended chart from the image above until they show the tick mark. After that, click on the export button (the one that I gave a red circle). With this, we are already successfully exporting the chart."
},
{
"code": null,
"e": 4738,
"s": 4608,
"text": "So, where to access the chart? The exported chart is actually stored in our own data frame variable. Let’s try to access it then."
},
{
"code": null,
"e": 4843,
"s": 4738,
"text": "#The visualization is stored in the .exported attribute we could access any timevis = mpg.exported[0]vis"
},
{
"code": null,
"e": 4911,
"s": 4843,
"text": "With that, we have already stored our plot to a different variable."
},
{
"code": null,
"e": 5112,
"s": 4911,
"text": "Lux is a recommendation-based system EDA to help us quickly get around our data. The package helps us by giving us all the possible data combinations and exploring the data based on our own intention."
}
] |
Bit Stuffing error detection technique using Java - GeeksforGeeks | 07 Oct, 2021
Prerequisites:1. Socket programming in Java2. Bit Stuffing3. Framing in data Link Layer
Data is encapsulated in frames in the data link layer and sent over the network. Bit Stuffing is a error detection technique.
The idea used is very simple. Each frame begins and ends with a special bit pattern “01111110” which is the flag byte. Whenever the sender’s data link layer encounters five consecutive 1s in the data, it automatically stuffs a 0 bit in the outgoing bit stream. The bit stuffing is analogous to byte stuffing, in which an escape byte is stuffed into the ongoing character stream before a flag byte in the data.
When the receiver sees five consecutive 1 bits, followed by a 0 bit, it automatically destuffs(deletes) the 0 bit. Bit stuffing is completely transparent to the network layer in both sender and receiver computers.
With bit stuffing, the boundary between the two frames can be unambiguously recognized by the flag pattern. Thus, if the receiver loses track of where it is, all it has to do is scan the input for flag sequences., since they can only occur at frame boundaries and never within the data.
Illustrative Examples
Sender Side(Client):
User enters a binary data as input.
Enter data:
0000001
Data is stuffed and sent to the receiver for unstuffing.
Here server is the receiver.
Data stuffed in client: 01111110000000101111110
Sending to server for unstuffing
Receiver Side(Server):
Receiver receives the stuffed data.
Stuffed data from client: 01111110000000101111110
Receiver has to unstuff the input data from sender and get the original data which
was given as input by the user.
Unstuffed data:
0000001
The code implementation of the above logic is given below.At Sender side(client side):
package bitstuffing;import java.io.*;import java.net.*;import java.util.Scanner;public class BitStuffingClient { public static void main(String[] args) throws IOException { // Opens a socket for connection Socket socket = new Socket("localhost", 6789); DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); // Scanner class object to take input Scanner sc = new Scanner(System.in); // Takes input of unstuffed data from user System.out.println("Enter data: "); String data = sc.nextLine(); int cnt = 0; String s = ""; for (int i = 0; i < data.length(); i++) { char ch = data.charAt(i); if (ch == '1') { // count number of consecutive 1's // in user's data cnt++; if (cnt < 5) s += ch; else { // add one '0' after 5 consecutive 1's s = s + ch + '0'; cnt = 0; } } else { s += ch; cnt = 0; } } // add flag byte in the beginning // and end of stuffed data s = "01111110" + s + "01111110"; System.out.println("Data stuffed in client: " + s); System.out.println("Sending to server for unstuffing"); dos.writeUTF(s); }}
At Receiver side(server side):
package bitstuffing;import java.io.*;import java.net.*;public class BitStuffingServer { public static void main(String[] args) throws IOException { ServerSocket skt = new ServerSocket(6789); // Used to block until a client connects to the server Socket socket = skt.accept(); DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); // Receiving the string from the client which // needs to be stuffed String s = dis.readUTF(); System.out.println("Stuffed data from client: " + s); System.out.println("Unstuffed data: "); int cnt = 0; // removal of stuffed bits: // start from 9th bit because the first 8 // bits are of the special pattern. for (int i = 8; i < s.length() - 8; i++) { char ch = s.charAt(i); if (ch == '1') { cnt++; System.out.print(ch); // After 5 consecutive 1's one stuffed bit //'0' is added. We need to remove that. if (cnt == 5) { i++; cnt = 0; } } else { // print unstuffed data System.out.print(ch); // we only need to maintain count // of consecutive 1's cnt = 0; } } System.out.println(); }}
The input and output are as shown above.
sagar0719kumar
Java-Networking
Computer Networks
Java
Java Programs
Java
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advanced Encryption Standard (AES)
Active and Passive attacks in Information Security
Cryptography and its Types
Multiple Access Protocols in Computer Network
Intrusion Detection System (IDS)
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 24119,
"s": 24091,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 24207,
"s": 24119,
"text": "Prerequisites:1. Socket programming in Java2. Bit Stuffing3. Framing in data Link Layer"
},
{
"code": null,
"e": 24333,
"s": 24207,
"text": "Data is encapsulated in frames in the data link layer and sent over the network. Bit Stuffing is a error detection technique."
},
{
"code": null,
"e": 24743,
"s": 24333,
"text": "The idea used is very simple. Each frame begins and ends with a special bit pattern “01111110” which is the flag byte. Whenever the sender’s data link layer encounters five consecutive 1s in the data, it automatically stuffs a 0 bit in the outgoing bit stream. The bit stuffing is analogous to byte stuffing, in which an escape byte is stuffed into the ongoing character stream before a flag byte in the data."
},
{
"code": null,
"e": 24957,
"s": 24743,
"text": "When the receiver sees five consecutive 1 bits, followed by a 0 bit, it automatically destuffs(deletes) the 0 bit. Bit stuffing is completely transparent to the network layer in both sender and receiver computers."
},
{
"code": null,
"e": 25244,
"s": 24957,
"text": "With bit stuffing, the boundary between the two frames can be unambiguously recognized by the flag pattern. Thus, if the receiver loses track of where it is, all it has to do is scan the input for flag sequences., since they can only occur at frame boundaries and never within the data."
},
{
"code": null,
"e": 25766,
"s": 25244,
"text": "Illustrative Examples\n\nSender Side(Client):\nUser enters a binary data as input.\nEnter data: \n0000001\nData is stuffed and sent to the receiver for unstuffing. \nHere server is the receiver.\nData stuffed in client: 01111110000000101111110\nSending to server for unstuffing\n\nReceiver Side(Server):\nReceiver receives the stuffed data. \nStuffed data from client: 01111110000000101111110\nReceiver has to unstuff the input data from sender and get the original data which \nwas given as input by the user.\nUnstuffed data: \n0000001\n"
},
{
"code": null,
"e": 25853,
"s": 25766,
"text": "The code implementation of the above logic is given below.At Sender side(client side):"
},
{
"code": "package bitstuffing;import java.io.*;import java.net.*;import java.util.Scanner;public class BitStuffingClient { public static void main(String[] args) throws IOException { // Opens a socket for connection Socket socket = new Socket(\"localhost\", 6789); DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); // Scanner class object to take input Scanner sc = new Scanner(System.in); // Takes input of unstuffed data from user System.out.println(\"Enter data: \"); String data = sc.nextLine(); int cnt = 0; String s = \"\"; for (int i = 0; i < data.length(); i++) { char ch = data.charAt(i); if (ch == '1') { // count number of consecutive 1's // in user's data cnt++; if (cnt < 5) s += ch; else { // add one '0' after 5 consecutive 1's s = s + ch + '0'; cnt = 0; } } else { s += ch; cnt = 0; } } // add flag byte in the beginning // and end of stuffed data s = \"01111110\" + s + \"01111110\"; System.out.println(\"Data stuffed in client: \" + s); System.out.println(\"Sending to server for unstuffing\"); dos.writeUTF(s); }}",
"e": 27362,
"s": 25853,
"text": null
},
{
"code": null,
"e": 27393,
"s": 27362,
"text": "At Receiver side(server side):"
},
{
"code": "package bitstuffing;import java.io.*;import java.net.*;public class BitStuffingServer { public static void main(String[] args) throws IOException { ServerSocket skt = new ServerSocket(6789); // Used to block until a client connects to the server Socket socket = skt.accept(); DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); // Receiving the string from the client which // needs to be stuffed String s = dis.readUTF(); System.out.println(\"Stuffed data from client: \" + s); System.out.println(\"Unstuffed data: \"); int cnt = 0; // removal of stuffed bits: // start from 9th bit because the first 8 // bits are of the special pattern. for (int i = 8; i < s.length() - 8; i++) { char ch = s.charAt(i); if (ch == '1') { cnt++; System.out.print(ch); // After 5 consecutive 1's one stuffed bit //'0' is added. We need to remove that. if (cnt == 5) { i++; cnt = 0; } } else { // print unstuffed data System.out.print(ch); // we only need to maintain count // of consecutive 1's cnt = 0; } } System.out.println(); }}",
"e": 28896,
"s": 27393,
"text": null
},
{
"code": null,
"e": 28937,
"s": 28896,
"text": "The input and output are as shown above."
},
{
"code": null,
"e": 28952,
"s": 28937,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 28968,
"s": 28952,
"text": "Java-Networking"
},
{
"code": null,
"e": 28986,
"s": 28968,
"text": "Computer Networks"
},
{
"code": null,
"e": 28991,
"s": 28986,
"text": "Java"
},
{
"code": null,
"e": 29005,
"s": 28991,
"text": "Java Programs"
},
{
"code": null,
"e": 29010,
"s": 29005,
"text": "Java"
},
{
"code": null,
"e": 29028,
"s": 29010,
"text": "Computer Networks"
},
{
"code": null,
"e": 29126,
"s": 29028,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29135,
"s": 29126,
"text": "Comments"
},
{
"code": null,
"e": 29148,
"s": 29135,
"text": "Old Comments"
},
{
"code": null,
"e": 29183,
"s": 29148,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 29234,
"s": 29183,
"text": "Active and Passive attacks in Information Security"
},
{
"code": null,
"e": 29261,
"s": 29234,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 29307,
"s": 29261,
"text": "Multiple Access Protocols in Computer Network"
},
{
"code": null,
"e": 29340,
"s": 29307,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 29355,
"s": 29340,
"text": "Arrays in Java"
},
{
"code": null,
"e": 29399,
"s": 29355,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 29421,
"s": 29399,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 29446,
"s": 29421,
"text": "Reverse a string in Java"
}
] |
How to create text-reveal effect using HTML and CSS ? - GeeksforGeeks | 02 Nov, 2021
Text-reveal is a type of effect in which all the alphabets of the text are revealed one by one in some animated way. There are uncountable ways to animate text for this effect. It up to your creativity that how you want the text to reveal. We will look at a basic and easy way to get started.Approach: The approach is to use keyframes to animate frames to slowly reveal the text frame-wise.HTML Code: In HTML, we have used <h1> tag wrapped inside a <div> tag.
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Text Reveal Animation</title></head> <body> <div class="geeks"> <h1>GeeksforGeeks</h1> </div></body> </html>
CSS Code: For CSS, follow these steps:
Step 1: First we have done some basic styling like providing a background color, aligning text to center, etc.
Step 2: Then use animation property with identifier named as animate.
Step 3: Now use keyframes to animate each frame and set different height and width for each frame.
Tip: You can change the value of height and width used in each frame to reveal text in a different way.
CSS
<style> body { background: green; } .geeks { width: 20%; top: 50%; position: absolute; left: 40%; border-bottom: 5px solid white; overflow: hidden; animation: animate 2s linear forwards; } .geeks h1 { color: white; } @keyframes animate { 0% { width: 0px; height: 0px; } 30% { width: 50px; height: 0px; } 60% { width: 50px; height: 80px; } }</style>
Complete Code: It is the combination of the above two section of codes.
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Text Reveal Animation</title> <style> body { background: green; } .geeks { width: 20%; top: 50%; position: absolute; left: 40%; border-bottom: 5px solid white; overflow: hidden; animation: animate 2s linear forwards; } .geeks h1 { color: white; } @keyframes animate { 0% { width: 0px; height: 0px; } 30% { width: 50px; height: 0px; } 60% { width: 50px; height: 80px; } } </style></head> <body> <div class="geeks"> <h1>GeeksforGeeks</h1> </div></body> </html>
Output:
One more animated method
HTML Code: The following code snippet creates HTML div element which contains the text for modification.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Collecting Data</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> </head><body class="container" style="margin-top: 50px; width: 50% height:auto; "> <div class="text-typing"> <p>Geeks For Geeks </p> </div></html>
CSS Code: For CSS, follow theses steps:
Step 1: First we have done some basic styling like providing a background color, aligning items to center, etc.
Step 2: Then use animation property with identifier named as text-typing p.
Step 3: Now use keyframes to animate from width 0 to 100%..
HTML
<style > body { margin:0px; height:100vh; display:flex; align-items:center; justify-content:center; background:#ddd;}.text-typing { padding:20px 30px; background:#f5f5f5; font-size:35px; font-family:monospace; border-radius:50px;}.text-typing p { margin:0px; white-space:nowrap; overflow:hidden; animation:typing 4s steps(22,end) forwards, blink 1s infinite;}@keyframes typing { 0% { width:0% } 100% { width:100% }}@keyframes blink { 0%,100% { border-right:2px solid transparent; } 50% { border-right:2px solid #222; }} </style>
Complete Code: It is the combination of the above two section of codes.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Collecting Data</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <style > body { margin:0px; height:100vh; display:flex; align-items:center; justify-content:center; background:#ddd;}.text-typing { padding:20px 30px; background:#f5f5f5; font-size:35px; font-family:monospace; border-radius:50px;}.text-typing p { margin:0px; white-space:nowrap; overflow:hidden; animation:typing 4s steps(22,end) forwards, blink 1s infinite;}@keyframes typing { 0% { width:0% } 100% { width:100% }}@keyframes blink { 0%,100% { border-right:2px solid transparent; } 50% { border-right:2px solid #222; }} </style></head><body class="container" style="margin-top: 50px; width: 50% height:auto; "> <div class="text-typing"> <p>Geeks For Geeks </p> </div></html>
Output
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
annianni
varshagumber28
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 24275,
"s": 24247,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 24737,
"s": 24275,
"text": "Text-reveal is a type of effect in which all the alphabets of the text are revealed one by one in some animated way. There are uncountable ways to animate text for this effect. It up to your creativity that how you want the text to reveal. We will look at a basic and easy way to get started.Approach: The approach is to use keyframes to animate frames to slowly reveal the text frame-wise.HTML Code: In HTML, we have used <h1> tag wrapped inside a <div> tag. "
},
{
"code": null,
"e": 24742,
"s": 24737,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Text Reveal Animation</title></head> <body> <div class=\"geeks\"> <h1>GeeksforGeeks</h1> </div></body> </html>",
"e": 25021,
"s": 24742,
"text": null
},
{
"code": null,
"e": 25062,
"s": 25021,
"text": "CSS Code: For CSS, follow these steps: "
},
{
"code": null,
"e": 25173,
"s": 25062,
"text": "Step 1: First we have done some basic styling like providing a background color, aligning text to center, etc."
},
{
"code": null,
"e": 25243,
"s": 25173,
"text": "Step 2: Then use animation property with identifier named as animate."
},
{
"code": null,
"e": 25342,
"s": 25243,
"text": "Step 3: Now use keyframes to animate each frame and set different height and width for each frame."
},
{
"code": null,
"e": 25447,
"s": 25342,
"text": "Tip: You can change the value of height and width used in each frame to reveal text in a different way. "
},
{
"code": null,
"e": 25451,
"s": 25447,
"text": "CSS"
},
{
"code": "<style> body { background: green; } .geeks { width: 20%; top: 50%; position: absolute; left: 40%; border-bottom: 5px solid white; overflow: hidden; animation: animate 2s linear forwards; } .geeks h1 { color: white; } @keyframes animate { 0% { width: 0px; height: 0px; } 30% { width: 50px; height: 0px; } 60% { width: 50px; height: 80px; } }</style>",
"e": 25998,
"s": 25451,
"text": null
},
{
"code": null,
"e": 26071,
"s": 25998,
"text": "Complete Code: It is the combination of the above two section of codes. "
},
{
"code": null,
"e": 26076,
"s": 26071,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Text Reveal Animation</title> <style> body { background: green; } .geeks { width: 20%; top: 50%; position: absolute; left: 40%; border-bottom: 5px solid white; overflow: hidden; animation: animate 2s linear forwards; } .geeks h1 { color: white; } @keyframes animate { 0% { width: 0px; height: 0px; } 30% { width: 50px; height: 0px; } 60% { width: 50px; height: 80px; } } </style></head> <body> <div class=\"geeks\"> <h1>GeeksforGeeks</h1> </div></body> </html>",
"e": 27026,
"s": 26076,
"text": null
},
{
"code": null,
"e": 27036,
"s": 27026,
"text": "Output: "
},
{
"code": null,
"e": 27061,
"s": 27036,
"text": "One more animated method"
},
{
"code": null,
"e": 27166,
"s": 27061,
"text": "HTML Code: The following code snippet creates HTML div element which contains the text for modification."
},
{
"code": null,
"e": 27171,
"s": 27166,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Collecting Data</title> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\" crossorigin=\"anonymous\"> </head><body class=\"container\" style=\"margin-top: 50px; width: 50% height:auto; \"> <div class=\"text-typing\"> <p>Geeks For Geeks </p> </div></html>",
"e": 27636,
"s": 27171,
"text": null
},
{
"code": null,
"e": 27676,
"s": 27636,
"text": "CSS Code: For CSS, follow theses steps:"
},
{
"code": null,
"e": 27788,
"s": 27676,
"text": "Step 1: First we have done some basic styling like providing a background color, aligning items to center, etc."
},
{
"code": null,
"e": 27864,
"s": 27788,
"text": "Step 2: Then use animation property with identifier named as text-typing p."
},
{
"code": null,
"e": 27924,
"s": 27864,
"text": "Step 3: Now use keyframes to animate from width 0 to 100%.."
},
{
"code": null,
"e": 27929,
"s": 27924,
"text": "HTML"
},
{
"code": "<style > body { margin:0px; height:100vh; display:flex; align-items:center; justify-content:center; background:#ddd;}.text-typing { padding:20px 30px; background:#f5f5f5; font-size:35px; font-family:monospace; border-radius:50px;}.text-typing p { margin:0px; white-space:nowrap; overflow:hidden; animation:typing 4s steps(22,end) forwards, blink 1s infinite;}@keyframes typing { 0% { width:0% } 100% { width:100% }}@keyframes blink { 0%,100% { border-right:2px solid transparent; } 50% { border-right:2px solid #222; }} </style>",
"e": 28505,
"s": 27929,
"text": null
},
{
"code": null,
"e": 28577,
"s": 28505,
"text": "Complete Code: It is the combination of the above two section of codes."
},
{
"code": null,
"e": 28582,
"s": 28577,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Collecting Data</title> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\" crossorigin=\"anonymous\"> <style > body { margin:0px; height:100vh; display:flex; align-items:center; justify-content:center; background:#ddd;}.text-typing { padding:20px 30px; background:#f5f5f5; font-size:35px; font-family:monospace; border-radius:50px;}.text-typing p { margin:0px; white-space:nowrap; overflow:hidden; animation:typing 4s steps(22,end) forwards, blink 1s infinite;}@keyframes typing { 0% { width:0% } 100% { width:100% }}@keyframes blink { 0%,100% { border-right:2px solid transparent; } 50% { border-right:2px solid #222; }} </style></head><body class=\"container\" style=\"margin-top: 50px; width: 50% height:auto; \"> <div class=\"text-typing\"> <p>Geeks For Geeks </p> </div></html>",
"e": 29623,
"s": 28582,
"text": null
},
{
"code": null,
"e": 29630,
"s": 29623,
"text": "Output"
},
{
"code": null,
"e": 29767,
"s": 29630,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29776,
"s": 29767,
"text": "annianni"
},
{
"code": null,
"e": 29791,
"s": 29776,
"text": "varshagumber28"
},
{
"code": null,
"e": 29800,
"s": 29791,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29810,
"s": 29800,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29814,
"s": 29810,
"text": "CSS"
},
{
"code": null,
"e": 29819,
"s": 29814,
"text": "HTML"
},
{
"code": null,
"e": 29836,
"s": 29819,
"text": "Web Technologies"
},
{
"code": null,
"e": 29863,
"s": 29836,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29868,
"s": 29863,
"text": "HTML"
},
{
"code": null,
"e": 29966,
"s": 29868,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29975,
"s": 29966,
"text": "Comments"
},
{
"code": null,
"e": 29988,
"s": 29975,
"text": "Old Comments"
},
{
"code": null,
"e": 30046,
"s": 29988,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 30083,
"s": 30046,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 30124,
"s": 30083,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 30161,
"s": 30124,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30225,
"s": 30161,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 30285,
"s": 30225,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30346,
"s": 30285,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30383,
"s": 30346,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 30436,
"s": 30383,
"text": "Hide or show elements in HTML using display property"
}
] |
How to set dialog to show with full screen in Android? | This example demonstrates how do I set the dialog to show with full screen in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:onClick="ClickHere"
android:text="Click here" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello World" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ClickHere(View view) {
Dialog dialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
dialog.setContentView(R.layout.activity_main);
dialog.show();
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "This example demonstrates how do I set the dialog to show with full screen in android."
},
{
"code": null,
"e": 1278,
"s": 1149,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1343,
"s": 1278,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2027,
"s": 1343,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n<Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"40dp\"\n android:onClick=\"ClickHere\"\n android:text=\"Click here\" />\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Hello World\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2084,
"s": 2027,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2639,
"s": 2084,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.app.Dialog;\nimport android.os.Bundle;\nimport android.view.View;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void ClickHere(View view) {\n Dialog dialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);\n dialog.setContentView(R.layout.activity_main);\n dialog.show();\n }\n}\n"
},
{
"code": null,
"e": 2694,
"s": 2639,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3367,
"s": 2694,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3721,
"s": 3367,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
}
] |
Bollinger Bands Statistics in Trading | by Atilla Yurtseven | Towards Data Science | There are lots of traders use Bollinger Bands. I love Bollinger Bands as well. It uses and brings statistics into the trading world. But how accurate is it? Is it a correct way to use standard deviation in time-series? Let’s find out together!
There is no leading indicators
As traders, most of us use OHLC candle/bar charts (Open-High-Low-Close). This chart shows us what happened in the past. We can clearly see where a bar opened, moved and closed. We use lots of indicators. All of them tell us what happened in the past. To me; there’s no leading indicators. Past is the past! However, there are probabilities. If we have enough data from the past, we will have enough statistics about the underlying asset.
DATA DATA DATA...
We need data! Data is the key. Data is everything. We need to grab the data from a reliable source. In this article, I’m going to show you how can you download data for free as well using Python. I’m going to use AlphaVantage.
First of all; go ahead and register for a free key in AlphaVantage website. Note that, I’m not affiliated with them.
Now let’s download the data using Python.
def load_data(sym="EUR", to_sym="USD", interval="5min", dtype=2, intraday=False, outputsize="full"): key = "ENTER_YOUR_KEY" if dtype == 1: # Download stock if intraday: url = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&interval={}&symbol={}&apikey={}&datatype=csv&outputsize={}".format(interval, sym, key, outputsize) else: url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&apikey={}&datatype=csv&outputsize={}".format(sym, key, outputsize) elif dtype == 2: # Download forex print("FX") if intraday: url = "https://www.alphavantage.co/query?function=FX_INTRADAY&interval={}&from_symbol={}&to_symbol={}&apikey={}&datatype=csv&outputsize={}".format(interval, sym, to_sym, key, outputsize) else: url = "https://www.alphavantage.co/query?function=FX_DAILY&from_symbol={}&to_symbol={}&apikey={}&datatype=csv&outputsize={}".format(sym, to_sym, key, outputsize) elif dtype == 3: # Download Crypto url = "https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol={}&market={}&apikey={}&datatype=csv&outputsize={}".format(sym, to_sym, key, outputsize) print("Downloading", url) print("---") df = pd.read_csv(url)# rename columns if dtype == 3: df.rename(columns={'timestamp': 'Date', 'open (USD)': 'Open', 'high (USD)': 'High', 'low (USD)': 'Low', 'close (USD)': 'Close', 'volume': 'Volume'}, inplace=True) else: df.rename(columns={'timestamp': 'Date', 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close', 'volume': 'Volume'}, inplace=True) df.sort_values(by="Date", ascending=True, inplace=True) print("Data loaded:", len(df), "rows") return df# Optionssym = "EUR"to_sym = "USD" # only for fx and cryptocurrencyintraday = False # False: Dailyinterval = "5min" # 1min 5min 15min 30min 60min - only if intraday is set to Truedtype = 2 # 1: stock 2: fx 3: crypto# load datadf = load_data(sym, to_sym, interval, dtype, intraday)
We have downloaded our data and here’s how it looks.
df['Close'].plot(figsize=(15, 10))
Here’s the daily chart of EURUSD. Now what we need to do is to add Bollinger Bands on the chart and calculate the statistics.
def add_bb(df, dev=2, lb=20, col="Close", lines=100): df['MA'] = df[col].rolling(lb).mean() df['STD'] = df[col].rolling(lb).std() df['OVB'] = df['MA'] + df['STD'] * dev df['OVS'] = df['MA'] - df['STD'] * dev plot_candles(df, lines=lines) get_stats(df, dev=dev)
Notice that i have added two new functions. First one plots candles and second one calculates and prints out the past statistics of Bollinger Bands. Let’s quickly define these functions.
def plot_candles(df, lines=100): df['Bar'] = df['High'] - df['Low'] df['Body'] = abs(df['Close'] - df['Open']) df['Up'] = df['Close'] > df['Open'] df['Color'] = np.where(df['Up'], "g", "r") if lines > 0: db = df[-lines:].reset_index(drop=True).reset_index() else: db = df.reset_index(drop=True).reset_index() plt.figure(figsize=(15, 10)) plt.bar(db['index'], bottom=db['Low'], height=db['Bar'], color="#000000", width=0.2) plt.bar(db['index'], bottom=np.where(db['Up'], db['Open'], db['Close']), height=db['Body'], color=db['Color'], width=0.9) plt.plot(db['OVB'], color="b") plt.plot(db['OVS'], color="b") plt.show()def get_stats(df, high_col="Close", low_col="Close", high_dev="OVB", low_dev="OVS", dev=2): total = len(df) inside = len(df[(df[high_col]<=df[high_dev]) & (df[low_col]>=df[low_dev])]) upside = len(df[df[high_col]>=df[high_dev]]) downside = len(df[df[low_col]<=df[low_dev]]) i = np.round(inside / total * 100, 2) u = np.round(upside / total * 100, 2) d = np.round(downside / total * 100, 2) # Print the stats print("Total bars:", total) print("Deviation", dev) print("Inside: ", i, "%", sep="") print("Up side: ", u, "%", sep="") print("Down side: ", d, "%", sep="")
Now let’s go ahead and run add_bb() function and see the results
dev = 2 # standard deviationlb = 20 # simple moving average (SMA) of last 20 bars including the final barlines = 500 # plot last 500 bars onlyadd_bb(df, dev=dev, lb=lb, lines=lines)
Very nice candlestick chart in a tricky way! And here’s the stats of Bollinger Bands within two standard deviation:
Total bars: 5000Deviation 2Inside: 89.96%Up side: 5.3%Down side: 4.36%
Inside means, total bars closed between 2 standard deviation; up side means, total bars closed above the upper band and down side means, total bars closed below the lower band.
Now what we see here’s the “PAST” statistics of standard Bollinger Bands. Feel free to change settings. For example, you can set one standard deviation with 200 SMA.
If you have a statistical background, you should know that, standard deviation works better in a normal distributed data. However, Closing prices is not normally distributed. You can easily see that running the code below:
df['Close'].hist(bins=500, figsize=(15, 10))
You might think it looks like normal distribution but i can easily say that it’s not. Here is how it should look:
That’s what i call a perfect bell curved shape. If you have such histogram plot, you can have better statistics which tells you more. And the distance between bands wouldn’t be as wide as Bollinger Bands.
Standard deviation states that; 68.26% of the data falls within one standard deviation of the mean, 95.44% of the data falls within two standard deviations of the mean and 99.74% of the data falls within three standard deviations of the mean. However, if we test using one standard deviation, here’s the result:
Total bars: 5000Deviation 1Inside: 44.96%Up side: 28.96%Down side: 25.7%
You can try stocks, forex, cryptocurrency; they all give you the similar results. This doesn’t look accurate to me at all!
Statistically speaking, Bollinger Bands may not meet your needs. However, you can use your favorite trading strategy and still make profit!
Disclaimer
I’m not a professional financial advisor. This article and codes, shared for educational purposes only and not financial advice. You are responsible your own losses or wins.
The whole code of this article can be found on this repository:
github.com
Ah also; remember to follow me on the following social channels:
MediumTwitterTradingView
Until next time; stay safe, trade safe!!!
Atilla Yurtseven
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. | [
{
"code": null,
"e": 415,
"s": 171,
"text": "There are lots of traders use Bollinger Bands. I love Bollinger Bands as well. It uses and brings statistics into the trading world. But how accurate is it? Is it a correct way to use standard deviation in time-series? Let’s find out together!"
},
{
"code": null,
"e": 446,
"s": 415,
"text": "There is no leading indicators"
},
{
"code": null,
"e": 884,
"s": 446,
"text": "As traders, most of us use OHLC candle/bar charts (Open-High-Low-Close). This chart shows us what happened in the past. We can clearly see where a bar opened, moved and closed. We use lots of indicators. All of them tell us what happened in the past. To me; there’s no leading indicators. Past is the past! However, there are probabilities. If we have enough data from the past, we will have enough statistics about the underlying asset."
},
{
"code": null,
"e": 902,
"s": 884,
"text": "DATA DATA DATA..."
},
{
"code": null,
"e": 1129,
"s": 902,
"text": "We need data! Data is the key. Data is everything. We need to grab the data from a reliable source. In this article, I’m going to show you how can you download data for free as well using Python. I’m going to use AlphaVantage."
},
{
"code": null,
"e": 1246,
"s": 1129,
"text": "First of all; go ahead and register for a free key in AlphaVantage website. Note that, I’m not affiliated with them."
},
{
"code": null,
"e": 1288,
"s": 1246,
"text": "Now let’s download the data using Python."
},
{
"code": null,
"e": 3316,
"s": 1288,
"text": "def load_data(sym=\"EUR\", to_sym=\"USD\", interval=\"5min\", dtype=2, intraday=False, outputsize=\"full\"): key = \"ENTER_YOUR_KEY\" if dtype == 1: # Download stock if intraday: url = \"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&interval={}&symbol={}&apikey={}&datatype=csv&outputsize={}\".format(interval, sym, key, outputsize) else: url = \"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&apikey={}&datatype=csv&outputsize={}\".format(sym, key, outputsize) elif dtype == 2: # Download forex print(\"FX\") if intraday: url = \"https://www.alphavantage.co/query?function=FX_INTRADAY&interval={}&from_symbol={}&to_symbol={}&apikey={}&datatype=csv&outputsize={}\".format(interval, sym, to_sym, key, outputsize) else: url = \"https://www.alphavantage.co/query?function=FX_DAILY&from_symbol={}&to_symbol={}&apikey={}&datatype=csv&outputsize={}\".format(sym, to_sym, key, outputsize) elif dtype == 3: # Download Crypto url = \"https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol={}&market={}&apikey={}&datatype=csv&outputsize={}\".format(sym, to_sym, key, outputsize) print(\"Downloading\", url) print(\"---\") df = pd.read_csv(url)# rename columns if dtype == 3: df.rename(columns={'timestamp': 'Date', 'open (USD)': 'Open', 'high (USD)': 'High', 'low (USD)': 'Low', 'close (USD)': 'Close', 'volume': 'Volume'}, inplace=True) else: df.rename(columns={'timestamp': 'Date', 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close', 'volume': 'Volume'}, inplace=True) df.sort_values(by=\"Date\", ascending=True, inplace=True) print(\"Data loaded:\", len(df), \"rows\") return df# Optionssym = \"EUR\"to_sym = \"USD\" # only for fx and cryptocurrencyintraday = False # False: Dailyinterval = \"5min\" # 1min 5min 15min 30min 60min - only if intraday is set to Truedtype = 2 # 1: stock 2: fx 3: crypto# load datadf = load_data(sym, to_sym, interval, dtype, intraday)"
},
{
"code": null,
"e": 3369,
"s": 3316,
"text": "We have downloaded our data and here’s how it looks."
},
{
"code": null,
"e": 3404,
"s": 3369,
"text": "df['Close'].plot(figsize=(15, 10))"
},
{
"code": null,
"e": 3530,
"s": 3404,
"text": "Here’s the daily chart of EURUSD. Now what we need to do is to add Bollinger Bands on the chart and calculate the statistics."
},
{
"code": null,
"e": 3809,
"s": 3530,
"text": "def add_bb(df, dev=2, lb=20, col=\"Close\", lines=100): df['MA'] = df[col].rolling(lb).mean() df['STD'] = df[col].rolling(lb).std() df['OVB'] = df['MA'] + df['STD'] * dev df['OVS'] = df['MA'] - df['STD'] * dev plot_candles(df, lines=lines) get_stats(df, dev=dev)"
},
{
"code": null,
"e": 3996,
"s": 3809,
"text": "Notice that i have added two new functions. First one plots candles and second one calculates and prints out the past statistics of Bollinger Bands. Let’s quickly define these functions."
},
{
"code": null,
"e": 5268,
"s": 3996,
"text": "def plot_candles(df, lines=100): df['Bar'] = df['High'] - df['Low'] df['Body'] = abs(df['Close'] - df['Open']) df['Up'] = df['Close'] > df['Open'] df['Color'] = np.where(df['Up'], \"g\", \"r\") if lines > 0: db = df[-lines:].reset_index(drop=True).reset_index() else: db = df.reset_index(drop=True).reset_index() plt.figure(figsize=(15, 10)) plt.bar(db['index'], bottom=db['Low'], height=db['Bar'], color=\"#000000\", width=0.2) plt.bar(db['index'], bottom=np.where(db['Up'], db['Open'], db['Close']), height=db['Body'], color=db['Color'], width=0.9) plt.plot(db['OVB'], color=\"b\") plt.plot(db['OVS'], color=\"b\") plt.show()def get_stats(df, high_col=\"Close\", low_col=\"Close\", high_dev=\"OVB\", low_dev=\"OVS\", dev=2): total = len(df) inside = len(df[(df[high_col]<=df[high_dev]) & (df[low_col]>=df[low_dev])]) upside = len(df[df[high_col]>=df[high_dev]]) downside = len(df[df[low_col]<=df[low_dev]]) i = np.round(inside / total * 100, 2) u = np.round(upside / total * 100, 2) d = np.round(downside / total * 100, 2) # Print the stats print(\"Total bars:\", total) print(\"Deviation\", dev) print(\"Inside: \", i, \"%\", sep=\"\") print(\"Up side: \", u, \"%\", sep=\"\") print(\"Down side: \", d, \"%\", sep=\"\")"
},
{
"code": null,
"e": 5333,
"s": 5268,
"text": "Now let’s go ahead and run add_bb() function and see the results"
},
{
"code": null,
"e": 5515,
"s": 5333,
"text": "dev = 2 # standard deviationlb = 20 # simple moving average (SMA) of last 20 bars including the final barlines = 500 # plot last 500 bars onlyadd_bb(df, dev=dev, lb=lb, lines=lines)"
},
{
"code": null,
"e": 5631,
"s": 5515,
"text": "Very nice candlestick chart in a tricky way! And here’s the stats of Bollinger Bands within two standard deviation:"
},
{
"code": null,
"e": 5702,
"s": 5631,
"text": "Total bars: 5000Deviation 2Inside: 89.96%Up side: 5.3%Down side: 4.36%"
},
{
"code": null,
"e": 5879,
"s": 5702,
"text": "Inside means, total bars closed between 2 standard deviation; up side means, total bars closed above the upper band and down side means, total bars closed below the lower band."
},
{
"code": null,
"e": 6045,
"s": 5879,
"text": "Now what we see here’s the “PAST” statistics of standard Bollinger Bands. Feel free to change settings. For example, you can set one standard deviation with 200 SMA."
},
{
"code": null,
"e": 6268,
"s": 6045,
"text": "If you have a statistical background, you should know that, standard deviation works better in a normal distributed data. However, Closing prices is not normally distributed. You can easily see that running the code below:"
},
{
"code": null,
"e": 6313,
"s": 6268,
"text": "df['Close'].hist(bins=500, figsize=(15, 10))"
},
{
"code": null,
"e": 6427,
"s": 6313,
"text": "You might think it looks like normal distribution but i can easily say that it’s not. Here is how it should look:"
},
{
"code": null,
"e": 6632,
"s": 6427,
"text": "That’s what i call a perfect bell curved shape. If you have such histogram plot, you can have better statistics which tells you more. And the distance between bands wouldn’t be as wide as Bollinger Bands."
},
{
"code": null,
"e": 6944,
"s": 6632,
"text": "Standard deviation states that; 68.26% of the data falls within one standard deviation of the mean, 95.44% of the data falls within two standard deviations of the mean and 99.74% of the data falls within three standard deviations of the mean. However, if we test using one standard deviation, here’s the result:"
},
{
"code": null,
"e": 7017,
"s": 6944,
"text": "Total bars: 5000Deviation 1Inside: 44.96%Up side: 28.96%Down side: 25.7%"
},
{
"code": null,
"e": 7140,
"s": 7017,
"text": "You can try stocks, forex, cryptocurrency; they all give you the similar results. This doesn’t look accurate to me at all!"
},
{
"code": null,
"e": 7280,
"s": 7140,
"text": "Statistically speaking, Bollinger Bands may not meet your needs. However, you can use your favorite trading strategy and still make profit!"
},
{
"code": null,
"e": 7291,
"s": 7280,
"text": "Disclaimer"
},
{
"code": null,
"e": 7465,
"s": 7291,
"text": "I’m not a professional financial advisor. This article and codes, shared for educational purposes only and not financial advice. You are responsible your own losses or wins."
},
{
"code": null,
"e": 7529,
"s": 7465,
"text": "The whole code of this article can be found on this repository:"
},
{
"code": null,
"e": 7540,
"s": 7529,
"text": "github.com"
},
{
"code": null,
"e": 7605,
"s": 7540,
"text": "Ah also; remember to follow me on the following social channels:"
},
{
"code": null,
"e": 7630,
"s": 7605,
"text": "MediumTwitterTradingView"
},
{
"code": null,
"e": 7672,
"s": 7630,
"text": "Until next time; stay safe, trade safe!!!"
},
{
"code": null,
"e": 7689,
"s": 7672,
"text": "Atilla Yurtseven"
}
] |
Deep Learning in Healthcare — X-Ray Imaging (Part 3-Analyzing images using Python) | by Arjun Sarkar | Towards Data Science | Now that we have seen how difficult it is for an untrained professional to interpret X-ray images, lets’ look at a few techniques to view and analyze the images, their histograms, and a technique to add images and labels together, using Python programming.
The image dataset (Chest X-Rays) was obtained from Kaggle. Dataset is available on the following link — https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia/data
About the dataset — direct quote from the Kaggle challenge — The dataset is organized into 3 folders (train, test, val) and contains subfolders for each image category (Pneumonia/Normal). There are 5,863 X-Ray images (JPEG) and 2 categories (Pneumonia/Normal). Chest X-ray images (anterior-posterior) were selected from retrospective cohorts of pediatric patients of one to five years old from Guangzhou Women and Children’s Medical Center, Guangzhou. All chest X-ray imaging was performed as part of patients’ routine clinical care. For the analysis of chest x-ray images, all chest radiographs were initially screened for quality control by removing all low quality or unreadable scans. The diagnoses for the images were then graded by two expert physicians before being cleared for training the AI system. In order to account for any grading errors, the evaluation set was also checked by a third expert.
As the content clearly states, there are a total of 5863 images available in the challenge, which have been split into 2 classes, Pneumonia and Normal, and further split into train/test and validation sets. To make the challenge even harder, we have split the data into three classes, Normal, Bacterial Pneumonia, and Viral Pneumonia. In this part, we will focus only on the images — loading them with python, analyzing various important aspects of the image from a medical imaging perspective, and loading the images and labels together. Let's dive straight into it.
#importing all the necessary librariesimport numpy as np import matplotlib.pyplot as pltimport osimport cv2 as cvimport random
Numpy — Numpy is one of the most commonly used libraries in Python. It is used for operations on multi-dimensional arrays and matrices and doing high-level mathematical functions to operate on these arrays.
Matplotlib — A library for creating static and animated visualizations in python.
os —A module that comes built-in with python. It provides functions for interacting with the operating system.
cv2 — OpenCV (Open Source Computer Vision Library) — A very important library mainly used for computer vision. Other similar libraries are SimpleITK and Pillow (Python Imaging Library).
random — A module that generates pseudo-random numbers.
#load a single image from the bacteria folderdef load_image(path): for img in os.listdir(bacteria_path): print('Image name =',img) image = cv.imread(os.path.join(bacteria_path, img)) break return image
The images from the dataset have been split into three classes as mentioned previously. 1-Normal, 2-Bacteria (Bacterial Pneumonia), 3- Virus (Viral Pneumonia).
The above code snippet is creating a function load_image, which will be used to load a single image from the training sets, Bacteria folder. os.listdir is used to list all the files present inside that directory. In this case, it can be used to access all the images present inside the folder Bacteria. Next, it will print the name of the image. Finally, the OpenCV library is used to read the image.
Break- is necessary here, so that only the first image is accessed, otherwise the function will loop through all the images present inside the Bacteria folder.
# Investigate a single imagebacteria_path = 'H:/All Files/Kaggle/chest_xray/train/2_BACTERIA/'image = load_image(bacteria_path)plt.imshow(image, cmap='gray')plt.colorbar()plt.title('Raw Chest X Ray Image')print(f"The dimensions are {image.shape[0]} pixels height and {image.shape[1]} pixels width")print(f"The maximum pixel value is {image.max():.4f}")print(f"The minimum pixel value is {image.min():.4f}")print(f"The mean value of the pixels is {image.mean():.4f}")print(f"The standard deviation is {image.std():.4f}")
output-
In this code snippet, first, the path of the images is defined. Then the first image from the folder is loaded into variable ‘image’ by calling the function load_image. The image is then viewed by using matplotlib.imshow. After this, the dimensions of the image, the maximum pixel value, and the minimum pixel value in the grayscale bar is printed. Also the mean and standard deviation of the image pixels are calculated.
Next, we plot the histogram of all the pixels of the image. A histogram is a graphical display of data using bars of different heights.
# plot a histogramplt.hist(image.ravel(),256,[0,256]) plt.show()
Output-
Matplotlib.hist is used to plot the histogram. As the image is mostly dark, we see a huge cluster of pixels on position zero of the grayscale bar.
These are some basic functions that can be carried out on images using OpenCV and matplotlib. We will in later parts see more uses of OpenCV.
# loading the path of the train imagespath = 'H:/All Files/Kaggle/chest_xray/train/'train = os.listdir(path)
The path of the training set is defined, and the directories under the path are saved in ‘train’. In this case, there are three folders, 1_Normal, 2_Bacteria, and 3_Virus.
folders=[]folders = [f for f in sorted(os.listdir(path))]print(folders)
output-
[‘1_NORMAL’, ‘2_BACTERIA’, ‘3_VIRUS’]
We create an empty list — folders. Then, iterate over the path, using os.listdir, and sort and store the folder names in the list — ‘folders’.
labels = foldersprint (f'The labels are {labels}')# setting the size of images that we wantimage_size = 256print(f'All images to be resized into {image_size}*{image_size} pixels')
output-
The folder names are set as labels for the images, and the image size is selected to be 256*256. That is, all the images will be resized into 256*256. If we go through the dataset, we see all the images are of varying dimensions, and to feed images into a Convolutional Neural Network (CNN) it is necessary to resize the images into the same dimensions.
# defining a function to load images and labels together# this function will also resize the imagesdef load_train(path): images = [] for label in labels: direc = os.path.join(path, label) class_num = labels.index(label) for image in os.listdir(direc): image_read = cv.imread(os.path.join(direc,image),cv.IMREAD_GRAYSCALE) image_resized = cv.resize(image_read,(image_size,image_size)) images.append([image_resized,class_num]) return np.array(images)
Here we define a function to load in all the images according to the label names, resize them into 256*256 pixels, and return the image arrays.
An empty list is created to save all the images. Then a ‘for’ loop is run to extract all the images from all the three folders. os.path.join is used to combine paths from directories. cv.IMREAD_GRAYSCALE converts all images to grayscale format. cv.resize is used to resize images to 256*256 pixels. ‘.append’ is used to append all the images into a list, which is finally converted to an array and returned using the return statement.
#load all the training images to train_imagestrain_images = load_train(path)print(f'Shape of the training images = {train_images.shape}')
output- Shape of the training images = (5208, 2)
The function ‘load_train’ is then called, and all the training images are saved as an array in train_images. The shape of training images is (5208,2)
#loading the images and labels seperately in X and y, to be used later for trainingX = []y = []for feature, label in train_images: X.append(feature) y.append(label) print (f'Length of X = {len(X)}')print (f'Length of y = {len(y)}')
output -
The images and labels need to be separated for training a neural network, and they are done so, by looping over the train_images, and by extracting the images and their corresponding labels.
# checking the number of images of each classa = 0b = 0c = 0for label in y: if label == 0: a += 1 if label == 1: b += 1 if label == 2: c += 1 print (f'Number of Normal images = {a}')print (f'Number of Bacteria images = {b}')print (f'Number of Virus images = {c}')# plotting the datax_pos = [i for i, _ in enumerate(labels)]numbers = [a,b,c]plt.bar(x_pos,numbers,color = 'green')plt.xlabel("Labels")plt.ylabel("No. of images")plt.title("Images for each label")plt.xticks(x_pos, labels)plt.show()
output-
To check the number of images in each class, a for loop was run. The results are then plotted using matplotlib.bar which is used to create bar charts.
From the data, it is clear, that there is a big difference in the number of images belonging to each label. If the network is trained with exactly these numbers of images, it might be biased towards the class with most labels. This is known as the Class Imbalance Problem. Hence it is necessary for each class to have a similar number of images, which we will talk about in the next part.
# Displays images # Extract 9 random imagesprint('Display Random Images')# Adjust the size of your imagesplt.figure(figsize=(20,10))for i in range(9): num = random.randint(0,len(X)-1) plt.subplot(3, 3, i + 1) plt.imshow(X[num],cmap='gray') plt.axis('off') # Adjust subplot parameters to give specified paddingplt.tight_layout()
Finally, we use the random module to generate nine random images from the training set and then used matplotlib to plot these images.
This is the end of this part. As we see, for medical imaging analysis it is first very important to understand the dataset properly, in this case, X-ray images. In the next part, we will deal with the class imbalance problem and more operations using matplotlib and OpenCV.
References:
Dataset obtained from- Kermany, Daniel; Zhang, Kang; Goldbaum, Michael (2018), “Labeled Optical Coherence Tomography (OCT) and Chest X-Ray Images for Classification”, Mendeley Data, v2http://dx.doi.org/10.17632/rscbjbr9sj.Identifying Medical Diagnoses and Treatable Diseases by Image-Based Deep Learning- (2018), Author: Daniel S. Kermany, Michael Goldbaum, Wenjia Cai, Carolina C.S. Valentim, Huiying Liang, Sally L. Baxter, Alex McKeown, Ge Yang, Xiaokang Wu, Fangbing Yan, Justin Dong, Made K. Prasadha, Jacqueline Pei, Magdalene Y.L. Ting, Jie Zhu, Christina Li, Sierra Hewett, et al., Publication: Cell Publisher: Elsevier.
Dataset obtained from- Kermany, Daniel; Zhang, Kang; Goldbaum, Michael (2018), “Labeled Optical Coherence Tomography (OCT) and Chest X-Ray Images for Classification”, Mendeley Data, v2http://dx.doi.org/10.17632/rscbjbr9sj.
Identifying Medical Diagnoses and Treatable Diseases by Image-Based Deep Learning- (2018), Author: Daniel S. Kermany, Michael Goldbaum, Wenjia Cai, Carolina C.S. Valentim, Huiying Liang, Sally L. Baxter, Alex McKeown, Ge Yang, Xiaokang Wu, Fangbing Yan, Justin Dong, Made K. Prasadha, Jacqueline Pei, Magdalene Y.L. Ting, Jie Zhu, Christina Li, Sierra Hewett, et al., Publication: Cell Publisher: Elsevier. | [
{
"code": null,
"e": 428,
"s": 171,
"text": "Now that we have seen how difficult it is for an untrained professional to interpret X-ray images, lets’ look at a few techniques to view and analyze the images, their histograms, and a technique to add images and labels together, using Python programming."
},
{
"code": null,
"e": 599,
"s": 428,
"text": "The image dataset (Chest X-Rays) was obtained from Kaggle. Dataset is available on the following link — https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia/data"
},
{
"code": null,
"e": 1507,
"s": 599,
"text": "About the dataset — direct quote from the Kaggle challenge — The dataset is organized into 3 folders (train, test, val) and contains subfolders for each image category (Pneumonia/Normal). There are 5,863 X-Ray images (JPEG) and 2 categories (Pneumonia/Normal). Chest X-ray images (anterior-posterior) were selected from retrospective cohorts of pediatric patients of one to five years old from Guangzhou Women and Children’s Medical Center, Guangzhou. All chest X-ray imaging was performed as part of patients’ routine clinical care. For the analysis of chest x-ray images, all chest radiographs were initially screened for quality control by removing all low quality or unreadable scans. The diagnoses for the images were then graded by two expert physicians before being cleared for training the AI system. In order to account for any grading errors, the evaluation set was also checked by a third expert."
},
{
"code": null,
"e": 2075,
"s": 1507,
"text": "As the content clearly states, there are a total of 5863 images available in the challenge, which have been split into 2 classes, Pneumonia and Normal, and further split into train/test and validation sets. To make the challenge even harder, we have split the data into three classes, Normal, Bacterial Pneumonia, and Viral Pneumonia. In this part, we will focus only on the images — loading them with python, analyzing various important aspects of the image from a medical imaging perspective, and loading the images and labels together. Let's dive straight into it."
},
{
"code": null,
"e": 2222,
"s": 2075,
"text": "#importing all the necessary librariesimport numpy as np import matplotlib.pyplot as pltimport osimport cv2 as cvimport random"
},
{
"code": null,
"e": 2429,
"s": 2222,
"text": "Numpy — Numpy is one of the most commonly used libraries in Python. It is used for operations on multi-dimensional arrays and matrices and doing high-level mathematical functions to operate on these arrays."
},
{
"code": null,
"e": 2511,
"s": 2429,
"text": "Matplotlib — A library for creating static and animated visualizations in python."
},
{
"code": null,
"e": 2622,
"s": 2511,
"text": "os —A module that comes built-in with python. It provides functions for interacting with the operating system."
},
{
"code": null,
"e": 2808,
"s": 2622,
"text": "cv2 — OpenCV (Open Source Computer Vision Library) — A very important library mainly used for computer vision. Other similar libraries are SimpleITK and Pillow (Python Imaging Library)."
},
{
"code": null,
"e": 2864,
"s": 2808,
"text": "random — A module that generates pseudo-random numbers."
},
{
"code": null,
"e": 3101,
"s": 2864,
"text": "#load a single image from the bacteria folderdef load_image(path): for img in os.listdir(bacteria_path): print('Image name =',img) image = cv.imread(os.path.join(bacteria_path, img)) break return image"
},
{
"code": null,
"e": 3261,
"s": 3101,
"text": "The images from the dataset have been split into three classes as mentioned previously. 1-Normal, 2-Bacteria (Bacterial Pneumonia), 3- Virus (Viral Pneumonia)."
},
{
"code": null,
"e": 3662,
"s": 3261,
"text": "The above code snippet is creating a function load_image, which will be used to load a single image from the training sets, Bacteria folder. os.listdir is used to list all the files present inside that directory. In this case, it can be used to access all the images present inside the folder Bacteria. Next, it will print the name of the image. Finally, the OpenCV library is used to read the image."
},
{
"code": null,
"e": 3822,
"s": 3662,
"text": "Break- is necessary here, so that only the first image is accessed, otherwise the function will loop through all the images present inside the Bacteria folder."
},
{
"code": null,
"e": 4342,
"s": 3822,
"text": "# Investigate a single imagebacteria_path = 'H:/All Files/Kaggle/chest_xray/train/2_BACTERIA/'image = load_image(bacteria_path)plt.imshow(image, cmap='gray')plt.colorbar()plt.title('Raw Chest X Ray Image')print(f\"The dimensions are {image.shape[0]} pixels height and {image.shape[1]} pixels width\")print(f\"The maximum pixel value is {image.max():.4f}\")print(f\"The minimum pixel value is {image.min():.4f}\")print(f\"The mean value of the pixels is {image.mean():.4f}\")print(f\"The standard deviation is {image.std():.4f}\")"
},
{
"code": null,
"e": 4350,
"s": 4342,
"text": "output-"
},
{
"code": null,
"e": 4772,
"s": 4350,
"text": "In this code snippet, first, the path of the images is defined. Then the first image from the folder is loaded into variable ‘image’ by calling the function load_image. The image is then viewed by using matplotlib.imshow. After this, the dimensions of the image, the maximum pixel value, and the minimum pixel value in the grayscale bar is printed. Also the mean and standard deviation of the image pixels are calculated."
},
{
"code": null,
"e": 4908,
"s": 4772,
"text": "Next, we plot the histogram of all the pixels of the image. A histogram is a graphical display of data using bars of different heights."
},
{
"code": null,
"e": 4973,
"s": 4908,
"text": "# plot a histogramplt.hist(image.ravel(),256,[0,256]) plt.show()"
},
{
"code": null,
"e": 4981,
"s": 4973,
"text": "Output-"
},
{
"code": null,
"e": 5128,
"s": 4981,
"text": "Matplotlib.hist is used to plot the histogram. As the image is mostly dark, we see a huge cluster of pixels on position zero of the grayscale bar."
},
{
"code": null,
"e": 5270,
"s": 5128,
"text": "These are some basic functions that can be carried out on images using OpenCV and matplotlib. We will in later parts see more uses of OpenCV."
},
{
"code": null,
"e": 5379,
"s": 5270,
"text": "# loading the path of the train imagespath = 'H:/All Files/Kaggle/chest_xray/train/'train = os.listdir(path)"
},
{
"code": null,
"e": 5551,
"s": 5379,
"text": "The path of the training set is defined, and the directories under the path are saved in ‘train’. In this case, there are three folders, 1_Normal, 2_Bacteria, and 3_Virus."
},
{
"code": null,
"e": 5623,
"s": 5551,
"text": "folders=[]folders = [f for f in sorted(os.listdir(path))]print(folders)"
},
{
"code": null,
"e": 5631,
"s": 5623,
"text": "output-"
},
{
"code": null,
"e": 5669,
"s": 5631,
"text": "[‘1_NORMAL’, ‘2_BACTERIA’, ‘3_VIRUS’]"
},
{
"code": null,
"e": 5812,
"s": 5669,
"text": "We create an empty list — folders. Then, iterate over the path, using os.listdir, and sort and store the folder names in the list — ‘folders’."
},
{
"code": null,
"e": 5992,
"s": 5812,
"text": "labels = foldersprint (f'The labels are {labels}')# setting the size of images that we wantimage_size = 256print(f'All images to be resized into {image_size}*{image_size} pixels')"
},
{
"code": null,
"e": 6000,
"s": 5992,
"text": "output-"
},
{
"code": null,
"e": 6354,
"s": 6000,
"text": "The folder names are set as labels for the images, and the image size is selected to be 256*256. That is, all the images will be resized into 256*256. If we go through the dataset, we see all the images are of varying dimensions, and to feed images into a Convolutional Neural Network (CNN) it is necessary to resize the images into the same dimensions."
},
{
"code": null,
"e": 6894,
"s": 6354,
"text": "# defining a function to load images and labels together# this function will also resize the imagesdef load_train(path): images = [] for label in labels: direc = os.path.join(path, label) class_num = labels.index(label) for image in os.listdir(direc): image_read = cv.imread(os.path.join(direc,image),cv.IMREAD_GRAYSCALE) image_resized = cv.resize(image_read,(image_size,image_size)) images.append([image_resized,class_num]) return np.array(images)"
},
{
"code": null,
"e": 7038,
"s": 6894,
"text": "Here we define a function to load in all the images according to the label names, resize them into 256*256 pixels, and return the image arrays."
},
{
"code": null,
"e": 7473,
"s": 7038,
"text": "An empty list is created to save all the images. Then a ‘for’ loop is run to extract all the images from all the three folders. os.path.join is used to combine paths from directories. cv.IMREAD_GRAYSCALE converts all images to grayscale format. cv.resize is used to resize images to 256*256 pixels. ‘.append’ is used to append all the images into a list, which is finally converted to an array and returned using the return statement."
},
{
"code": null,
"e": 7611,
"s": 7473,
"text": "#load all the training images to train_imagestrain_images = load_train(path)print(f'Shape of the training images = {train_images.shape}')"
},
{
"code": null,
"e": 7660,
"s": 7611,
"text": "output- Shape of the training images = (5208, 2)"
},
{
"code": null,
"e": 7810,
"s": 7660,
"text": "The function ‘load_train’ is then called, and all the training images are saved as an array in train_images. The shape of training images is (5208,2)"
},
{
"code": null,
"e": 8051,
"s": 7810,
"text": "#loading the images and labels seperately in X and y, to be used later for trainingX = []y = []for feature, label in train_images: X.append(feature) y.append(label) print (f'Length of X = {len(X)}')print (f'Length of y = {len(y)}')"
},
{
"code": null,
"e": 8060,
"s": 8051,
"text": "output -"
},
{
"code": null,
"e": 8251,
"s": 8060,
"text": "The images and labels need to be separated for training a neural network, and they are done so, by looping over the train_images, and by extracting the images and their corresponding labels."
},
{
"code": null,
"e": 8783,
"s": 8251,
"text": "# checking the number of images of each classa = 0b = 0c = 0for label in y: if label == 0: a += 1 if label == 1: b += 1 if label == 2: c += 1 print (f'Number of Normal images = {a}')print (f'Number of Bacteria images = {b}')print (f'Number of Virus images = {c}')# plotting the datax_pos = [i for i, _ in enumerate(labels)]numbers = [a,b,c]plt.bar(x_pos,numbers,color = 'green')plt.xlabel(\"Labels\")plt.ylabel(\"No. of images\")plt.title(\"Images for each label\")plt.xticks(x_pos, labels)plt.show()"
},
{
"code": null,
"e": 8791,
"s": 8783,
"text": "output-"
},
{
"code": null,
"e": 8942,
"s": 8791,
"text": "To check the number of images in each class, a for loop was run. The results are then plotted using matplotlib.bar which is used to create bar charts."
},
{
"code": null,
"e": 9331,
"s": 8942,
"text": "From the data, it is clear, that there is a big difference in the number of images belonging to each label. If the network is trained with exactly these numbers of images, it might be biased towards the class with most labels. This is known as the Class Imbalance Problem. Hence it is necessary for each class to have a similar number of images, which we will talk about in the next part."
},
{
"code": null,
"e": 9678,
"s": 9331,
"text": "# Displays images # Extract 9 random imagesprint('Display Random Images')# Adjust the size of your imagesplt.figure(figsize=(20,10))for i in range(9): num = random.randint(0,len(X)-1) plt.subplot(3, 3, i + 1) plt.imshow(X[num],cmap='gray') plt.axis('off') # Adjust subplot parameters to give specified paddingplt.tight_layout()"
},
{
"code": null,
"e": 9812,
"s": 9678,
"text": "Finally, we use the random module to generate nine random images from the training set and then used matplotlib to plot these images."
},
{
"code": null,
"e": 10086,
"s": 9812,
"text": "This is the end of this part. As we see, for medical imaging analysis it is first very important to understand the dataset properly, in this case, X-ray images. In the next part, we will deal with the class imbalance problem and more operations using matplotlib and OpenCV."
},
{
"code": null,
"e": 10098,
"s": 10086,
"text": "References:"
},
{
"code": null,
"e": 10727,
"s": 10098,
"text": "Dataset obtained from- Kermany, Daniel; Zhang, Kang; Goldbaum, Michael (2018), “Labeled Optical Coherence Tomography (OCT) and Chest X-Ray Images for Classification”, Mendeley Data, v2http://dx.doi.org/10.17632/rscbjbr9sj.Identifying Medical Diagnoses and Treatable Diseases by Image-Based Deep Learning- (2018), Author: Daniel S. Kermany, Michael Goldbaum, Wenjia Cai, Carolina C.S. Valentim, Huiying Liang, Sally L. Baxter, Alex McKeown, Ge Yang, Xiaokang Wu, Fangbing Yan, Justin Dong, Made K. Prasadha, Jacqueline Pei, Magdalene Y.L. Ting, Jie Zhu, Christina Li, Sierra Hewett, et al., Publication: Cell Publisher: Elsevier."
},
{
"code": null,
"e": 10950,
"s": 10727,
"text": "Dataset obtained from- Kermany, Daniel; Zhang, Kang; Goldbaum, Michael (2018), “Labeled Optical Coherence Tomography (OCT) and Chest X-Ray Images for Classification”, Mendeley Data, v2http://dx.doi.org/10.17632/rscbjbr9sj."
}
] |
How to programmatically empty browser cache with HTML? | You can tell your browser not to cache your page by using the following meta tags −
<metahttp-equiv = 'cache-control' content = 'no-cache'>
<metahttp-equiv = 'expires' content = '0'>
<metahttp-equiv = 'pragma' content = 'no-cache'>
In addition, try the following: Append a parameter/string to the filename in the script tag. Change it when the file changes.
<scriptsrc = "newfile.js?version = 1.0.0"></script>
Then the next time you update the file, just update the version i.e.
<scriptsrc = "newfile.js?version = 1.0.1"></script> | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "You can tell your browser not to cache your page by using the following meta tags −"
},
{
"code": null,
"e": 1294,
"s": 1146,
"text": "<metahttp-equiv = 'cache-control' content = 'no-cache'>\n<metahttp-equiv = 'expires' content = '0'>\n<metahttp-equiv = 'pragma' content = 'no-cache'>"
},
{
"code": null,
"e": 1421,
"s": 1294,
"text": "In addition, try the following: Append a parameter/string to the filename in the script tag. Change it when the file changes."
},
{
"code": null,
"e": 1473,
"s": 1421,
"text": "<scriptsrc = \"newfile.js?version = 1.0.0\"></script>"
},
{
"code": null,
"e": 1542,
"s": 1473,
"text": "Then the next time you update the file, just update the version i.e."
},
{
"code": null,
"e": 1594,
"s": 1542,
"text": "<scriptsrc = \"newfile.js?version = 1.0.1\"></script>"
}
] |
Analyzing multigraphs in Neo4j Graph data science library | by Tomaz Bratanic | Towards Data Science | When times are tough, I think it is essential to focus on our relationships. Some of us concentrate more on social interactions. Others like to play around with neurons, while some just want to look at cute animals. No matter your network preference, I would like to help you reflect on those relationships and find more (positive) insights about them. To do that, we will put on our data science hat and examine a simple network to learn how does the Neo4j Graph data science library deal with multigraphs and how to analyze them. I have to warn you that this will be a longer blog post and focused more on the technical details.
What is a multigraph anyway? Let’s look at the Wikipedia definition:
In mathematics, and more specifically in graph theory, a multigraph is a graph which is permitted to have multiple edges (also called parallel edges), that is, edges that have the same end nodes. Thus two vertices may be connected by more than one edge.
There are two distinct notions of multiple edges:
- Edges without own identity: The identity of an edge is defined solely by the two nodes it connects. In this case, the term “multiple edges” means that the same edge can occur several times between these two nodes.
- Edges with own identity: Edges are primitive entities just like nodes. When multiple edges connect two nodes, these are different edges.
To summarize the definition, the multigraph allows multiple relationships between a given pair of nodes. In other words, it means that we can have many connections of the same type between a pair of nodes like:
Or connections with different types between a pair of nodes like:
For example, in a knowledge graph, we might run into a combination of both.
We will use the above example graph to demonstrate how the GDS library handles projecting multigraphs, what to look for, and what to expect. I have added weights to relationships as we will need them to demonstrate property aggregations, but more on that later.
CREATE (t:Entity{name:'Tomaz'}), (n:Entity{name:'Neo4j'})CREATE (t)-[:LIKES{weight:1}]->(n), (t)-[:LOVES{weight:2}]->(n), (t)-[:PRESENTED_FOR{weight:0.5}]->(n), (t)-[:PRESENTED_FOR{weight:1.5}]->(n);
You can expect a deep dive into GDS multigraph projections, and little to no focus on the actual graph algorithms. We will use only the Degree centrality to examine the projected graphs.
In the context of the GDS library, relationships without their own identity imply that we ignore the type of relationships in the process of projecting the graph.
We will start with native projection examples. If we use the wildcard operator * to define the relationships we want to project, we ignore their type and bundle them all together. This can be understood as losing their own identity (type in the context of Neo4j).
In the first example, we will observe the default behavior of the graph projection process.
CALL gds.graph.create('default_agg','*','*', {relationshipProperties: ['weight']})
The default aggregation strategy doesn’t perform any aggregations and projects all the relationships from the stored graph to memory without any transformations. If we check the relationshipCount, we observe that four relationships have been projected. We can also take a look at the relationshipProjection:
{ "*": { "orientation": "NATURAL", "aggregation": "DEFAULT", "type": "*", "properties": { "weight": { "property": "weight", "defaultValue": null, "aggregation": "DEFAULT" } } }}
Anytime you see a type:'*', you can be sure that all relationships have lost their type in the projection process. This also means that we can't perform additional filtering when executing the algorithms. To double-check the projected graph, we can use the degree centrality.
CALL gds.alpha.degree.stream('default_agg')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC
Results
╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 4.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝
As we expected, all four relationships have been projected. To have a reference for the future, let’s also calculate the weighted degree centrality. By adding therelationshipWeightProperty parameter, we indicate we want to use the weighted variant of the algorithm.
CALL gds.alpha.degree.stream('default_agg', {relationshipWeightProperty:'weight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS weighted_degreeORDER BY weighted_degree DESC
Results
╔═══════════╦════════════════════╗║ name ║ weighted_degree ║╠═══════════╬════════════════════║║ Tomaz ║ 4.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════════════╝
The result is the sum of weights of all the considered relationships. We have no use of this projected graph anymore, so remember to release it from memory.
CALL gds.graph.drop('default_agg');
Depending on the use case, we might want to reduce our multigraph to a single graph during the projection process. This can be easily achieved with the aggregation parameter. We have to use the configuration map variant for the relationship definition.
CALL gds.graph.create('single_rel_strategy','*', {TYPE:{type:'*', aggregation:'SINGLE'}})
We notice by looking at the relationshipCount, that only a single relationship has been projected. If we want, we can double-check the results with the degree centrality.
CALL gds.alpha.degree.stream('single_rel_strategy')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC
Results
╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 1.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝
Don’t forget to drop the projected graph once we are done.
CALL gds.graph.drop('single_rel_strategy');
We have looked at the unweighted multigraph so far. Now it is time to look at what happens when we are dealing with a weighted multigraph, and we want to reduce it to a single graph. There are three different strategies we can pick for property aggregation strategy:
MIN: minimum value of all weights is projected
MAX: maximum value of all weights is projected
SUM: the sum of all weights is projected
In our next example, we will use the MIN property aggregation strategy to reduce a weighted multigraph to a single graph. By providing the property aggregation parameter, we indicate we want to reduce the stored graph to a single graph in the projection process.
CALL gds.graph.create('min_aggregation','*','*', {relationshipProperties: {weight: {property: 'weight', aggregation: 'MIN'}}})
We can observe that the relationshipCount is 1, which means our multigraph has been successfully reduced to a single graph. Let's examine the relationshipProjection.
{ "*": { "orientation": "NATURAL", "aggregation": "DEFAULT", "type": "*", "properties": { "weight": { "property": "weight", "defaultValue": null, "aggregation": "MIN" } } }}
Here we can observe that there are two aggregation configuration options, one on the relationship level and one on the property level. As far as I can tell, you should use the relationships level aggregation when dealing with unweighted networks and property level aggregation when dealing with weighted ones. We will again double-check the results with the degree centrality.
CALL gds.alpha.degree.stream('min_aggregation')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC
Results
╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 1.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝
To validate the MIN property aggregation, let's also calculate the weighted degree centrality.
CALL gds.alpha.degree.stream('min_aggregation', {relationshipWeightProperty:'weight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS weighted_degreeORDER BY weighted_degree DESC
Results
╔═══════════╦════════════════════╗║ name ║ weighted_degree ║╠═══════════╬════════════════════║║ Tomaz ║ 0.5 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════════════╝
As we expected with the MIN property aggregation strategy, the single reduced weight has the minimum value of considered weights. Again, as we finished with the example, don't forget to drop the projected graph.
CALL gds.graph.drop('min_aggregation');
Let’s recreate the above examples with cypher projection. To lose the identity of the relationships and bundle them all together, we avoid providing the type column in the return of the relationship statement.
Similarly to native projection, the default setting in cypher projection is to project all the relationships without any transformation during the projection process.
CALL gds.graph.create.cypher( 'cypher_default_strategy', 'MATCH (n:Entity) RETURN id(n) AS id', 'MATCH (n:Entity)-[r]->(m:Entity) RETURN id(n) AS source, id(m) AS target')
By looking at the relationshipCount, we observe that all four relationships have been projected as intended. Let's also take a close look at the relationshipProjection.
{ "*": { "orientation": "NATURAL", "aggregation": "DEFAULT", "type": "*", "properties": { } }}
Remember, before we said that the type:"*" indicates that relationships lose their identity (type) during the projection process. The same applies to cypher projection. To verify the projected graph, we run the degree centrality.
CALL gds.alpha.degree.stream('cypher_default_strategy')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC
Results
╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 4.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝
With cypher projection, we don’t have access to relationship level aggregation strategies. This is no problem at all, as it is very straightforward to reduce the multigraph to a single graph using only the cypher query language. We simply add the DISTINCT clause in the return of the relationship statement, and it should be good to go. If you need more help with cypher, I suggest you take a look at Neo4j Graph Academy.
CALL gds.graph.create.cypher( 'cypher_single_strategy', 'MATCH (n:Entity) RETURN id(n) AS id', 'MATCH (n:Entity)-[r]->(m:Entity) RETURN DISTINCT id(n) AS source, id(m) AS target')
The relationship count is 1, which means we have successfully reduced the multigraph. Remember to drop the projected graph.
CALL gds.graph.drop('cypher_single_strategy')
On the other hand, with cypher projection, we do have access to property level aggregation strategies. We don’t really “need” them as we can accomplish all the transformation using only cypher. To show you what I mean by that, we can apply the minimum property strategy aggregation using plain cypher like:
CALL gds.graph.create.cypher( 'cypher_min_strategy', 'MATCH (n:Entity) RETURN id(n) AS id', 'MATCH (n:Entity)-[r]->(m:Entity) RETURN id(n) AS source, id(m) AS target, min(r.weight) as weight')
However, if we look at the official documentation:
One drawback of that approach is that we put more pressure on the Cypher execution engine and the query result consumes additional memory. An alternative approach is to use relationshipProperties as part of the optional configuration map. The syntax is identical to the property mappings used in the native projection.
So, to conserve memory, we can use the property level aggregation strategies in the configuration map.
CALL gds.graph.create.cypher( 'cypher_min_improved', 'MATCH (n:Entity) RETURN id(n) AS id', 'MATCH (n:Entity)-[r]->(m:Entity) RETURN id(n) AS source, id(m) AS target, r.weight as weight', {relationshipProperties: {minWeight: {property: 'weight', aggregation: 'MIN'}}})
The relationshipCount is 1, which confirms our successful multigraph reduction. Just to make sure, we can run the weighted centrality and validate results.
CALL gds.alpha.degree.stream('cypher_min_improved', {relationshipWeightProperty:'minWeight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS weighted_degreeORDER BY weighted_degree DESC
Results
╔═══════════╦════════════════════╗║ name ║ weighted_degree ║╠═══════════╬════════════════════║║ Tomaz ║ 0.5 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════════════╝
With everything in order, we can release both projected graphs from memory.
CALL gds.graph.drop('cypher_min_improved');CALL gds.graph.drop('cypher_min_strategy);
We also have the option to retain the type of relationships during the projection process. Among other things, this allows us to perform additional filtering when executing graph algorithms. However, we have to be careful, as projecting relationships with a preserved type is a bit different in the context of multigraphs.
With the native projection, it is simple to declare that we want to preserve the type of relationships. All we have to do is specify which relationship types we want to consider, and the GDS engine will automatically bundle relationships under the specific relationship type. Let’s take a look at some examples to gain a better understanding.
From previous examples we already know that the default aggregation strategy does not perform any transformations. By defining the relationship types, we indicate to the GDS library that we want to retain their type after the projection process.
CALL gds.graph.create('type_default','*', ['PRESENTED_FOR','LIKES','LOVES'])
As expected, therelationshipsCount is 4. Let's take a closer look at the relationshipProjection.
{ "LIKES": { "orientation": "NATURAL", "aggregation": "DEFAULT", "type": "LIKES", "properties": {} }, "LOVES": { "orientation": "NATURAL", "aggregation": "DEFAULT", "type": "LOVES", "properties": {} }, "PRESENTED_FOR": { "orientation": "NATURAL", "aggregation": "DEFAULT", "type": "PRESENTED_FOR", "properties": {} }}
We can see that we have three different bundles or groups of relationships. Each bundle composes of a single relationship type, which is defined with the type parameter. It is handy to look at relationshipProjection to validate what kind of graph we have projected and if the relationship types have been retained. Not much else to do with this in-memory graph.
CALL gds.graph.drop('type_default');
Like before, we can reduce our unweighted multigraph to a single graph with the relationship level aggregation parameter. We have to provide the aggregation parameter for each relationship type separately.
CALL gds.graph.create('type_single','*', {LIKES:{type:'LIKES',aggregation:'SINGLE'}, LOVES:{type:'LOVES',aggregation:'SINGLE'}, PRESENTED_FOR:{type:'PRESENTED_FOR',aggregation:'SINGLE'}})
Ok, so we reduced to a single graph, but the relationshipCount is 3. Why is it so? The multigraph reduction process works on the relationship type level, and because we have three distinct relationship types, a single relationship for each type has been projected. Let's calculate the degree centrality on the whole in-memory graph.
CALL gds.alpha.degree.stream('type_single')YIELD nodeId, score RETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC
Results
╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 3.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝
As we explained, even though we have reduced each relationship type separately, we are still dealing with a multigraph on the whole. When running graph algorithms, you have to pay close attention to whether you are dealing with a multigraph or not, have you projected multiple relationship types and have you performed any transformations during projection, as all of this will affect the algorithm results.
We can now drop this graph.
CALL gds.graph.drop('type_single');
Property aggregation strategies are very similar to before when we were dealing with relationships without identity. The only change is that now the aggregations are grouped by the relationship type.
CALL gds.graph.create('type_min','*', ['PRESENTED_FOR','LIKES','LOVES'], {relationshipProperties: {weight: {property: 'weight', aggregation: 'MIN'}}})
We get 3 relationships projected as we have learned that the aggregations happen on the relationship type level. We will double-check the results with the weighted degree.
CALL gds.alpha.degree.stream('type_min', {relationshipWeightProperty:'weight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS weighted_degreeORDER BY weighted_degree DESC
Results
╔═══════════╦════════════════════╗║ name ║ weighted_degree ║╠═══════════╬════════════════════║║ Tomaz ║ 3.5 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════════════╝
I feel like a broken record by now, but don’t forget to drop the graph :)
CALL gds.graph.drop('type-min');
I skipped the examples for cypher projection with preserved relationship types to shorten this blog post a bit. Basically, all you have to do is to add the column type in the relationship statement, and it should behave identically to the native projection examples. I hope you got a better understanding of what is going on under the hood of the Neo4j Graph Data Science library during the projection process, which will hopefully help you find more and better insights. To sum it up, all aggregations either on relationship level or property level are grouped by the relationship type.
Thanks for reading, and as always, the code is available on GitHub. | [
{
"code": null,
"e": 803,
"s": 172,
"text": "When times are tough, I think it is essential to focus on our relationships. Some of us concentrate more on social interactions. Others like to play around with neurons, while some just want to look at cute animals. No matter your network preference, I would like to help you reflect on those relationships and find more (positive) insights about them. To do that, we will put on our data science hat and examine a simple network to learn how does the Neo4j Graph data science library deal with multigraphs and how to analyze them. I have to warn you that this will be a longer blog post and focused more on the technical details."
},
{
"code": null,
"e": 872,
"s": 803,
"text": "What is a multigraph anyway? Let’s look at the Wikipedia definition:"
},
{
"code": null,
"e": 1126,
"s": 872,
"text": "In mathematics, and more specifically in graph theory, a multigraph is a graph which is permitted to have multiple edges (also called parallel edges), that is, edges that have the same end nodes. Thus two vertices may be connected by more than one edge."
},
{
"code": null,
"e": 1176,
"s": 1126,
"text": "There are two distinct notions of multiple edges:"
},
{
"code": null,
"e": 1392,
"s": 1176,
"text": "- Edges without own identity: The identity of an edge is defined solely by the two nodes it connects. In this case, the term “multiple edges” means that the same edge can occur several times between these two nodes."
},
{
"code": null,
"e": 1531,
"s": 1392,
"text": "- Edges with own identity: Edges are primitive entities just like nodes. When multiple edges connect two nodes, these are different edges."
},
{
"code": null,
"e": 1742,
"s": 1531,
"text": "To summarize the definition, the multigraph allows multiple relationships between a given pair of nodes. In other words, it means that we can have many connections of the same type between a pair of nodes like:"
},
{
"code": null,
"e": 1808,
"s": 1742,
"text": "Or connections with different types between a pair of nodes like:"
},
{
"code": null,
"e": 1884,
"s": 1808,
"text": "For example, in a knowledge graph, we might run into a combination of both."
},
{
"code": null,
"e": 2146,
"s": 1884,
"text": "We will use the above example graph to demonstrate how the GDS library handles projecting multigraphs, what to look for, and what to expect. I have added weights to relationships as we will need them to demonstrate property aggregations, but more on that later."
},
{
"code": null,
"e": 2370,
"s": 2146,
"text": "CREATE (t:Entity{name:'Tomaz'}), (n:Entity{name:'Neo4j'})CREATE (t)-[:LIKES{weight:1}]->(n), (t)-[:LOVES{weight:2}]->(n), (t)-[:PRESENTED_FOR{weight:0.5}]->(n), (t)-[:PRESENTED_FOR{weight:1.5}]->(n);"
},
{
"code": null,
"e": 2557,
"s": 2370,
"text": "You can expect a deep dive into GDS multigraph projections, and little to no focus on the actual graph algorithms. We will use only the Degree centrality to examine the projected graphs."
},
{
"code": null,
"e": 2720,
"s": 2557,
"text": "In the context of the GDS library, relationships without their own identity imply that we ignore the type of relationships in the process of projecting the graph."
},
{
"code": null,
"e": 2984,
"s": 2720,
"text": "We will start with native projection examples. If we use the wildcard operator * to define the relationships we want to project, we ignore their type and bundle them all together. This can be understood as losing their own identity (type in the context of Neo4j)."
},
{
"code": null,
"e": 3076,
"s": 2984,
"text": "In the first example, we will observe the default behavior of the graph projection process."
},
{
"code": null,
"e": 3163,
"s": 3076,
"text": "CALL gds.graph.create('default_agg','*','*', {relationshipProperties: ['weight']})"
},
{
"code": null,
"e": 3471,
"s": 3163,
"text": "The default aggregation strategy doesn’t perform any aggregations and projects all the relationships from the stored graph to memory without any transformations. If we check the relationshipCount, we observe that four relationships have been projected. We can also take a look at the relationshipProjection:"
},
{
"code": null,
"e": 3697,
"s": 3471,
"text": "{ \"*\": { \"orientation\": \"NATURAL\", \"aggregation\": \"DEFAULT\", \"type\": \"*\", \"properties\": { \"weight\": { \"property\": \"weight\", \"defaultValue\": null, \"aggregation\": \"DEFAULT\" } } }}"
},
{
"code": null,
"e": 3973,
"s": 3697,
"text": "Anytime you see a type:'*', you can be sure that all relationships have lost their type in the projection process. This also means that we can't perform additional filtering when executing the algorithms. To double-check the projected graph, we can use the degree centrality."
},
{
"code": null,
"e": 4123,
"s": 3973,
"text": "CALL gds.alpha.degree.stream('default_agg')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC"
},
{
"code": null,
"e": 4131,
"s": 4123,
"text": "Results"
},
{
"code": null,
"e": 4288,
"s": 4131,
"text": "╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 4.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝"
},
{
"code": null,
"e": 4554,
"s": 4288,
"text": "As we expected, all four relationships have been projected. To have a reference for the future, let’s also calculate the weighted degree centrality. By adding therelationshipWeightProperty parameter, we indicate we want to use the weighted variant of the algorithm."
},
{
"code": null,
"e": 4765,
"s": 4554,
"text": "CALL gds.alpha.degree.stream('default_agg', {relationshipWeightProperty:'weight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS weighted_degreeORDER BY weighted_degree DESC"
},
{
"code": null,
"e": 4773,
"s": 4765,
"text": "Results"
},
{
"code": null,
"e": 4978,
"s": 4773,
"text": "╔═══════════╦════════════════════╗║ name ║ weighted_degree ║╠═══════════╬════════════════════║║ Tomaz ║ 4.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════════════╝"
},
{
"code": null,
"e": 5135,
"s": 4978,
"text": "The result is the sum of weights of all the considered relationships. We have no use of this projected graph anymore, so remember to release it from memory."
},
{
"code": null,
"e": 5171,
"s": 5135,
"text": "CALL gds.graph.drop('default_agg');"
},
{
"code": null,
"e": 5424,
"s": 5171,
"text": "Depending on the use case, we might want to reduce our multigraph to a single graph during the projection process. This can be easily achieved with the aggregation parameter. We have to use the configuration map variant for the relationship definition."
},
{
"code": null,
"e": 5516,
"s": 5424,
"text": "CALL gds.graph.create('single_rel_strategy','*', {TYPE:{type:'*', aggregation:'SINGLE'}})"
},
{
"code": null,
"e": 5687,
"s": 5516,
"text": "We notice by looking at the relationshipCount, that only a single relationship has been projected. If we want, we can double-check the results with the degree centrality."
},
{
"code": null,
"e": 5844,
"s": 5687,
"text": "CALL gds.alpha.degree.stream('single_rel_strategy')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC"
},
{
"code": null,
"e": 5852,
"s": 5844,
"text": "Results"
},
{
"code": null,
"e": 6009,
"s": 5852,
"text": "╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 1.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝"
},
{
"code": null,
"e": 6068,
"s": 6009,
"text": "Don’t forget to drop the projected graph once we are done."
},
{
"code": null,
"e": 6112,
"s": 6068,
"text": "CALL gds.graph.drop('single_rel_strategy');"
},
{
"code": null,
"e": 6379,
"s": 6112,
"text": "We have looked at the unweighted multigraph so far. Now it is time to look at what happens when we are dealing with a weighted multigraph, and we want to reduce it to a single graph. There are three different strategies we can pick for property aggregation strategy:"
},
{
"code": null,
"e": 6426,
"s": 6379,
"text": "MIN: minimum value of all weights is projected"
},
{
"code": null,
"e": 6473,
"s": 6426,
"text": "MAX: maximum value of all weights is projected"
},
{
"code": null,
"e": 6514,
"s": 6473,
"text": "SUM: the sum of all weights is projected"
},
{
"code": null,
"e": 6777,
"s": 6514,
"text": "In our next example, we will use the MIN property aggregation strategy to reduce a weighted multigraph to a single graph. By providing the property aggregation parameter, we indicate we want to reduce the stored graph to a single graph in the projection process."
},
{
"code": null,
"e": 6945,
"s": 6777,
"text": "CALL gds.graph.create('min_aggregation','*','*', {relationshipProperties: {weight: {property: 'weight', aggregation: 'MIN'}}})"
},
{
"code": null,
"e": 7111,
"s": 6945,
"text": "We can observe that the relationshipCount is 1, which means our multigraph has been successfully reduced to a single graph. Let's examine the relationshipProjection."
},
{
"code": null,
"e": 7333,
"s": 7111,
"text": "{ \"*\": { \"orientation\": \"NATURAL\", \"aggregation\": \"DEFAULT\", \"type\": \"*\", \"properties\": { \"weight\": { \"property\": \"weight\", \"defaultValue\": null, \"aggregation\": \"MIN\" } } }}"
},
{
"code": null,
"e": 7710,
"s": 7333,
"text": "Here we can observe that there are two aggregation configuration options, one on the relationship level and one on the property level. As far as I can tell, you should use the relationships level aggregation when dealing with unweighted networks and property level aggregation when dealing with weighted ones. We will again double-check the results with the degree centrality."
},
{
"code": null,
"e": 7863,
"s": 7710,
"text": "CALL gds.alpha.degree.stream('min_aggregation')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC"
},
{
"code": null,
"e": 7871,
"s": 7863,
"text": "Results"
},
{
"code": null,
"e": 8028,
"s": 7871,
"text": "╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 1.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝"
},
{
"code": null,
"e": 8123,
"s": 8028,
"text": "To validate the MIN property aggregation, let's also calculate the weighted degree centrality."
},
{
"code": null,
"e": 8336,
"s": 8123,
"text": "CALL gds.alpha.degree.stream('min_aggregation', {relationshipWeightProperty:'weight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS weighted_degreeORDER BY weighted_degree DESC"
},
{
"code": null,
"e": 8344,
"s": 8336,
"text": "Results"
},
{
"code": null,
"e": 8549,
"s": 8344,
"text": "╔═══════════╦════════════════════╗║ name ║ weighted_degree ║╠═══════════╬════════════════════║║ Tomaz ║ 0.5 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════════════╝"
},
{
"code": null,
"e": 8761,
"s": 8549,
"text": "As we expected with the MIN property aggregation strategy, the single reduced weight has the minimum value of considered weights. Again, as we finished with the example, don't forget to drop the projected graph."
},
{
"code": null,
"e": 8801,
"s": 8761,
"text": "CALL gds.graph.drop('min_aggregation');"
},
{
"code": null,
"e": 9011,
"s": 8801,
"text": "Let’s recreate the above examples with cypher projection. To lose the identity of the relationships and bundle them all together, we avoid providing the type column in the return of the relationship statement."
},
{
"code": null,
"e": 9178,
"s": 9011,
"text": "Similarly to native projection, the default setting in cypher projection is to project all the relationships without any transformation during the projection process."
},
{
"code": null,
"e": 9355,
"s": 9178,
"text": "CALL gds.graph.create.cypher( 'cypher_default_strategy', 'MATCH (n:Entity) RETURN id(n) AS id', 'MATCH (n:Entity)-[r]->(m:Entity) RETURN id(n) AS source, id(m) AS target')"
},
{
"code": null,
"e": 9524,
"s": 9355,
"text": "By looking at the relationshipCount, we observe that all four relationships have been projected as intended. Let's also take a close look at the relationshipProjection."
},
{
"code": null,
"e": 9637,
"s": 9524,
"text": "{ \"*\": { \"orientation\": \"NATURAL\", \"aggregation\": \"DEFAULT\", \"type\": \"*\", \"properties\": { } }}"
},
{
"code": null,
"e": 9867,
"s": 9637,
"text": "Remember, before we said that the type:\"*\" indicates that relationships lose their identity (type) during the projection process. The same applies to cypher projection. To verify the projected graph, we run the degree centrality."
},
{
"code": null,
"e": 10029,
"s": 9867,
"text": "CALL gds.alpha.degree.stream('cypher_default_strategy')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC"
},
{
"code": null,
"e": 10037,
"s": 10029,
"text": "Results"
},
{
"code": null,
"e": 10194,
"s": 10037,
"text": "╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 4.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝"
},
{
"code": null,
"e": 10616,
"s": 10194,
"text": "With cypher projection, we don’t have access to relationship level aggregation strategies. This is no problem at all, as it is very straightforward to reduce the multigraph to a single graph using only the cypher query language. We simply add the DISTINCT clause in the return of the relationship statement, and it should be good to go. If you need more help with cypher, I suggest you take a look at Neo4j Graph Academy."
},
{
"code": null,
"e": 10802,
"s": 10616,
"text": "CALL gds.graph.create.cypher( 'cypher_single_strategy', 'MATCH (n:Entity) RETURN id(n) AS id', 'MATCH (n:Entity)-[r]->(m:Entity) RETURN DISTINCT id(n) AS source, id(m) AS target')"
},
{
"code": null,
"e": 10926,
"s": 10802,
"text": "The relationship count is 1, which means we have successfully reduced the multigraph. Remember to drop the projected graph."
},
{
"code": null,
"e": 10972,
"s": 10926,
"text": "CALL gds.graph.drop('cypher_single_strategy')"
},
{
"code": null,
"e": 11279,
"s": 10972,
"text": "On the other hand, with cypher projection, we do have access to property level aggregation strategies. We don’t really “need” them as we can accomplish all the transformation using only cypher. To show you what I mean by that, we can apply the minimum property strategy aggregation using plain cypher like:"
},
{
"code": null,
"e": 11477,
"s": 11279,
"text": "CALL gds.graph.create.cypher( 'cypher_min_strategy', 'MATCH (n:Entity) RETURN id(n) AS id', 'MATCH (n:Entity)-[r]->(m:Entity) RETURN id(n) AS source, id(m) AS target, min(r.weight) as weight')"
},
{
"code": null,
"e": 11528,
"s": 11477,
"text": "However, if we look at the official documentation:"
},
{
"code": null,
"e": 11847,
"s": 11528,
"text": "One drawback of that approach is that we put more pressure on the Cypher execution engine and the query result consumes additional memory. An alternative approach is to use relationshipProperties as part of the optional configuration map. The syntax is identical to the property mappings used in the native projection."
},
{
"code": null,
"e": 11950,
"s": 11847,
"text": "So, to conserve memory, we can use the property level aggregation strategies in the configuration map."
},
{
"code": null,
"e": 12267,
"s": 11950,
"text": "CALL gds.graph.create.cypher( 'cypher_min_improved', 'MATCH (n:Entity) RETURN id(n) AS id', 'MATCH (n:Entity)-[r]->(m:Entity) RETURN id(n) AS source, id(m) AS target, r.weight as weight', {relationshipProperties: {minWeight: {property: 'weight', aggregation: 'MIN'}}})"
},
{
"code": null,
"e": 12423,
"s": 12267,
"text": "The relationshipCount is 1, which confirms our successful multigraph reduction. Just to make sure, we can run the weighted centrality and validate results."
},
{
"code": null,
"e": 12644,
"s": 12423,
"text": "CALL gds.alpha.degree.stream('cypher_min_improved', {relationshipWeightProperty:'minWeight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS weighted_degreeORDER BY weighted_degree DESC"
},
{
"code": null,
"e": 12652,
"s": 12644,
"text": "Results"
},
{
"code": null,
"e": 12857,
"s": 12652,
"text": "╔═══════════╦════════════════════╗║ name ║ weighted_degree ║╠═══════════╬════════════════════║║ Tomaz ║ 0.5 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════════════╝"
},
{
"code": null,
"e": 12933,
"s": 12857,
"text": "With everything in order, we can release both projected graphs from memory."
},
{
"code": null,
"e": 13019,
"s": 12933,
"text": "CALL gds.graph.drop('cypher_min_improved');CALL gds.graph.drop('cypher_min_strategy);"
},
{
"code": null,
"e": 13342,
"s": 13019,
"text": "We also have the option to retain the type of relationships during the projection process. Among other things, this allows us to perform additional filtering when executing graph algorithms. However, we have to be careful, as projecting relationships with a preserved type is a bit different in the context of multigraphs."
},
{
"code": null,
"e": 13685,
"s": 13342,
"text": "With the native projection, it is simple to declare that we want to preserve the type of relationships. All we have to do is specify which relationship types we want to consider, and the GDS engine will automatically bundle relationships under the specific relationship type. Let’s take a look at some examples to gain a better understanding."
},
{
"code": null,
"e": 13931,
"s": 13685,
"text": "From previous examples we already know that the default aggregation strategy does not perform any transformations. By defining the relationship types, we indicate to the GDS library that we want to retain their type after the projection process."
},
{
"code": null,
"e": 14011,
"s": 13931,
"text": "CALL gds.graph.create('type_default','*', ['PRESENTED_FOR','LIKES','LOVES'])"
},
{
"code": null,
"e": 14108,
"s": 14011,
"text": "As expected, therelationshipsCount is 4. Let's take a closer look at the relationshipProjection."
},
{
"code": null,
"e": 14468,
"s": 14108,
"text": "{ \"LIKES\": { \"orientation\": \"NATURAL\", \"aggregation\": \"DEFAULT\", \"type\": \"LIKES\", \"properties\": {} }, \"LOVES\": { \"orientation\": \"NATURAL\", \"aggregation\": \"DEFAULT\", \"type\": \"LOVES\", \"properties\": {} }, \"PRESENTED_FOR\": { \"orientation\": \"NATURAL\", \"aggregation\": \"DEFAULT\", \"type\": \"PRESENTED_FOR\", \"properties\": {} }}"
},
{
"code": null,
"e": 14830,
"s": 14468,
"text": "We can see that we have three different bundles or groups of relationships. Each bundle composes of a single relationship type, which is defined with the type parameter. It is handy to look at relationshipProjection to validate what kind of graph we have projected and if the relationship types have been retained. Not much else to do with this in-memory graph."
},
{
"code": null,
"e": 14867,
"s": 14830,
"text": "CALL gds.graph.drop('type_default');"
},
{
"code": null,
"e": 15073,
"s": 14867,
"text": "Like before, we can reduce our unweighted multigraph to a single graph with the relationship level aggregation parameter. We have to provide the aggregation parameter for each relationship type separately."
},
{
"code": null,
"e": 15269,
"s": 15073,
"text": "CALL gds.graph.create('type_single','*', {LIKES:{type:'LIKES',aggregation:'SINGLE'}, LOVES:{type:'LOVES',aggregation:'SINGLE'}, PRESENTED_FOR:{type:'PRESENTED_FOR',aggregation:'SINGLE'}})"
},
{
"code": null,
"e": 15602,
"s": 15269,
"text": "Ok, so we reduced to a single graph, but the relationshipCount is 3. Why is it so? The multigraph reduction process works on the relationship type level, and because we have three distinct relationship types, a single relationship for each type has been projected. Let's calculate the degree centrality on the whole in-memory graph."
},
{
"code": null,
"e": 15753,
"s": 15602,
"text": "CALL gds.alpha.degree.stream('type_single')YIELD nodeId, score RETURN gds.util.asNode(nodeId).name AS name, score AS degreeORDER BY degree DESC"
},
{
"code": null,
"e": 15761,
"s": 15753,
"text": "Results"
},
{
"code": null,
"e": 15918,
"s": 15761,
"text": "╔═══════════╦════════════╗║ name ║ degree ║╠═══════════╬════════════║║ Tomaz ║ 3.0 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════╝"
},
{
"code": null,
"e": 16326,
"s": 15918,
"text": "As we explained, even though we have reduced each relationship type separately, we are still dealing with a multigraph on the whole. When running graph algorithms, you have to pay close attention to whether you are dealing with a multigraph or not, have you projected multiple relationship types and have you performed any transformations during projection, as all of this will affect the algorithm results."
},
{
"code": null,
"e": 16354,
"s": 16326,
"text": "We can now drop this graph."
},
{
"code": null,
"e": 16390,
"s": 16354,
"text": "CALL gds.graph.drop('type_single');"
},
{
"code": null,
"e": 16590,
"s": 16390,
"text": "Property aggregation strategies are very similar to before when we were dealing with relationships without identity. The only change is that now the aggregations are grouped by the relationship type."
},
{
"code": null,
"e": 16786,
"s": 16590,
"text": "CALL gds.graph.create('type_min','*', ['PRESENTED_FOR','LIKES','LOVES'], {relationshipProperties: {weight: {property: 'weight', aggregation: 'MIN'}}})"
},
{
"code": null,
"e": 16958,
"s": 16786,
"text": "We get 3 relationships projected as we have learned that the aggregations happen on the relationship type level. We will double-check the results with the weighted degree."
},
{
"code": null,
"e": 17165,
"s": 16958,
"text": "CALL gds.alpha.degree.stream('type_min', {relationshipWeightProperty:'weight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name AS name, score AS weighted_degreeORDER BY weighted_degree DESC"
},
{
"code": null,
"e": 17173,
"s": 17165,
"text": "Results"
},
{
"code": null,
"e": 17378,
"s": 17173,
"text": "╔═══════════╦════════════════════╗║ name ║ weighted_degree ║╠═══════════╬════════════════════║║ Tomaz ║ 3.5 ║║ Neo4j ║ 0.0 ║╚═══════════╩════════════════════╝"
},
{
"code": null,
"e": 17452,
"s": 17378,
"text": "I feel like a broken record by now, but don’t forget to drop the graph :)"
},
{
"code": null,
"e": 17485,
"s": 17452,
"text": "CALL gds.graph.drop('type-min');"
},
{
"code": null,
"e": 18073,
"s": 17485,
"text": "I skipped the examples for cypher projection with preserved relationship types to shorten this blog post a bit. Basically, all you have to do is to add the column type in the relationship statement, and it should behave identically to the native projection examples. I hope you got a better understanding of what is going on under the hood of the Neo4j Graph Data Science library during the projection process, which will hopefully help you find more and better insights. To sum it up, all aggregations either on relationship level or property level are grouped by the relationship type."
}
] |
Adding one to number represented as array of digits - GeeksforGeeks | 05 Jan, 2022
Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ). The digits are stored such that the most significant digit is the first element of the array.
Examples :
Input : [1, 2, 4]
Output : [1, 2, 5]
Input : [9, 9, 9]
Output : [1, 0, 0, 0]
Approach: To add one to the number represented by digits, follow the below steps :
Parse the given array from the end as we do in school addition.
If the last elements are 9, make it 0 and carry = 1.
For the next iteration check carry and if it adds to 10, do same as step 2.
After adding carry, make carry = 0 for the next iteration.
If the vectors add and increase the vector size, append 1 in the beginning.
Below is the implementation to add 1 to number represented by digits.
C++
Java
C#
Python3
Javascript
// CPP implementation for Adding one// to number represented by digits#include <bits/stdc++.h>using namespace std; // function for adding one to numbervoid incrementVector(vector<int>& a){ int n = a.size(); // Add 1 to last digit and find carry a[n - 1] += 1; int carry = a[n - 1] / 10; a[n - 1] = a[n - 1] % 10; // Traverse from second last digit for (int i = n - 2; i >= 0; i--) { if (carry == 1) { a[i] += 1; carry = a[i] / 10; a[i] = a[i] % 10; } } // If carry is 1, we need to add // a 1 at the beginning of vector if (carry == 1) a.insert(a.begin(), 1);} // driver codeint main(){ vector<int> vect{ 1, 7, 8, 9 }; incrementVector(vect); for (int i = 0; i < vect.size(); i++) cout << vect[i] << " "; return 0;}
// Java implementation for Adding one// to number represented by digitsimport java.io.*;import java.util.*; class GFG { // function for adding one to number static void incrementVector(Vector<Integer> a) { int n = a.size(); // Add 1 to last digit and find carry a.set(n - 1, a.get(n - 1) + 1); int carry = a.get(n - 1) / 10; a.set(n - 1, a.get(n - 1) % 10); // Traverse from second last digit for (int i = n - 2; i >= 0; i--) { if (carry == 1) { a.set(i, a.get(i) + 1); carry = a.get(i) / 10; a.set(i, a.get(i) % 10); } } // If carry is 1, we need to add // a 1 at the beginning of vector if (carry == 1) a.add(0, 1); } // Driver code public static void main(String[] args) { Vector<Integer> vect = new Vector<Integer>(); vect.add(1); vect.add(7); vect.add(8); vect.add(9); incrementVector(vect); for (int i = 0; i < vect.size(); i++) System.out.print(vect.get(i) + " "); }} // This code is contributed by Gitanjali.
// C# implementation for Adding one// to number represented by digitsusing System;using System.Xml; namespace myTry {class Program { // Driver code static void Main(string[] args) { int carry = 0; int[] array = new int[] { 1, 7, 8, 9 }; // find the length of the array int n = array.Length; // Add 1 to the last digit and find carry array[n - 1] += 1; carry = array[n - 1] / 10; array[n - 1] = array[n - 1] % 10; // Traverse from second last digit for (int i = n - 2; i >= 0; i--) { if (carry == 1) { array[i] += 1; carry = array[i] / 10; array[i] = array[i] % 10; } } // If the carry is 1, we need to add // a 1 at the beginning of the array if (carry == 1) { Array.Resize(ref array, n + 1); array[0] = carry; } for (int i = 0; i < array.Length; i++) Console.WriteLine(array[i] + " "); }}}
# Python implementation for Adding one# to number represented by digits import math # function for adding one to number def incrementVector(a): n = len(a) # Add 1 to last digit and find carry a[n-1] += 1 carry = a[n-1]/10 a[n-1] = a[n-1] % 10 # Traverse from second last digit for i in range(n-2, -1, -1): if (carry == 1): a[i] += 1 carry = a[i]/10 a[i] = a[i] % 10 # If carry is 1, we need to add # a 1 at the beginning of vector if (carry == 1): a.insert(0, 1) # driver codevect = [1, 7, 8, 9] incrementVector(vect) for i in range(0, len(vect)): print(vect[i], end=" ") # This code is contributed by Gitanjali.
<script>// JavaScript implementation for Adding one// to number represented by digits // function for adding one to numberconst incrementVector = (a) =>{let n = a.length; // Add 1 to last digit and find carrya[n - 1] += 1;let carry = parseInt(a[n - 1] / 10);a[n - 1] = a[n - 1] % 10; // Traverse from second last digitfor (let i = n - 2; i >= 0; i--) { if (carry == 1) { a[i] += 1; carry = parseInt(a[i] / 10); a[i] = a[i] % 10; }} // If carry is 1, we need to add// a 1 at the beginning of vectorif (carry == 1) a.unshift(1);} // driver code let vect = [ 1, 7, 8, 9 ]; incrementVector(vect); for (let i = 0; i < vect.length; i++) document.write(`${vect[i]} `); // This code is contributed by rakeshsahni </script>
1 7 9 0
Another Approach: Start from the end of the vector and if the last element is 9 set it to 0, else exit the loop.
If the loop setted all digits to 0 (if all digits were 9) insert 1 at the beginning.
Else increment the element at the position where the loop stopped.
No carry/division/modulo is needed.
Below is the implementation:
C++
Java
Python3
C#
Javascript
#include <iostream>#include <vector> using namespace std; void AddOne(vector<int>& digits){ // initialize an index (digit of units) int index = digits.size() - 1; // while the index is valid and the value at [index] == // 9 set it as 0 while (index >= 0 && digits[index] == 9) digits[index--] = 0; // if index < 0 (if all digits were 9) if (index < 0) // insert an one at the beginning of the vector digits.insert(digits.begin(), 1, 1); // else increment the value at [index] else digits[index]++;} // Driver codeint main(){ vector<int> digits{ 1, 7, 8, 9 }; AddOne(digits); for (int digit : digits) cout << digit << ' '; return 0;}// This code is contributed// by Gatea David
// Java implementation for Adding one// to number represented by digitsimport java.io.*;import java.util.*;class GFG { static void AddOne(Vector<Integer> digits) { // initialize an index (digit of units) int index= digits.size() - 1; // while the index is valid and the value at [index] == // 9 set it as 0 while (index >= 0 && digits.get(index) == 9){ digits.set(index, 0); index -= 1; } // if index < 0 (if all digits were 9) if (index < 0) // insert an one at the beginning of the vector digits.set(0, 1); // else increment the value at [index] else digits.set(index, digits.get(index) + 1); } // Driver code public static void main(String[] args) { Vector<Integer> digits = new Vector<Integer>(Arrays.asList(1,7,8,9)); AddOne(digits); for (int digit : digits) System.out.print(digit + " "); }} // This code is contributed by Shubham Singh
#Python Programdef AddOne(digits): # initialize an index (digit of units) index = len(digits) - 1 # while the index is valid and the value at [index] == # 9 set it as 0 while (index >= 0 and digits[index] == 9): digits[index] = 0 index -= 1 # if index < 0 (if all digits were 9) if (index < 0): # insert an one at the beginning of the vector digits.insert(0, 1) # else increment the value at [index] else: digits[index]+=1 digits = [1, 7, 8, 9] AddOne(digits) for digit in digits: print(digit, end =' ') # This code is contributed# by Shubham Singh
// C# implementation for adding one// to number represented by digitsusing System;using System.Xml; class GFG{ // Driver codestatic void Main(string[] args){ int[] digits = new int[] { 1, 7, 8, 9 }; // Initialize an index (digit of units) int index = digits.Length - 1; // While the index is valid and the value at // [index] == 9 set it as 0 while (index >= 0 && digits[index] == 9) digits[index--] = 0; // If index < 0 (if all digits were 9) if (index < 0) { // Insert an one at the beginning of the vector Array.Resize(ref digits, index + 1); digits[0] = 1; } // Else increment the value at [index] else digits[index]++; foreach(int digit in digits) Console.Write(digit + " ");}} // This code is contributed by Shubham Singh
<script>// JavaScript implementation for Adding one// to number represented by digits // function for adding one to numberconst AddOne = (digits) =>{ // initialize an index (digit of units) let index = digits.length -1; // while the index is valid and the value at [index] == // 9 set it as 0 while (index >= 0 && digits[index] == 9) digits[index--] = 0; // if index < 0 (if all digits were 9) if (index < 0) // insert an one at the beginning of the vector digits.insert(digits.begin(), 1, 1); // else increment the value at [index] else digits[index]++;}// driver code let digits = [ 1, 7, 8, 9 ]; AddOne(digits); for (let i = 0; i < digits.length; i++) document.write(`${digits[i]} `); // This code is contributed by Shubham Singh </script>
1 7 9 0
Time Complexity: O(n), where n is the number of digits.
Auxiliary Space: O(1)
Another Approach :
In this approach we first reverse the original array then we take a carry variable to store the carry value.
Now we start iterating over the array from the start and we simply add 1 and carry to the value of that array at that index. After this we are going to check if that the value of that index is it greater than 9 then we can take carry as the ten’s value and the value at that index in the array will the value present at the ones place else we simply move on.
if digits[i]>9 then carry = digits[i]/10 and digits[i]%=10
if digits[i]<=9 then carry = 0.
We keep on doing this until we reach the last of the array. Now after coming out also if carry is not zero the we need to simply add that 1 the array also and then again reverse the array so that we get our original array.
How to Reverse an Array ?
Implementation :
C++
Java
Python3
C#
Javascript
// This Code represents one more approach to// Add 1 to the number repesentes in the array.// This code is contributed by Omkar Subhash Ghongade.#include<bits/stdc++.h>using namespace std; void plus_one(vector<int> &digits,int n){ // We are reversing the original arr // So thar we need to iterate from Back. reverse(digits.begin(),digits.end()); // Taking a carry variable in case if there is any carry int carry=0; for(int i=0;i<n;i++) { // Intitally carry is 0 so this is base case if(i==0) digits[i]+=(1+carry); // If carry is not equal to zero it should be added to // array element at that position. else if(carry!=0) digits[i]+=carry; // Now to get carry, i.e. // If digits[i]>9 we get the value at tens place in carry // or else if digits[i]<9 carry will be 0 carry=digits[i]/10; // Now if carry is not equal to 0 // so at that index we should keep the value present // at the ones place so we di digits[i]%10 if(carry!=0) digits[i]=digits[i]%10; } // Afte doing all that if carry is still there which means // one more element is needed to be added to the array if(carry!=0) digits.push_back(carry); // Now we reverse the array so that we get the final array reverse(digits.begin(),digits.end());} int main(){ vector<int> digits={9,8,9,9}; int n=digits.size(); plus_one(digits,n); for(int i=0;i<digits.size();i++) { cout<<digits[i]<<" "; }}
// This Code represents one more approach to// Add 1 to the number repesentes in the array.// This code is contributed by Omkar Subhash Ghongade.import java.io.*;import java.util.*;class GFG { public static void plus_one(Vector<Integer> digits,int n) { // We are reversing the original arr // So thar we need to iterate from Back. Collections.reverse(digits); // Taking a carry variable in case if there is any carry int carry = 0; for(int i = 0; i < n; i++) { // Intitally carry is 0 so this is base case if(i == 0) digits.set(i, digits.get(i) + 1 + carry); // If carry is not equal to zero it should be added to // array element at that position. else if(carry != 0) digits.set(i, digits.get(i) + carry); // Now to get carry, i.e. // If digits[i]>9 we get the value at tens place in carry // or else if digits[i]<9 carry will be 0 carry = digits.get(i) / 10; // Now if carry is not equal to 0 // so at that index we should keep the value present // at the ones place so we di digits[i]%10 if(carry != 0) digits.set(i, digits.get(i) % 10); } // Afte doing all that if carry is still there which means // one more element is needed to be added to the array if(carry != 0) digits.set(digits.size() - 1, carry); // Now we reverse the array so that we get the final array Collections.reverse(digits); } public static void main (String[] args) { Vector<Integer> digits = new Vector<Integer>(Arrays.asList(9,8,9,9)); int n = digits.size(); plus_one(digits, n); for(int i = 0; i < n; i++) { System.out.print(digits.get(i) + " "); } }} // This code is contributed by Shubham Singh
# This Code represents one more approach to# Add 1 to the number repesentes in the array.def plus_one(digits, n): # We are reversing the original arr # So thar we need to iterate from Back. digits.reverse() # Taking a carry variable in case if there is any carry carry = 0 for i in range(n): # itally carry is 0 so this is base case if(i == 0): digits[i] += (1 + carry) # If carry is not equal to zero it should be added to # array element at that position. elif(carry != 0): digits[i] += carry # Now to get carry, i.e. # If digits[i]>9 we get the value at tens place in carry # or else if digits[i]<9 carry will be 0 carry = digits[i]//10 # Now if carry is not equal to 0 # so at that index we should keep the value present # at the ones place so we di digits[i]%10 if(carry != 0): digits[i] = digits[i] % 10 # Afte doing all that if carry is still there which means # one more element is needed to be added to the array if(carry != 0): digits.append(carry) # Now we reverse the array so that we get the final array digits.reverse() # Diver codedigits = [9, 8, 9, 9]n = len(digits)plus_one(digits, n) for i in digits: print(i, end =" ") # This code is contributed# by Shubham Singh
// This Code represents one more approach to// Add 1 to the number repesentes in the array. using System; public class GFG{ public static void Main () { int[] digits = new int[] {9,8,9,9}; int n = digits.Length; // We are reversing the original arr // So thar we need to iterate from Back. Array.Reverse(digits); // Taking a carry variable in case if there is any carry int carry = 0; for(int i = 0; i < n; i++) { // Intitally carry is 0 so this is base case if(i == 0) digits[i] = digits[i] + 1 + carry; // If carry is not equal to zero it should be added to // array element at that position. else if(carry != 0) digits[i] = digits[i] + carry; // Now to get carry, i.e. // If digits[i]>9 we get the value at tens place in carry // or else if digits[i]<9 carry will be 0 carry = digits[i] / 10; // Now if carry is not equal to 0 // so at that index we should keep the value present // at the ones place so we di digits[i]%10 if(carry != 0) digits[i] = digits[i]%10; } // Afte doing all that if carry is still there which means // one more element is needed to be added to the array if(carry != 0) digits[digits.Length -1] = carry; // Now we reverse the array so that we get the final array Array.Reverse(digits); for(int i = 0; i < n; i++) { Console.Write(digits[i] + " "); } }} // This code is contributed by Shubham Singh
<script>// This Code represents one more approach to// Add 1 to the number repesentes in the array. var digits = [9,8,9,9];var n = digits.length; // We are reversing the original arr// So thar we need to iterate from Back.digits.reverse(); // Taking a carry variable in case if there is any carryvar carry = 0;for(var i = 0; i < n; i++){ // Intitally carry is 0 so this is base case if(i == 0) digits[i] = digits[i] + 1 + carry; // If carry is not equal to zero it should be added to // array element at that position. else if(carry != 0) digits[i] = digits[i] + carry; // Now to get carry, i.e. // If digits[i]>9 we get the value at tens place in carry // or else if digits[i]<9 carry will be 0 carry = parseInt(digits[i] / 10); // Now if carry is not equal to 0 // so at that index we should keep the value present // at the ones place so we di digits[i]%10 if(carry != 0) digits[i] = digits[i]%10;} // Afte doing all that if carry is still there which means// one more element is needed to be added to the arrayif(carry != 0) digits[digits.length -1] = carry; // Now we reverse the array so that we get the final arraydigits.reverse(); for(var i = 0; i < n; i++){ document.write(digits[i] + " ");} // This code is contributed by Shubham Singh</script>
9 9 0 0
Time Complexity : O(n), where n is the size of the array.
Auxiliary Space : O(1)
PINKYWALIA
davidgatea21
rexomkar
rakeshsahni
varshagumber28
SHUBHAMSINGH10
cpp-vector
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in C++
C++ Classes and Objects
Interfaces in Java
Operator Overloading in C++
Copy Constructor in C++
C++ Data Types
Overriding in Java
Types of Operating Systems
Polymorphism in C++
Python program to check if a string is palindrome or not | [
{
"code": null,
"e": 24685,
"s": 24657,
"text": "\n05 Jan, 2022"
},
{
"code": null,
"e": 24914,
"s": 24685,
"text": "Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ). The digits are stored such that the most significant digit is the first element of the array."
},
{
"code": null,
"e": 24926,
"s": 24914,
"text": "Examples : "
},
{
"code": null,
"e": 25004,
"s": 24926,
"text": "Input : [1, 2, 4]\nOutput : [1, 2, 5]\n\nInput : [9, 9, 9]\nOutput : [1, 0, 0, 0]"
},
{
"code": null,
"e": 25088,
"s": 25004,
"text": "Approach: To add one to the number represented by digits, follow the below steps : "
},
{
"code": null,
"e": 25152,
"s": 25088,
"text": "Parse the given array from the end as we do in school addition."
},
{
"code": null,
"e": 25205,
"s": 25152,
"text": "If the last elements are 9, make it 0 and carry = 1."
},
{
"code": null,
"e": 25281,
"s": 25205,
"text": "For the next iteration check carry and if it adds to 10, do same as step 2."
},
{
"code": null,
"e": 25340,
"s": 25281,
"text": "After adding carry, make carry = 0 for the next iteration."
},
{
"code": null,
"e": 25416,
"s": 25340,
"text": "If the vectors add and increase the vector size, append 1 in the beginning."
},
{
"code": null,
"e": 25487,
"s": 25416,
"text": "Below is the implementation to add 1 to number represented by digits. "
},
{
"code": null,
"e": 25491,
"s": 25487,
"text": "C++"
},
{
"code": null,
"e": 25496,
"s": 25491,
"text": "Java"
},
{
"code": null,
"e": 25499,
"s": 25496,
"text": "C#"
},
{
"code": null,
"e": 25507,
"s": 25499,
"text": "Python3"
},
{
"code": null,
"e": 25518,
"s": 25507,
"text": "Javascript"
},
{
"code": "// CPP implementation for Adding one// to number represented by digits#include <bits/stdc++.h>using namespace std; // function for adding one to numbervoid incrementVector(vector<int>& a){ int n = a.size(); // Add 1 to last digit and find carry a[n - 1] += 1; int carry = a[n - 1] / 10; a[n - 1] = a[n - 1] % 10; // Traverse from second last digit for (int i = n - 2; i >= 0; i--) { if (carry == 1) { a[i] += 1; carry = a[i] / 10; a[i] = a[i] % 10; } } // If carry is 1, we need to add // a 1 at the beginning of vector if (carry == 1) a.insert(a.begin(), 1);} // driver codeint main(){ vector<int> vect{ 1, 7, 8, 9 }; incrementVector(vect); for (int i = 0; i < vect.size(); i++) cout << vect[i] << \" \"; return 0;}",
"e": 26345,
"s": 25518,
"text": null
},
{
"code": "// Java implementation for Adding one// to number represented by digitsimport java.io.*;import java.util.*; class GFG { // function for adding one to number static void incrementVector(Vector<Integer> a) { int n = a.size(); // Add 1 to last digit and find carry a.set(n - 1, a.get(n - 1) + 1); int carry = a.get(n - 1) / 10; a.set(n - 1, a.get(n - 1) % 10); // Traverse from second last digit for (int i = n - 2; i >= 0; i--) { if (carry == 1) { a.set(i, a.get(i) + 1); carry = a.get(i) / 10; a.set(i, a.get(i) % 10); } } // If carry is 1, we need to add // a 1 at the beginning of vector if (carry == 1) a.add(0, 1); } // Driver code public static void main(String[] args) { Vector<Integer> vect = new Vector<Integer>(); vect.add(1); vect.add(7); vect.add(8); vect.add(9); incrementVector(vect); for (int i = 0; i < vect.size(); i++) System.out.print(vect.get(i) + \" \"); }} // This code is contributed by Gitanjali.",
"e": 27508,
"s": 26345,
"text": null
},
{
"code": "// C# implementation for Adding one// to number represented by digitsusing System;using System.Xml; namespace myTry {class Program { // Driver code static void Main(string[] args) { int carry = 0; int[] array = new int[] { 1, 7, 8, 9 }; // find the length of the array int n = array.Length; // Add 1 to the last digit and find carry array[n - 1] += 1; carry = array[n - 1] / 10; array[n - 1] = array[n - 1] % 10; // Traverse from second last digit for (int i = n - 2; i >= 0; i--) { if (carry == 1) { array[i] += 1; carry = array[i] / 10; array[i] = array[i] % 10; } } // If the carry is 1, we need to add // a 1 at the beginning of the array if (carry == 1) { Array.Resize(ref array, n + 1); array[0] = carry; } for (int i = 0; i < array.Length; i++) Console.WriteLine(array[i] + \" \"); }}}",
"e": 28528,
"s": 27508,
"text": null
},
{
"code": "# Python implementation for Adding one# to number represented by digits import math # function for adding one to number def incrementVector(a): n = len(a) # Add 1 to last digit and find carry a[n-1] += 1 carry = a[n-1]/10 a[n-1] = a[n-1] % 10 # Traverse from second last digit for i in range(n-2, -1, -1): if (carry == 1): a[i] += 1 carry = a[i]/10 a[i] = a[i] % 10 # If carry is 1, we need to add # a 1 at the beginning of vector if (carry == 1): a.insert(0, 1) # driver codevect = [1, 7, 8, 9] incrementVector(vect) for i in range(0, len(vect)): print(vect[i], end=\" \") # This code is contributed by Gitanjali.",
"e": 29227,
"s": 28528,
"text": null
},
{
"code": "<script>// JavaScript implementation for Adding one// to number represented by digits // function for adding one to numberconst incrementVector = (a) =>{let n = a.length; // Add 1 to last digit and find carrya[n - 1] += 1;let carry = parseInt(a[n - 1] / 10);a[n - 1] = a[n - 1] % 10; // Traverse from second last digitfor (let i = n - 2; i >= 0; i--) { if (carry == 1) { a[i] += 1; carry = parseInt(a[i] / 10); a[i] = a[i] % 10; }} // If carry is 1, we need to add// a 1 at the beginning of vectorif (carry == 1) a.unshift(1);} // driver code let vect = [ 1, 7, 8, 9 ]; incrementVector(vect); for (let i = 0; i < vect.length; i++) document.write(`${vect[i]} `); // This code is contributed by rakeshsahni </script>",
"e": 29975,
"s": 29227,
"text": null
},
{
"code": null,
"e": 29984,
"s": 29975,
"text": "1 7 9 0 "
},
{
"code": null,
"e": 30097,
"s": 29984,
"text": "Another Approach: Start from the end of the vector and if the last element is 9 set it to 0, else exit the loop."
},
{
"code": null,
"e": 30182,
"s": 30097,
"text": "If the loop setted all digits to 0 (if all digits were 9) insert 1 at the beginning."
},
{
"code": null,
"e": 30249,
"s": 30182,
"text": "Else increment the element at the position where the loop stopped."
},
{
"code": null,
"e": 30285,
"s": 30249,
"text": "No carry/division/modulo is needed."
},
{
"code": null,
"e": 30314,
"s": 30285,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 30318,
"s": 30314,
"text": "C++"
},
{
"code": null,
"e": 30323,
"s": 30318,
"text": "Java"
},
{
"code": null,
"e": 30331,
"s": 30323,
"text": "Python3"
},
{
"code": null,
"e": 30334,
"s": 30331,
"text": "C#"
},
{
"code": null,
"e": 30345,
"s": 30334,
"text": "Javascript"
},
{
"code": "#include <iostream>#include <vector> using namespace std; void AddOne(vector<int>& digits){ // initialize an index (digit of units) int index = digits.size() - 1; // while the index is valid and the value at [index] == // 9 set it as 0 while (index >= 0 && digits[index] == 9) digits[index--] = 0; // if index < 0 (if all digits were 9) if (index < 0) // insert an one at the beginning of the vector digits.insert(digits.begin(), 1, 1); // else increment the value at [index] else digits[index]++;} // Driver codeint main(){ vector<int> digits{ 1, 7, 8, 9 }; AddOne(digits); for (int digit : digits) cout << digit << ' '; return 0;}// This code is contributed// by Gatea David",
"e": 31102,
"s": 30345,
"text": null
},
{
"code": "// Java implementation for Adding one// to number represented by digitsimport java.io.*;import java.util.*;class GFG { static void AddOne(Vector<Integer> digits) { // initialize an index (digit of units) int index= digits.size() - 1; // while the index is valid and the value at [index] == // 9 set it as 0 while (index >= 0 && digits.get(index) == 9){ digits.set(index, 0); index -= 1; } // if index < 0 (if all digits were 9) if (index < 0) // insert an one at the beginning of the vector digits.set(0, 1); // else increment the value at [index] else digits.set(index, digits.get(index) + 1); } // Driver code public static void main(String[] args) { Vector<Integer> digits = new Vector<Integer>(Arrays.asList(1,7,8,9)); AddOne(digits); for (int digit : digits) System.out.print(digit + \" \"); }} // This code is contributed by Shubham Singh",
"e": 32029,
"s": 31102,
"text": null
},
{
"code": "#Python Programdef AddOne(digits): # initialize an index (digit of units) index = len(digits) - 1 # while the index is valid and the value at [index] == # 9 set it as 0 while (index >= 0 and digits[index] == 9): digits[index] = 0 index -= 1 # if index < 0 (if all digits were 9) if (index < 0): # insert an one at the beginning of the vector digits.insert(0, 1) # else increment the value at [index] else: digits[index]+=1 digits = [1, 7, 8, 9] AddOne(digits) for digit in digits: print(digit, end =' ') # This code is contributed# by Shubham Singh",
"e": 32681,
"s": 32029,
"text": null
},
{
"code": "// C# implementation for adding one// to number represented by digitsusing System;using System.Xml; class GFG{ // Driver codestatic void Main(string[] args){ int[] digits = new int[] { 1, 7, 8, 9 }; // Initialize an index (digit of units) int index = digits.Length - 1; // While the index is valid and the value at // [index] == 9 set it as 0 while (index >= 0 && digits[index] == 9) digits[index--] = 0; // If index < 0 (if all digits were 9) if (index < 0) { // Insert an one at the beginning of the vector Array.Resize(ref digits, index + 1); digits[0] = 1; } // Else increment the value at [index] else digits[index]++; foreach(int digit in digits) Console.Write(digit + \" \");}} // This code is contributed by Shubham Singh",
"e": 33584,
"s": 32681,
"text": null
},
{
"code": "<script>// JavaScript implementation for Adding one// to number represented by digits // function for adding one to numberconst AddOne = (digits) =>{ // initialize an index (digit of units) let index = digits.length -1; // while the index is valid and the value at [index] == // 9 set it as 0 while (index >= 0 && digits[index] == 9) digits[index--] = 0; // if index < 0 (if all digits were 9) if (index < 0) // insert an one at the beginning of the vector digits.insert(digits.begin(), 1, 1); // else increment the value at [index] else digits[index]++;}// driver code let digits = [ 1, 7, 8, 9 ]; AddOne(digits); for (let i = 0; i < digits.length; i++) document.write(`${digits[i]} `); // This code is contributed by Shubham Singh </script>",
"e": 34389,
"s": 33584,
"text": null
},
{
"code": null,
"e": 34398,
"s": 34389,
"text": "1 7 9 0 "
},
{
"code": null,
"e": 34454,
"s": 34398,
"text": "Time Complexity: O(n), where n is the number of digits."
},
{
"code": null,
"e": 34476,
"s": 34454,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34496,
"s": 34476,
"text": "Another Approach : "
},
{
"code": null,
"e": 34605,
"s": 34496,
"text": "In this approach we first reverse the original array then we take a carry variable to store the carry value."
},
{
"code": null,
"e": 34964,
"s": 34605,
"text": "Now we start iterating over the array from the start and we simply add 1 and carry to the value of that array at that index. After this we are going to check if that the value of that index is it greater than 9 then we can take carry as the ten’s value and the value at that index in the array will the value present at the ones place else we simply move on."
},
{
"code": null,
"e": 35055,
"s": 34964,
"text": "if digits[i]>9 then carry = digits[i]/10 and digits[i]%=10\nif digits[i]<=9 then carry = 0."
},
{
"code": null,
"e": 35278,
"s": 35055,
"text": "We keep on doing this until we reach the last of the array. Now after coming out also if carry is not zero the we need to simply add that 1 the array also and then again reverse the array so that we get our original array."
},
{
"code": null,
"e": 35304,
"s": 35278,
"text": "How to Reverse an Array ?"
},
{
"code": null,
"e": 35321,
"s": 35304,
"text": "Implementation :"
},
{
"code": null,
"e": 35325,
"s": 35321,
"text": "C++"
},
{
"code": null,
"e": 35330,
"s": 35325,
"text": "Java"
},
{
"code": null,
"e": 35338,
"s": 35330,
"text": "Python3"
},
{
"code": null,
"e": 35341,
"s": 35338,
"text": "C#"
},
{
"code": null,
"e": 35352,
"s": 35341,
"text": "Javascript"
},
{
"code": "// This Code represents one more approach to// Add 1 to the number repesentes in the array.// This code is contributed by Omkar Subhash Ghongade.#include<bits/stdc++.h>using namespace std; void plus_one(vector<int> &digits,int n){ // We are reversing the original arr // So thar we need to iterate from Back. reverse(digits.begin(),digits.end()); // Taking a carry variable in case if there is any carry int carry=0; for(int i=0;i<n;i++) { // Intitally carry is 0 so this is base case if(i==0) digits[i]+=(1+carry); // If carry is not equal to zero it should be added to // array element at that position. else if(carry!=0) digits[i]+=carry; // Now to get carry, i.e. // If digits[i]>9 we get the value at tens place in carry // or else if digits[i]<9 carry will be 0 carry=digits[i]/10; // Now if carry is not equal to 0 // so at that index we should keep the value present // at the ones place so we di digits[i]%10 if(carry!=0) digits[i]=digits[i]%10; } // Afte doing all that if carry is still there which means // one more element is needed to be added to the array if(carry!=0) digits.push_back(carry); // Now we reverse the array so that we get the final array reverse(digits.begin(),digits.end());} int main(){ vector<int> digits={9,8,9,9}; int n=digits.size(); plus_one(digits,n); for(int i=0;i<digits.size();i++) { cout<<digits[i]<<\" \"; }}",
"e": 36897,
"s": 35352,
"text": null
},
{
"code": "// This Code represents one more approach to// Add 1 to the number repesentes in the array.// This code is contributed by Omkar Subhash Ghongade.import java.io.*;import java.util.*;class GFG { public static void plus_one(Vector<Integer> digits,int n) { // We are reversing the original arr // So thar we need to iterate from Back. Collections.reverse(digits); // Taking a carry variable in case if there is any carry int carry = 0; for(int i = 0; i < n; i++) { // Intitally carry is 0 so this is base case if(i == 0) digits.set(i, digits.get(i) + 1 + carry); // If carry is not equal to zero it should be added to // array element at that position. else if(carry != 0) digits.set(i, digits.get(i) + carry); // Now to get carry, i.e. // If digits[i]>9 we get the value at tens place in carry // or else if digits[i]<9 carry will be 0 carry = digits.get(i) / 10; // Now if carry is not equal to 0 // so at that index we should keep the value present // at the ones place so we di digits[i]%10 if(carry != 0) digits.set(i, digits.get(i) % 10); } // Afte doing all that if carry is still there which means // one more element is needed to be added to the array if(carry != 0) digits.set(digits.size() - 1, carry); // Now we reverse the array so that we get the final array Collections.reverse(digits); } public static void main (String[] args) { Vector<Integer> digits = new Vector<Integer>(Arrays.asList(9,8,9,9)); int n = digits.size(); plus_one(digits, n); for(int i = 0; i < n; i++) { System.out.print(digits.get(i) + \" \"); } }} // This code is contributed by Shubham Singh",
"e": 38640,
"s": 36897,
"text": null
},
{
"code": "# This Code represents one more approach to# Add 1 to the number repesentes in the array.def plus_one(digits, n): # We are reversing the original arr # So thar we need to iterate from Back. digits.reverse() # Taking a carry variable in case if there is any carry carry = 0 for i in range(n): # itally carry is 0 so this is base case if(i == 0): digits[i] += (1 + carry) # If carry is not equal to zero it should be added to # array element at that position. elif(carry != 0): digits[i] += carry # Now to get carry, i.e. # If digits[i]>9 we get the value at tens place in carry # or else if digits[i]<9 carry will be 0 carry = digits[i]//10 # Now if carry is not equal to 0 # so at that index we should keep the value present # at the ones place so we di digits[i]%10 if(carry != 0): digits[i] = digits[i] % 10 # Afte doing all that if carry is still there which means # one more element is needed to be added to the array if(carry != 0): digits.append(carry) # Now we reverse the array so that we get the final array digits.reverse() # Diver codedigits = [9, 8, 9, 9]n = len(digits)plus_one(digits, n) for i in digits: print(i, end =\" \") # This code is contributed# by Shubham Singh",
"e": 40069,
"s": 38640,
"text": null
},
{
"code": "// This Code represents one more approach to// Add 1 to the number repesentes in the array. using System; public class GFG{ public static void Main () { int[] digits = new int[] {9,8,9,9}; int n = digits.Length; // We are reversing the original arr // So thar we need to iterate from Back. Array.Reverse(digits); // Taking a carry variable in case if there is any carry int carry = 0; for(int i = 0; i < n; i++) { // Intitally carry is 0 so this is base case if(i == 0) digits[i] = digits[i] + 1 + carry; // If carry is not equal to zero it should be added to // array element at that position. else if(carry != 0) digits[i] = digits[i] + carry; // Now to get carry, i.e. // If digits[i]>9 we get the value at tens place in carry // or else if digits[i]<9 carry will be 0 carry = digits[i] / 10; // Now if carry is not equal to 0 // so at that index we should keep the value present // at the ones place so we di digits[i]%10 if(carry != 0) digits[i] = digits[i]%10; } // Afte doing all that if carry is still there which means // one more element is needed to be added to the array if(carry != 0) digits[digits.Length -1] = carry; // Now we reverse the array so that we get the final array Array.Reverse(digits); for(int i = 0; i < n; i++) { Console.Write(digits[i] + \" \"); } }} // This code is contributed by Shubham Singh",
"e": 41570,
"s": 40069,
"text": null
},
{
"code": "<script>// This Code represents one more approach to// Add 1 to the number repesentes in the array. var digits = [9,8,9,9];var n = digits.length; // We are reversing the original arr// So thar we need to iterate from Back.digits.reverse(); // Taking a carry variable in case if there is any carryvar carry = 0;for(var i = 0; i < n; i++){ // Intitally carry is 0 so this is base case if(i == 0) digits[i] = digits[i] + 1 + carry; // If carry is not equal to zero it should be added to // array element at that position. else if(carry != 0) digits[i] = digits[i] + carry; // Now to get carry, i.e. // If digits[i]>9 we get the value at tens place in carry // or else if digits[i]<9 carry will be 0 carry = parseInt(digits[i] / 10); // Now if carry is not equal to 0 // so at that index we should keep the value present // at the ones place so we di digits[i]%10 if(carry != 0) digits[i] = digits[i]%10;} // Afte doing all that if carry is still there which means// one more element is needed to be added to the arrayif(carry != 0) digits[digits.length -1] = carry; // Now we reverse the array so that we get the final arraydigits.reverse(); for(var i = 0; i < n; i++){ document.write(digits[i] + \" \");} // This code is contributed by Shubham Singh</script>",
"e": 42905,
"s": 41570,
"text": null
},
{
"code": null,
"e": 42914,
"s": 42905,
"text": "9 9 0 0 "
},
{
"code": null,
"e": 42972,
"s": 42914,
"text": "Time Complexity : O(n), where n is the size of the array."
},
{
"code": null,
"e": 42995,
"s": 42972,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 43006,
"s": 42995,
"text": "PINKYWALIA"
},
{
"code": null,
"e": 43019,
"s": 43006,
"text": "davidgatea21"
},
{
"code": null,
"e": 43028,
"s": 43019,
"text": "rexomkar"
},
{
"code": null,
"e": 43040,
"s": 43028,
"text": "rakeshsahni"
},
{
"code": null,
"e": 43055,
"s": 43040,
"text": "varshagumber28"
},
{
"code": null,
"e": 43070,
"s": 43055,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 43081,
"s": 43070,
"text": "cpp-vector"
},
{
"code": null,
"e": 43100,
"s": 43081,
"text": "School Programming"
},
{
"code": null,
"e": 43198,
"s": 43100,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43207,
"s": 43198,
"text": "Comments"
},
{
"code": null,
"e": 43220,
"s": 43207,
"text": "Old Comments"
},
{
"code": null,
"e": 43240,
"s": 43220,
"text": "Constructors in C++"
},
{
"code": null,
"e": 43264,
"s": 43240,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 43283,
"s": 43264,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 43311,
"s": 43283,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 43335,
"s": 43311,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 43350,
"s": 43335,
"text": "C++ Data Types"
},
{
"code": null,
"e": 43369,
"s": 43350,
"text": "Overriding in Java"
},
{
"code": null,
"e": 43396,
"s": 43369,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 43416,
"s": 43396,
"text": "Polymorphism in C++"
}
] |
How to click on a link in Selenium with python? | We can click on a link on page with the help of locators available in Selenium. Link text and partial link text are the locators generally used for clicking links. Both these locators work with the text available inside the anchor tags.
Link Text – The text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.
Link Text – The text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.
Partial link Text – The partial text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.
Partial link Text – The partial text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.
Coding Implementation with link text
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the link with the help of link text locator
driver.find_element_by_link_text("Company").click()
#to close the browser
driver.close()
Coding Implementation with partial link text.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the link with the help of partial link text locator
driver.find_element_by_partial_link_text("Privacy").click()
#to close the browser
driver.quit() | [
{
"code": null,
"e": 1299,
"s": 1062,
"text": "We can click on a link on page with the help of locators available in Selenium. Link text and partial link text are the locators generally used for clicking links. Both these locators work with the text available inside the anchor tags."
},
{
"code": null,
"e": 1498,
"s": 1299,
"text": "Link Text – The text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown."
},
{
"code": null,
"e": 1697,
"s": 1498,
"text": "Link Text – The text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown."
},
{
"code": null,
"e": 1912,
"s": 1697,
"text": "Partial link Text – The partial text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown."
},
{
"code": null,
"e": 2127,
"s": 1912,
"text": "Partial link Text – The partial text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown."
},
{
"code": null,
"e": 2164,
"s": 2127,
"text": "Coding Implementation with link text"
},
{
"code": null,
"e": 2740,
"s": 2164,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke #actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the link with the help of link text locator\ndriver.find_element_by_link_text(\"Company\").click()\n#to close the browser\ndriver.close()"
},
{
"code": null,
"e": 2786,
"s": 2740,
"text": "Coding Implementation with partial link text."
},
{
"code": null,
"e": 3377,
"s": 2786,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke #actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the link with the help of partial link text locator\ndriver.find_element_by_partial_link_text(\"Privacy\").click()\n#to close the browser\ndriver.quit()"
}
] |
How to match underscore in a MySQL String? | To match underscore in a MySQL string, you can use the below syntax −
select *from yourTableName where yourColumnName LIKE '%\_%';
Let us first create a table −
mysql> create table DemoTable
(
ClientId varchar(200)
);
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('CLI_101');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('CLI1110');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('_CLI102');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('CLI103_');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('CLI1111');
Query OK, 1 row affected (0.16 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+
| ClientId |
+----------+
| CLI_101 |
| CLI1110 |
| _CLI102 |
| CLI103_ |
| CLI1111 |
+----------+
5 rows in set (0.00 sec)
Here is the query to match underscore in String using LIKE −
mysql> select *from DemoTable where ClientId LIKE '%\_%';
This will produce the following output displaying the strings with underscore −
+----------+
| ClientId |
+----------+
| CLI_101 |
| _CLI102 |
| CLI103_ |
+----------+
3 rows in set (0.00 sec)
You can use alternate query −
mysql> select *from DemoTable where ClientId REGEXP '_';
This will produce the following output −
+----------+
| ClientId |
+----------+
| CLI_101 |
| _CLI102 |
| CLI103_ |
+----------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "To match underscore in a MySQL string, you can use the below syntax −"
},
{
"code": null,
"e": 1193,
"s": 1132,
"text": "select *from yourTableName where yourColumnName LIKE '%\\_%';"
},
{
"code": null,
"e": 1223,
"s": 1193,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1320,
"s": 1223,
"text": "mysql> create table DemoTable\n(\n ClientId varchar(200)\n);\nQuery OK, 0 rows affected (0.79 sec)"
},
{
"code": null,
"e": 1376,
"s": 1320,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1796,
"s": 1376,
"text": "mysql> insert into DemoTable values('CLI_101');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('CLI1110');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('_CLI102');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values('CLI103_');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('CLI1111');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1882,
"s": 1796,
"text": "Following is the query to display all records from the table using select statement −"
},
{
"code": null,
"e": 1913,
"s": 1882,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1954,
"s": 1913,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2096,
"s": 1954,
"text": "+----------+\n| ClientId |\n+----------+\n| CLI_101 |\n| CLI1110 |\n| _CLI102 |\n| CLI103_ |\n| CLI1111 |\n+----------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2157,
"s": 2096,
"text": "Here is the query to match underscore in String using LIKE −"
},
{
"code": null,
"e": 2215,
"s": 2157,
"text": "mysql> select *from DemoTable where ClientId LIKE '%\\_%';"
},
{
"code": null,
"e": 2295,
"s": 2215,
"text": "This will produce the following output displaying the strings with underscore −"
},
{
"code": null,
"e": 2411,
"s": 2295,
"text": "+----------+\n| ClientId |\n+----------+\n| CLI_101 |\n| _CLI102 |\n| CLI103_ |\n+----------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2441,
"s": 2411,
"text": "You can use alternate query −"
},
{
"code": null,
"e": 2498,
"s": 2441,
"text": "mysql> select *from DemoTable where ClientId REGEXP '_';"
},
{
"code": null,
"e": 2539,
"s": 2498,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2655,
"s": 2539,
"text": "+----------+\n| ClientId |\n+----------+\n| CLI_101 |\n| _CLI102 |\n| CLI103_ |\n+----------+\n3 rows in set (0.00 sec)"
}
] |
Apache HttpClient - Multipart Upload | Using HttpClient, we can perform Multipart upload, i.e., we can upload larger objects in
smaller parts. In this chapter, we demonstrate the multipart upload in HTTP client by uploading a simple text file.
In general, any multipart upload contains three parts.
Initiation of the upload
Initiation of the upload
Uploading the object parts
Uploading the object parts
Completing the Multipart upload
Completing the Multipart upload
For the multipart upload using HttpClient, we need to follow the below steps −
Create a multipart builder.
Create a multipart builder.
Add desired parts to it.
Add desired parts to it.
Complete the build and obtain a multipart HttpEntity.
Complete the build and obtain a multipart HttpEntity.
Build request by setting the above muti-part entity.
Build request by setting the above muti-part entity.
Execute the request.
Execute the request.
Following are the steps to upload a multipart entity using the HttpClient library.
The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object −
//Creating CloseableHttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
FileBody class represents the binary body part backed by a file. Instantiate this class by passing a File object and a ContentType object representing the type of the content.
//Creating a File object
File file = new File("sample.txt");
//Creating the FileBody object
FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);
The MultipartEntityBuilder class is used to build the multi-part HttpEntity object. Create its object using the create() method (of the same class).
//Creating the MultipartEntityBuilder
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
A MultipartEntityBuilder has three modes: STRICT, RFC6532, and BROWSER_COMPATIBLE. Set it to the desired mode using the setMode() method.
//Setting the mode
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
Using the methods addTextBody(), addPart() and, addBinaryBody(), you can add simple text, files, streams, and other objects to a MultipartBuilder. Add the desired contents using these methods.
//Adding text
entitybuilder.addTextBody("sample_text", "This is the text part of our file");
//Adding a file
entitybuilder.addBinaryBody("image", new File("logo.png"));
You can build all these parts to a single entity using the build() method of the MultipartEntityBuilder class. Using this method, build all the parts into a single HttpEntity.
//Building a single entity using the parts
HttpEntity mutiPartHttpEntity = entityBuilder.build();
The class RequestBuilder is used to build request by adding parameters to it. If the request is of type PUT or POST, it adds the parameters to the request as URL encoded entity.
Create a RequestBuilder object (of type POST) using the post() method. And pass the Uri
to which you wanted to send the request it as a parameter.
//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");
Set the above created multipart entity to the RequestBuilder using the setEntity() method of the RequestBuilder class.
//Setting the entity object to the RequestBuilder
reqbuilder.setEntity(mutiPartHttpEntity);
Build a HttpUriRequest request object using the build() method of the RequestBuilder class.
//Building the request
HttpUriRequest multipartRequest = reqbuilder.build();
Using the execute() method, execute the request built in the previous step (bypassing the request as a parameter to this method).
//Executing the request
HttpResponse httpresponse = httpclient.execute(multipartRequest);
Following example demonstrates how to send a multipart request using the HttpClient library. In this example, we are trying to send a multipart request backed by a file.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
public class MultipartUploadExample {
public static void main(String args[]) throws Exception{
//Creating CloseableHttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
//Creating a file object
File file = new File("sample.txt");
//Creating the FileBody object
FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);
//Creating the MultipartEntityBuilder
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
//Setting the mode
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//Adding text
entitybuilder.addTextBody("sample_text", "This is the text part of our file");
//Adding a file
entitybuilder.addBinaryBody("image", new File("logo.png"));
//Building a single entity using the parts
HttpEntity mutiPartHttpEntity = entitybuilder.build();
//Building the RequestBuilder request object
RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");
//Set the entity object to the RequestBuilder
reqbuilder.setEntity(mutiPartHttpEntity);
//Building the request
HttpUriRequest multipartRequest = reqbuilder.build();
//Executing the request
HttpResponse httpresponse = httpclient.execute(multipartRequest);
//Printing the status and the contents of the response
System.out.println(EntityUtils.toString(httpresponse.getEntity()));
System.out.println(httpresponse.getStatusLine());
}
}
On executing, the above program generates the following output −
{
"args": {},
"data": "",
"files": {
"image": "data:application/octets66PohrH3IWNk1FzpohfdXPIfv9X3490FGcuXsHn9X0piCwomF/xdgADZ9GsfSyvLYAAAAAE
lFTkSuQmCC"
},
"form": {
"sample_text": "This is the text part of our file"
},
"headers": {
"Accept-Encoding": "gzip,deflate",
"Connection": "close",
"Content-Length": "11104",
"Content-Type": "multipart/form-data;
boundary=UFJbPHT7mTwpVq70LpZgCi5I2nvxd1g-I8Rt",
"Host": "httpbin.org",
"User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)"
},
"json": null,
"origin": "117.216.245.180",
"url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2032,
"s": 1827,
"text": "Using HttpClient, we can perform Multipart upload, i.e., we can upload larger objects in\nsmaller parts. In this chapter, we demonstrate the multipart upload in HTTP client by uploading a simple text file."
},
{
"code": null,
"e": 2087,
"s": 2032,
"text": "In general, any multipart upload contains three parts."
},
{
"code": null,
"e": 2112,
"s": 2087,
"text": "Initiation of the upload"
},
{
"code": null,
"e": 2137,
"s": 2112,
"text": "Initiation of the upload"
},
{
"code": null,
"e": 2164,
"s": 2137,
"text": "Uploading the object parts"
},
{
"code": null,
"e": 2191,
"s": 2164,
"text": "Uploading the object parts"
},
{
"code": null,
"e": 2223,
"s": 2191,
"text": "Completing the Multipart upload"
},
{
"code": null,
"e": 2255,
"s": 2223,
"text": "Completing the Multipart upload"
},
{
"code": null,
"e": 2334,
"s": 2255,
"text": "For the multipart upload using HttpClient, we need to follow the below steps −"
},
{
"code": null,
"e": 2362,
"s": 2334,
"text": "Create a multipart builder."
},
{
"code": null,
"e": 2390,
"s": 2362,
"text": "Create a multipart builder."
},
{
"code": null,
"e": 2415,
"s": 2390,
"text": "Add desired parts to it."
},
{
"code": null,
"e": 2440,
"s": 2415,
"text": "Add desired parts to it."
},
{
"code": null,
"e": 2494,
"s": 2440,
"text": "Complete the build and obtain a multipart HttpEntity."
},
{
"code": null,
"e": 2548,
"s": 2494,
"text": "Complete the build and obtain a multipart HttpEntity."
},
{
"code": null,
"e": 2601,
"s": 2548,
"text": "Build request by setting the above muti-part entity."
},
{
"code": null,
"e": 2654,
"s": 2601,
"text": "Build request by setting the above muti-part entity."
},
{
"code": null,
"e": 2675,
"s": 2654,
"text": "Execute the request."
},
{
"code": null,
"e": 2696,
"s": 2675,
"text": "Execute the request."
},
{
"code": null,
"e": 2779,
"s": 2696,
"text": "Following are the steps to upload a multipart entity using the HttpClient library."
},
{
"code": null,
"e": 2994,
"s": 2779,
"text": "The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object −"
},
{
"code": null,
"e": 3095,
"s": 2994,
"text": "//Creating CloseableHttpClient object\nCloseableHttpClient httpclient = HttpClients.createDefault();\n"
},
{
"code": null,
"e": 3271,
"s": 3095,
"text": "FileBody class represents the binary body part backed by a file. Instantiate this class by passing a File object and a ContentType object representing the type of the content."
},
{
"code": null,
"e": 3433,
"s": 3271,
"text": "//Creating a File object\nFile file = new File(\"sample.txt\");\n\n//Creating the FileBody object\nFileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);\n"
},
{
"code": null,
"e": 3582,
"s": 3433,
"text": "The MultipartEntityBuilder class is used to build the multi-part HttpEntity object. Create its object using the create() method (of the same class)."
},
{
"code": null,
"e": 3693,
"s": 3582,
"text": "//Creating the MultipartEntityBuilder\nMultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();\n"
},
{
"code": null,
"e": 3831,
"s": 3693,
"text": "A MultipartEntityBuilder has three modes: STRICT, RFC6532, and BROWSER_COMPATIBLE. Set it to the desired mode using the setMode() method."
},
{
"code": null,
"e": 3912,
"s": 3831,
"text": "//Setting the mode\nentitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n"
},
{
"code": null,
"e": 4105,
"s": 3912,
"text": "Using the methods addTextBody(), addPart() and, addBinaryBody(), you can add simple text, files, streams, and other objects to a MultipartBuilder. Add the desired contents using these methods."
},
{
"code": null,
"e": 4275,
"s": 4105,
"text": "//Adding text\nentitybuilder.addTextBody(\"sample_text\", \"This is the text part of our file\");\n//Adding a file\nentitybuilder.addBinaryBody(\"image\", new File(\"logo.png\"));\n"
},
{
"code": null,
"e": 4451,
"s": 4275,
"text": "You can build all these parts to a single entity using the build() method of the MultipartEntityBuilder class. Using this method, build all the parts into a single HttpEntity."
},
{
"code": null,
"e": 4551,
"s": 4451,
"text": "//Building a single entity using the parts\nHttpEntity mutiPartHttpEntity = entityBuilder.build(); \n"
},
{
"code": null,
"e": 4729,
"s": 4551,
"text": "The class RequestBuilder is used to build request by adding parameters to it. If the request is of type PUT or POST, it adds the parameters to the request as URL encoded entity."
},
{
"code": null,
"e": 4876,
"s": 4729,
"text": "Create a RequestBuilder object (of type POST) using the post() method. And pass the Uri\nto which you wanted to send the request it as a parameter."
},
{
"code": null,
"e": 4988,
"s": 4876,
"text": "//Building the post request object\nRequestBuilder reqbuilder = RequestBuilder.post(\"http://httpbin.org/post\");\n"
},
{
"code": null,
"e": 5107,
"s": 4988,
"text": "Set the above created multipart entity to the RequestBuilder using the setEntity() method of the RequestBuilder class."
},
{
"code": null,
"e": 5200,
"s": 5107,
"text": "//Setting the entity object to the RequestBuilder\nreqbuilder.setEntity(mutiPartHttpEntity);\n"
},
{
"code": null,
"e": 5292,
"s": 5200,
"text": "Build a HttpUriRequest request object using the build() method of the RequestBuilder class."
},
{
"code": null,
"e": 5370,
"s": 5292,
"text": "//Building the request\nHttpUriRequest multipartRequest = reqbuilder.build();\n"
},
{
"code": null,
"e": 5500,
"s": 5370,
"text": "Using the execute() method, execute the request built in the previous step (bypassing the request as a parameter to this method)."
},
{
"code": null,
"e": 5591,
"s": 5500,
"text": "//Executing the request\nHttpResponse httpresponse = httpclient.execute(multipartRequest);\n"
},
{
"code": null,
"e": 5761,
"s": 5591,
"text": "Following example demonstrates how to send a multipart request using the HttpClient library. In this example, we are trying to send a multipart request backed by a file."
},
{
"code": null,
"e": 7931,
"s": 5761,
"text": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpUriRequest;\nimport org.apache.http.client.methods.RequestBuilder;\nimport org.apache.http.entity.ContentType;\nimport org.apache.http.entity.mime.HttpMultipartMode;\nimport org.apache.http.entity.mime.MultipartEntityBuilder;\nimport org.apache.http.entity.mime.content.FileBody;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\n\npublic class MultipartUploadExample {\n \n public static void main(String args[]) throws Exception{\n\n //Creating CloseableHttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n \n //Creating a file object\n File file = new File(\"sample.txt\");\n\n //Creating the FileBody object\n FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);\n\n //Creating the MultipartEntityBuilder\n MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();\n\n //Setting the mode\n entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n\n //Adding text\n entitybuilder.addTextBody(\"sample_text\", \"This is the text part of our file\");\n\n //Adding a file\n entitybuilder.addBinaryBody(\"image\", new File(\"logo.png\"));\n\n //Building a single entity using the parts\n HttpEntity mutiPartHttpEntity = entitybuilder.build();\n\n //Building the RequestBuilder request object\n RequestBuilder reqbuilder = RequestBuilder.post(\"http://httpbin.org/post\");\n\n //Set the entity object to the RequestBuilder\n reqbuilder.setEntity(mutiPartHttpEntity);\n\n //Building the request\n HttpUriRequest multipartRequest = reqbuilder.build();\n\n //Executing the request\n HttpResponse httpresponse = httpclient.execute(multipartRequest);\n\n //Printing the status and the contents of the response\n System.out.println(EntityUtils.toString(httpresponse.getEntity()));\n System.out.println(httpresponse.getStatusLine());\n }\n} "
},
{
"code": null,
"e": 7996,
"s": 7931,
"text": "On executing, the above program generates the following output −"
},
{
"code": null,
"e": 8672,
"s": 7996,
"text": "{\n \"args\": {},\n \"data\": \"\",\n \"files\": {\n \"image\": \"data:application/octets66PohrH3IWNk1FzpohfdXPIfv9X3490FGcuXsHn9X0piCwomF/xdgADZ9GsfSyvLYAAAAAE\n lFTkSuQmCC\"\n },\n \"form\": {\n \"sample_text\": \"This is the text part of our file\"\n },\n \"headers\": {\n \"Accept-Encoding\": \"gzip,deflate\",\n \"Connection\": \"close\",\n \"Content-Length\": \"11104\", \n \"Content-Type\": \"multipart/form-data;\n boundary=UFJbPHT7mTwpVq70LpZgCi5I2nvxd1g-I8Rt\",\n \"Host\": \"httpbin.org\",\n \"User-Agent\": \"Apache-HttpClient/4.5.6 (Java/1.8.0_91)\"\n },\n \"json\": null,\n \"origin\": \"117.216.245.180\",\n \"url\": \"http://httpbin.org/post\"\n}\nHTTP/1.1 200 OK\n"
},
{
"code": null,
"e": 8707,
"s": 8672,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8726,
"s": 8707,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8761,
"s": 8726,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8782,
"s": 8761,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 8815,
"s": 8782,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8828,
"s": 8815,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 8863,
"s": 8828,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8881,
"s": 8863,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 8914,
"s": 8881,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8932,
"s": 8914,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 8965,
"s": 8932,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8983,
"s": 8965,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 8990,
"s": 8983,
"text": " Print"
},
{
"code": null,
"e": 9001,
"s": 8990,
"text": " Add Notes"
}
] |
Easy Stylish Chip Button in Bottom Navigation Bar in Android - GeeksforGeeks | 18 Feb, 2021
We all have come across apps that have a Bottom Navigation Bar. Some popular examples include Instagram, Snapchat, etc. In this article, let’s learn how to implement an easy stylish functional Bottom Navigation Bar in the Android app. For Creating a Basic Bottom Navigation bar refer to Bottom Navigation Bar in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
It allows the user to navigate from one fragment to another easily.
It makes it easy to view all other screens present in the app.
User can check it easily which screen they are working at the moment.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding the dependency to the build.gradle(:app) file
implementation ‘com.ismaeldivita.chipnavigation:chip-navigation-bar:1.3.4’
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#EEEEEE" tools:context=".MainActivity"> <TextView android:id="@+id/text_main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Welcome!" android:textColor="#000" android:textSize="20sp" /> <com.ismaeldivita.chipnavigation.ChipNavigationBar android:id="@+id/bottom_nav_bar" android:layout_width="match_parent" android:layout_height="60dp" android:layout_alignParentBottom="true" android:layout_gravity="bottom" android:background="#fff" android:fadingEdge="horizontal" app:cnb_menuResource="@menu/menu" /> </RelativeLayout>
This is how the activity_main.xml looks like:
Step 4: Creating a menu for the Chip Navigation Bar
Go to the app > res > right-click > New > Android Resource File and in the pop-up screen choose Resource type as Menu and keep the file name as menu. Below is the code for the menu.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/nav_near" android:icon="@drawable/ic_home_black_24dp" android:title="Home" app:cnb_iconColor="#2196F3"/> <item android:id="@+id/nav_new_chat" android:icon="@drawable/ic_message_black_24dp" android:title="Message" app:cnb_iconColor="#F44336"/> <item android:id="@+id/nav_profile" android:icon="@drawable/ic_notifications_black_24dp" android:title="Notify" app:cnb_iconColor="#4CAF50"/> <item android:id="@+id/nav_settings" android:icon="@drawable/ic_person_black_24dp" android:title="Profile" app:cnb_iconColor="#FF9800"/> </menu>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import com.ismaeldivita.chipnavigation.ChipNavigationBar; public class MainActivity extends AppCompatActivity { ChipNavigationBar chipNavigationBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); chipNavigationBar = findViewById(R.id.bottom_nav_bar); }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 24749,
"s": 24721,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 25235,
"s": 24749,
"text": "We all have come across apps that have a Bottom Navigation Bar. Some popular examples include Instagram, Snapchat, etc. In this article, let’s learn how to implement an easy stylish functional Bottom Navigation Bar in the Android app. For Creating a Basic Bottom Navigation bar refer to Bottom Navigation Bar in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25303,
"s": 25235,
"text": "It allows the user to navigate from one fragment to another easily."
},
{
"code": null,
"e": 25366,
"s": 25303,
"text": "It makes it easy to view all other screens present in the app."
},
{
"code": null,
"e": 25436,
"s": 25366,
"text": "User can check it easily which screen they are working at the moment."
},
{
"code": null,
"e": 25465,
"s": 25436,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25627,
"s": 25465,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 25688,
"s": 25627,
"text": "Step 2: Adding the dependency to the build.gradle(:app) file"
},
{
"code": null,
"e": 25763,
"s": 25688,
"text": "implementation ‘com.ismaeldivita.chipnavigation:chip-navigation-bar:1.3.4’"
},
{
"code": null,
"e": 25811,
"s": 25763,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 25954,
"s": 25811,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 25958,
"s": 25954,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/rl_layout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#EEEEEE\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/text_main\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Welcome!\" android:textColor=\"#000\" android:textSize=\"20sp\" /> <com.ismaeldivita.chipnavigation.ChipNavigationBar android:id=\"@+id/bottom_nav_bar\" android:layout_width=\"match_parent\" android:layout_height=\"60dp\" android:layout_alignParentBottom=\"true\" android:layout_gravity=\"bottom\" android:background=\"#fff\" android:fadingEdge=\"horizontal\" app:cnb_menuResource=\"@menu/menu\" /> </RelativeLayout>",
"e": 27030,
"s": 25958,
"text": null
},
{
"code": null,
"e": 27076,
"s": 27030,
"text": "This is how the activity_main.xml looks like:"
},
{
"code": null,
"e": 27128,
"s": 27076,
"text": "Step 4: Creating a menu for the Chip Navigation Bar"
},
{
"code": null,
"e": 27319,
"s": 27128,
"text": "Go to the app > res > right-click > New > Android Resource File and in the pop-up screen choose Resource type as Menu and keep the file name as menu. Below is the code for the menu.xml file."
},
{
"code": null,
"e": 27323,
"s": 27319,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\"> <item android:id=\"@+id/nav_near\" android:icon=\"@drawable/ic_home_black_24dp\" android:title=\"Home\" app:cnb_iconColor=\"#2196F3\"/> <item android:id=\"@+id/nav_new_chat\" android:icon=\"@drawable/ic_message_black_24dp\" android:title=\"Message\" app:cnb_iconColor=\"#F44336\"/> <item android:id=\"@+id/nav_profile\" android:icon=\"@drawable/ic_notifications_black_24dp\" android:title=\"Notify\" app:cnb_iconColor=\"#4CAF50\"/> <item android:id=\"@+id/nav_settings\" android:icon=\"@drawable/ic_person_black_24dp\" android:title=\"Profile\" app:cnb_iconColor=\"#FF9800\"/> </menu>",
"e": 28172,
"s": 27323,
"text": null
},
{
"code": null,
"e": 28220,
"s": 28172,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 28410,
"s": 28220,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 28415,
"s": 28410,
"text": "Java"
},
{
"code": "import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import com.ismaeldivita.chipnavigation.ChipNavigationBar; public class MainActivity extends AppCompatActivity { ChipNavigationBar chipNavigationBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); chipNavigationBar = findViewById(R.id.bottom_nav_bar); }}",
"e": 28872,
"s": 28415,
"text": null
},
{
"code": null,
"e": 28880,
"s": 28872,
"text": "android"
},
{
"code": null,
"e": 28904,
"s": 28880,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28912,
"s": 28904,
"text": "Android"
},
{
"code": null,
"e": 28917,
"s": 28912,
"text": "Java"
},
{
"code": null,
"e": 28936,
"s": 28917,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28941,
"s": 28936,
"text": "Java"
},
{
"code": null,
"e": 28949,
"s": 28941,
"text": "Android"
},
{
"code": null,
"e": 29047,
"s": 28949,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29056,
"s": 29047,
"text": "Comments"
},
{
"code": null,
"e": 29069,
"s": 29056,
"text": "Old Comments"
},
{
"code": null,
"e": 29108,
"s": 29069,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29158,
"s": 29108,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 29209,
"s": 29158,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 29247,
"s": 29209,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 29289,
"s": 29247,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29304,
"s": 29289,
"text": "Arrays in Java"
},
{
"code": null,
"e": 29348,
"s": 29304,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 29370,
"s": 29348,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 29395,
"s": 29370,
"text": "Reverse a string in Java"
}
] |
Ngx-Bootstrap - Pagination | ngx-bootstrap pagination component provides pagination links or a pager component to your site or component.
pagination
pagination
align − boolean, if true aligns each link to the sides of pager
align − boolean, if true aligns each link to the sides of pager
boundaryLinks − boolean, if false first and last buttons will be hidden
boundaryLinks − boolean, if false first and last buttons will be hidden
customFirstTemplate − TemplateRef<PaginationLinkContext>, custom template for first link
customFirstTemplate − TemplateRef<PaginationLinkContext>, custom template for first link
customLastTemplate − TemplateRef<PaginationLinkContext>, custom template for last link
customLastTemplate − TemplateRef<PaginationLinkContext>, custom template for last link
customNextTemplate − TemplateRef<PaginationLinkContext>, custom template for next link
customNextTemplate − TemplateRef<PaginationLinkContext>, custom template for next link
customPageTemplate − TemplateRef<PaginationLinkContext>, custom template for page link
customPageTemplate − TemplateRef<PaginationLinkContext>, custom template for page link
customPreviousTemplate − TemplateRef<PaginationLinkContext>, custom template for previous link
customPreviousTemplate − TemplateRef<PaginationLinkContext>, custom template for previous link
directionLinks − boolean, if false previous and next buttons will be hidden
directionLinks − boolean, if false previous and next buttons will be hidden
disabled − boolean, if true pagination component will be disabled
disabled − boolean, if true pagination component will be disabled
firstText − boolean, first button text
firstText − boolean, first button text
itemsPerPage − number, maximum number of items per page. If value less than 1 will display all items on one page
itemsPerPage − number, maximum number of items per page. If value less than 1 will display all items on one page
lastText − string, last button text
lastText − string, last button text
maxSize − number, limit number for page links in pager
maxSize − number, limit number for page links in pager
nextText − string, next button text
nextText − string, next button text
pageBtnClass − string, add class to <li>
pageBtnClass − string, add class to <li>
previousText − string, previous button text
previousText − string, previous button text
rotate − boolean, if true current page will in the middle of pages list
rotate − boolean, if true current page will in the middle of pages list
totalItems − number, total number of items in all pages
totalItems − number, total number of items in all pages
numPages − fired when total pages count changes, $event:number equals to total pages count.
numPages − fired when total pages count changes, $event:number equals to total pages count.
pageChanged − fired when page was changed, $event:{page, itemsPerPage} equals to object with current page index and number of items per page.
pageChanged − fired when page was changed, $event:{page, itemsPerPage} equals to object with current page index and number of items per page.
As we're going to use a pagination, We've to update app.module.ts used in ngx-bootstrap Modals chapter to use PaginationModule and PaginationConfig.
Update app.module.ts to use the PaginationModule and PaginationConfig.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { AccordionModule } from 'ngx-bootstrap/accordion';
import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';
import { ButtonsModule } from 'ngx-bootstrap/buttons';
import { FormsModule } from '@angular/forms';
import { CarouselModule } from 'ngx-bootstrap/carousel';
import { CollapseModule } from 'ngx-bootstrap/collapse';
import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';
import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';
import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserAnimationsModule,
BrowserModule,
AccordionModule,
AlertModule,
ButtonsModule,
FormsModule,
CarouselModule,
CollapseModule,
BsDatepickerModule.forRoot(),
BsDropdownModule,
ModalModule,
PaginationModule
],
providers: [AlertConfig,
BsDatepickerConfig,
BsDropdownConfig,
BsModalService,
PaginationConfig],
bootstrap: [AppComponent]
})
export class AppModule { }
Update test.component.html to use the modal.
test.component.html
<div class="row">
<div class="col-xs-12 col-12">
<div class="content-wrapper">
<p class="content-item" *ngFor="let content of returnedArray">{{content}}</p>
</div>
<pagination [boundaryLinks]="showBoundaryLinks"
[directionLinks]="showDirectionLinks"
[totalItems]="contentArray.length"
[itemsPerPage]="5"
(pageChanged)="pageChanged($event)"></pagination>
</div>
</div>
<div>
<div class="checkbox">
<label><input type="checkbox" [(ngModel)]="showBoundaryLinks">Show Boundary Links</label>
<br/>
<label><input type="checkbox" [(ngModel)]="showDirectionLinks">Show Direction Links</label>
</div>
</div>
Update test.component.ts for corresponding variables and methods.
test.component.ts
import { Component, OnInit } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { PageChangedEvent } from 'ngx-bootstrap/pagination';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
contentArray: string[] = new Array(50).fill('');
returnedArray: string[];
showBoundaryLinks: boolean = true;
showDirectionLinks: boolean = true;
constructor() {}
pageChanged(event: PageChangedEvent): void {
const startItem = (event.page - 1) * event.itemsPerPage;
const endItem = event.page * event.itemsPerPage;
this.returnedArray = this.contentArray.slice(startItem, endItem);
}
ngOnInit(): void {
this.contentArray = this.contentArray.map((v: string, i: number) => {
return 'Line '+ (i + 1);
});
this.returnedArray = this.contentArray.slice(0, 5);
}
}
Run the following command to start the angular server.
ng serve
Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2209,
"s": 2100,
"text": "ngx-bootstrap pagination component provides pagination links or a pager component to your site or component."
},
{
"code": null,
"e": 2220,
"s": 2209,
"text": "pagination"
},
{
"code": null,
"e": 2231,
"s": 2220,
"text": "pagination"
},
{
"code": null,
"e": 2295,
"s": 2231,
"text": "align − boolean, if true aligns each link to the sides of pager"
},
{
"code": null,
"e": 2359,
"s": 2295,
"text": "align − boolean, if true aligns each link to the sides of pager"
},
{
"code": null,
"e": 2431,
"s": 2359,
"text": "boundaryLinks − boolean, if false first and last buttons will be hidden"
},
{
"code": null,
"e": 2503,
"s": 2431,
"text": "boundaryLinks − boolean, if false first and last buttons will be hidden"
},
{
"code": null,
"e": 2592,
"s": 2503,
"text": "customFirstTemplate − TemplateRef<PaginationLinkContext>, custom template for first link"
},
{
"code": null,
"e": 2681,
"s": 2592,
"text": "customFirstTemplate − TemplateRef<PaginationLinkContext>, custom template for first link"
},
{
"code": null,
"e": 2768,
"s": 2681,
"text": "customLastTemplate − TemplateRef<PaginationLinkContext>, custom template for last link"
},
{
"code": null,
"e": 2855,
"s": 2768,
"text": "customLastTemplate − TemplateRef<PaginationLinkContext>, custom template for last link"
},
{
"code": null,
"e": 2942,
"s": 2855,
"text": "customNextTemplate − TemplateRef<PaginationLinkContext>, custom template for next link"
},
{
"code": null,
"e": 3029,
"s": 2942,
"text": "customNextTemplate − TemplateRef<PaginationLinkContext>, custom template for next link"
},
{
"code": null,
"e": 3116,
"s": 3029,
"text": "customPageTemplate − TemplateRef<PaginationLinkContext>, custom template for page link"
},
{
"code": null,
"e": 3203,
"s": 3116,
"text": "customPageTemplate − TemplateRef<PaginationLinkContext>, custom template for page link"
},
{
"code": null,
"e": 3298,
"s": 3203,
"text": "customPreviousTemplate − TemplateRef<PaginationLinkContext>, custom template for previous link"
},
{
"code": null,
"e": 3393,
"s": 3298,
"text": "customPreviousTemplate − TemplateRef<PaginationLinkContext>, custom template for previous link"
},
{
"code": null,
"e": 3469,
"s": 3393,
"text": "directionLinks − boolean, if false previous and next buttons will be hidden"
},
{
"code": null,
"e": 3545,
"s": 3469,
"text": "directionLinks − boolean, if false previous and next buttons will be hidden"
},
{
"code": null,
"e": 3611,
"s": 3545,
"text": "disabled − boolean, if true pagination component will be disabled"
},
{
"code": null,
"e": 3677,
"s": 3611,
"text": "disabled − boolean, if true pagination component will be disabled"
},
{
"code": null,
"e": 3716,
"s": 3677,
"text": "firstText − boolean, first button text"
},
{
"code": null,
"e": 3755,
"s": 3716,
"text": "firstText − boolean, first button text"
},
{
"code": null,
"e": 3868,
"s": 3755,
"text": "itemsPerPage − number, maximum number of items per page. If value less than 1 will display all items on one page"
},
{
"code": null,
"e": 3981,
"s": 3868,
"text": "itemsPerPage − number, maximum number of items per page. If value less than 1 will display all items on one page"
},
{
"code": null,
"e": 4017,
"s": 3981,
"text": "lastText − string, last button text"
},
{
"code": null,
"e": 4053,
"s": 4017,
"text": "lastText − string, last button text"
},
{
"code": null,
"e": 4108,
"s": 4053,
"text": "maxSize − number, limit number for page links in pager"
},
{
"code": null,
"e": 4163,
"s": 4108,
"text": "maxSize − number, limit number for page links in pager"
},
{
"code": null,
"e": 4199,
"s": 4163,
"text": "nextText − string, next button text"
},
{
"code": null,
"e": 4235,
"s": 4199,
"text": "nextText − string, next button text"
},
{
"code": null,
"e": 4276,
"s": 4235,
"text": "pageBtnClass − string, add class to <li>"
},
{
"code": null,
"e": 4317,
"s": 4276,
"text": "pageBtnClass − string, add class to <li>"
},
{
"code": null,
"e": 4361,
"s": 4317,
"text": "previousText − string, previous button text"
},
{
"code": null,
"e": 4405,
"s": 4361,
"text": "previousText − string, previous button text"
},
{
"code": null,
"e": 4477,
"s": 4405,
"text": "rotate − boolean, if true current page will in the middle of pages list"
},
{
"code": null,
"e": 4549,
"s": 4477,
"text": "rotate − boolean, if true current page will in the middle of pages list"
},
{
"code": null,
"e": 4605,
"s": 4549,
"text": "totalItems − number, total number of items in all pages"
},
{
"code": null,
"e": 4661,
"s": 4605,
"text": "totalItems − number, total number of items in all pages"
},
{
"code": null,
"e": 4753,
"s": 4661,
"text": "numPages − fired when total pages count changes, $event:number equals to total pages count."
},
{
"code": null,
"e": 4845,
"s": 4753,
"text": "numPages − fired when total pages count changes, $event:number equals to total pages count."
},
{
"code": null,
"e": 4987,
"s": 4845,
"text": "pageChanged − fired when page was changed, $event:{page, itemsPerPage} equals to object with current page index and number of items per page."
},
{
"code": null,
"e": 5129,
"s": 4987,
"text": "pageChanged − fired when page was changed, $event:{page, itemsPerPage} equals to object with current page index and number of items per page."
},
{
"code": null,
"e": 5278,
"s": 5129,
"text": "As we're going to use a pagination, We've to update app.module.ts used in ngx-bootstrap Modals chapter to use PaginationModule and PaginationConfig."
},
{
"code": null,
"e": 5349,
"s": 5278,
"text": "Update app.module.ts to use the PaginationModule and PaginationConfig."
},
{
"code": null,
"e": 5363,
"s": 5349,
"text": "app.module.ts"
},
{
"code": null,
"e": 6785,
"s": 5363,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 6830,
"s": 6785,
"text": "Update test.component.html to use the modal."
},
{
"code": null,
"e": 6850,
"s": 6830,
"text": "test.component.html"
},
{
"code": null,
"e": 7544,
"s": 6850,
"text": "<div class=\"row\">\n <div class=\"col-xs-12 col-12\">\n <div class=\"content-wrapper\">\n <p class=\"content-item\" *ngFor=\"let content of returnedArray\">{{content}}</p>\n </div>\n <pagination [boundaryLinks]=\"showBoundaryLinks\" \n [directionLinks]=\"showDirectionLinks\" \n [totalItems]=\"contentArray.length\"\n [itemsPerPage]=\"5\"\n (pageChanged)=\"pageChanged($event)\"></pagination>\n </div>\n</div>\n<div>\n <div class=\"checkbox\">\n <label><input type=\"checkbox\" [(ngModel)]=\"showBoundaryLinks\">Show Boundary Links</label>\n <br/>\n <label><input type=\"checkbox\" [(ngModel)]=\"showDirectionLinks\">Show Direction Links</label>\n </div>\n</div>"
},
{
"code": null,
"e": 7610,
"s": 7544,
"text": "Update test.component.ts for corresponding variables and methods."
},
{
"code": null,
"e": 7628,
"s": 7610,
"text": "test.component.ts"
},
{
"code": null,
"e": 8591,
"s": 7628,
"text": "import { Component, OnInit } from '@angular/core';\nimport { BsModalService } from 'ngx-bootstrap/modal';\nimport { PageChangedEvent } from 'ngx-bootstrap/pagination';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n contentArray: string[] = new Array(50).fill('');\n returnedArray: string[];\n showBoundaryLinks: boolean = true;\n showDirectionLinks: boolean = true;\n constructor() {}\n\n pageChanged(event: PageChangedEvent): void {\n const startItem = (event.page - 1) * event.itemsPerPage;\n const endItem = event.page * event.itemsPerPage;\n this.returnedArray = this.contentArray.slice(startItem, endItem);\n }\n ngOnInit(): void {\n this.contentArray = this.contentArray.map((v: string, i: number) => {\n return 'Line '+ (i + 1);\n });\n this.returnedArray = this.contentArray.slice(0, 5);\n }\n}"
},
{
"code": null,
"e": 8646,
"s": 8591,
"text": "Run the following command to start the angular server."
},
{
"code": null,
"e": 8656,
"s": 8646,
"text": "ng serve\n"
},
{
"code": null,
"e": 8775,
"s": 8656,
"text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output."
},
{
"code": null,
"e": 8782,
"s": 8775,
"text": " Print"
},
{
"code": null,
"e": 8793,
"s": 8782,
"text": " Add Notes"
}
] |
Send mail from your Gmail account using Python | In this article, we will see how we can send email with attachments using Python. To send mail, we do not need any external library. There is a module called SMTPlib, which comes with Python. It uses SMTP (Simple Mail Transfer Protocol) to send the mail. It creates SMTP client session objects for mailing.
SMTP needs valid source and destination email ids, and port numbers. The port number varies for different sites. As an example, for google the port is 587.
At first we need to import the module to send mail.
import smtplib
Here we are also using the MIME (Multipurpose Internet Mail Extension) module to make it more flexible. Using MIME header, we can store the sender and receiver information and some other details.
We are using Google's Gmail service to send mail. So we need some settings (if required) for google's security purposes. If those settings are not set up, then the following code may not work, if the google doesnot support the access from third-party app.
To allow the access, we need to set 'Less Secure App Access' settings in the google account. If the two step verification is on, we cannot use the less secure access.
To complete this setup, go to the Google's Admin Console, and search for the Less Secure App setup.
Create MIME
Add sender, receiver address into the MIME
Add the mail title into the MIME
Attach the body into the MIME
Start the SMTP session with valid port number with proper security features.
Login to the system.
Send mail and exit
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_content = '''Hello,
This is a simple mail. There is only text, no attachments are there The mail is sent using Python SMTP library.
Thank You
' ' '
#The mail addresses and password
sender_address = '[email protected]'
sender_pass = 'xxxxxxxx'
receiver_address = '[email protected]'
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'A test mail sent by Python. It has an attachment.' #The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')
D:\Python TP\Python 450\linux>python 327.Send_Mail.py
Mail Sent | [
{
"code": null,
"e": 1369,
"s": 1062,
"text": "In this article, we will see how we can send email with attachments using Python. To send mail, we do not need any external library. There is a module called SMTPlib, which comes with Python. It uses SMTP (Simple Mail Transfer Protocol) to send the mail. It creates SMTP client session objects for mailing."
},
{
"code": null,
"e": 1525,
"s": 1369,
"text": "SMTP needs valid source and destination email ids, and port numbers. The port number varies for different sites. As an example, for google the port is 587."
},
{
"code": null,
"e": 1577,
"s": 1525,
"text": "At first we need to import the module to send mail."
},
{
"code": null,
"e": 1593,
"s": 1577,
"text": "import smtplib\n"
},
{
"code": null,
"e": 1789,
"s": 1593,
"text": "Here we are also using the MIME (Multipurpose Internet Mail Extension) module to make it more flexible. Using MIME header, we can store the sender and receiver information and some other details."
},
{
"code": null,
"e": 2045,
"s": 1789,
"text": "We are using Google's Gmail service to send mail. So we need some settings (if required) for google's security purposes. If those settings are not set up, then the following code may not work, if the google doesnot support the access from third-party app."
},
{
"code": null,
"e": 2212,
"s": 2045,
"text": "To allow the access, we need to set 'Less Secure App Access' settings in the google account. If the two step verification is on, we cannot use the less secure access."
},
{
"code": null,
"e": 2312,
"s": 2212,
"text": "To complete this setup, go to the Google's Admin Console, and search for the Less Secure App setup."
},
{
"code": null,
"e": 2324,
"s": 2312,
"text": "Create MIME"
},
{
"code": null,
"e": 2367,
"s": 2324,
"text": "Add sender, receiver address into the MIME"
},
{
"code": null,
"e": 2400,
"s": 2367,
"text": "Add the mail title into the MIME"
},
{
"code": null,
"e": 2430,
"s": 2400,
"text": "Attach the body into the MIME"
},
{
"code": null,
"e": 2507,
"s": 2430,
"text": "Start the SMTP session with valid port number with proper security features."
},
{
"code": null,
"e": 2528,
"s": 2507,
"text": "Login to the system."
},
{
"code": null,
"e": 2547,
"s": 2528,
"text": "Send mail and exit"
},
{
"code": null,
"e": 3570,
"s": 2547,
"text": "import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nmail_content = '''Hello,\nThis is a simple mail. There is only text, no attachments are there The mail is sent using Python SMTP library.\nThank You\n' ' '\n#The mail addresses and password\nsender_address = '[email protected]'\nsender_pass = 'xxxxxxxx'\nreceiver_address = '[email protected]'\n#Setup the MIME\nmessage = MIMEMultipart()\nmessage['From'] = sender_address\nmessage['To'] = receiver_address\nmessage['Subject'] = 'A test mail sent by Python. It has an attachment.' #The subject line\n#The body and the attachments for the mail\nmessage.attach(MIMEText(mail_content, 'plain'))\n#Create SMTP session for sending the mail\nsession = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port\nsession.starttls() #enable security\nsession.login(sender_address, sender_pass) #login with mail_id and password\ntext = message.as_string()\nsession.sendmail(sender_address, receiver_address, text)\nsession.quit()\nprint('Mail Sent')"
},
{
"code": null,
"e": 3635,
"s": 3570,
"text": "D:\\Python TP\\Python 450\\linux>python 327.Send_Mail.py\nMail Sent\n"
}
] |
How to create Tab Layout in an Android App using Kotlin? | This example demonstrates how to create Tab Layout in an Android App using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#1db995">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tabLayout"
android:layout_centerInParent="true"
android:layout_marginTop="100dp"
tools:layout_editor_absoluteX="8dp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayout.TabLayoutOnPageChangeListener
class MainActivity : AppCompatActivity() {
lateinit var tabLayout: TabLayout
lateinit var viewPager: ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
tabLayout = findViewById(R.id.tabLayout)
viewPager = findViewById(R.id.viewPager)
tabLayout.addTab(tabLayout.newTab().setText("Football"))
tabLayout.addTab(tabLayout.newTab().setText("Cricket"))
tabLayout.addTab(tabLayout.newTab().setText("NBA"))
tabLayout.tabGravity = TabLayout.GRAVITY_FILL
val adapter = MyAdapter(this, supportFragmentManager,
tabLayout.tabCount)
viewPager.adapter = adapter
viewPager.addOnPageChangeListener(TabLayoutOnPageChangeListener(tabLayout))
tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
viewPager.currentItem = tab.position
}
override fun onTabUnselected(tab: TabLayout.Tab) {}
override fun onTabReselected(tab: TabLayout.Tab) {}
})
}
}
Step 4 − Create a new Adapter kotlin class (MyAdapter.kt) and add the following code −
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
@Suppress("DEPRECATION")
internal class MyAdapter(
var context: Context,
fm: FragmentManager,
var totalTabs: Int
) :
FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> {
Football()
}
1 -> {
Cricket()
}
2 -> {
NBA()
}
else -> getItem(position)
}
}
override fun getCount(): Int {
return totalTabs
}
}
Step 5 − Create 3 Fragment activities (Cricket, Football, NBA - You can have your name) and the following code −
Cricket.kt
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
class Cricket : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cricket, container, false)
}
}
fragment_cricket.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Cricket">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Cricket Fragment"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold" />
</FrameLayout>
Football.kt
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
class Football : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_football, container, false)
}
}
fragment_footbal.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Football">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Football Fragment"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold" />
</FrameLayout>
NBA.kt
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class NBA : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_n_b_a, container, false)
}
}
fragment_n_b_a.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NBA">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="NBA Fragment"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold" />
</FrameLayout>
Step 6 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "This example demonstrates how to create Tab Layout in an Android App using Kotlin."
},
{
"code": null,
"e": 1273,
"s": 1145,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1338,
"s": 1273,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2171,
"s": 1338,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n<com.google.android.material.tabs.TabLayout\n android:id=\"@+id/tabLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:background=\"#1db995\">\n</com.google.android.material.tabs.TabLayout>\n<androidx.viewpager.widget.ViewPager\n android:id=\"@+id/viewPager\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/tabLayout\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"100dp\"\n tools:layout_editor_absoluteX=\"8dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2226,
"s": 2171,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3690,
"s": 2226,
"text": "import android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.viewpager.widget.ViewPager\nimport com.google.android.material.tabs.TabLayout\nimport com.google.android.material.tabs.TabLayout.OnTabSelectedListener\nimport com.google.android.material.tabs.TabLayout.TabLayoutOnPageChangeListener\nclass MainActivity : AppCompatActivity() {\n lateinit var tabLayout: TabLayout\n lateinit var viewPager: ViewPager\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n tabLayout = findViewById(R.id.tabLayout)\n viewPager = findViewById(R.id.viewPager)\n tabLayout.addTab(tabLayout.newTab().setText(\"Football\"))\n tabLayout.addTab(tabLayout.newTab().setText(\"Cricket\"))\n tabLayout.addTab(tabLayout.newTab().setText(\"NBA\"))\n tabLayout.tabGravity = TabLayout.GRAVITY_FILL\n val adapter = MyAdapter(this, supportFragmentManager,\n tabLayout.tabCount)\n viewPager.adapter = adapter\n viewPager.addOnPageChangeListener(TabLayoutOnPageChangeListener(tabLayout))\n tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {\n override fun onTabSelected(tab: TabLayout.Tab) {\n viewPager.currentItem = tab.position\n }\n override fun onTabUnselected(tab: TabLayout.Tab) {}\n override fun onTabReselected(tab: TabLayout.Tab) {}\n })\n }\n}"
},
{
"code": null,
"e": 3777,
"s": 3690,
"text": "Step 4 − Create a new Adapter kotlin class (MyAdapter.kt) and add the following code −"
},
{
"code": null,
"e": 4432,
"s": 3777,
"text": "import android.content.Context\nimport androidx.fragment.app.Fragment\nimport androidx.fragment.app.FragmentManager\nimport androidx.fragment.app.FragmentPagerAdapter\n@Suppress(\"DEPRECATION\")\ninternal class MyAdapter(\n var context: Context,\n fm: FragmentManager,\n var totalTabs: Int\n) :\nFragmentPagerAdapter(fm) {\n override fun getItem(position: Int): Fragment {\n return when (position) {\n 0 -> {\n Football()\n }\n 1 -> {\n Cricket()\n }\n 2 -> {\n NBA()\n }\n else -> getItem(position)\n }\n }\n override fun getCount(): Int {\n return totalTabs\n }\n}"
},
{
"code": null,
"e": 4545,
"s": 4432,
"text": "Step 5 − Create 3 Fragment activities (Cricket, Football, NBA - You can have your name) and the following code −"
},
{
"code": null,
"e": 4556,
"s": 4545,
"text": "Cricket.kt"
},
{
"code": null,
"e": 4993,
"s": 4556,
"text": "import android.os.Bundle\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport androidx.fragment.app.Fragment\nclass Cricket : Fragment() {\n override fun onCreateView(\n inflater: LayoutInflater, container: ViewGroup?,\n savedInstanceState: Bundle?\n ): View? {\n // Inflate the layout for this fragment\n return inflater.inflate(R.layout.fragment_cricket, container, false)\n }\n}"
},
{
"code": null,
"e": 5014,
"s": 4993,
"text": "fragment_cricket.xml"
},
{
"code": null,
"e": 5558,
"s": 5014,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".Cricket\">\n<!-- TODO: Update blank fragment layout -->\n<TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:text=\"Cricket Fragment\"\n android:textAlignment=\"center\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n</FrameLayout>"
},
{
"code": null,
"e": 5570,
"s": 5558,
"text": "Football.kt"
},
{
"code": null,
"e": 6009,
"s": 5570,
"text": "import android.os.Bundle\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport androidx.fragment.app.Fragment\nclass Football : Fragment() {\n override fun onCreateView(\n inflater: LayoutInflater, container: ViewGroup?,\n savedInstanceState: Bundle?\n ): View? {\n // Inflate the layout for this fragment\n return inflater.inflate(R.layout.fragment_football, container, false)\n }\n}"
},
{
"code": null,
"e": 6030,
"s": 6009,
"text": "fragment_footbal.xml"
},
{
"code": null,
"e": 6576,
"s": 6030,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".Football\">\n<!-- TODO: Update blank fragment layout -->\n<TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:text=\"Football Fragment\"\n android:textAlignment=\"center\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n</FrameLayout>"
},
{
"code": null,
"e": 6583,
"s": 6576,
"text": "NBA.kt"
},
{
"code": null,
"e": 7014,
"s": 6583,
"text": "import android.os.Bundle\nimport androidx.fragment.app.Fragment\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nclass NBA : Fragment() {\n override fun onCreateView(\n inflater: LayoutInflater, container: ViewGroup?,\n savedInstanceState: Bundle?\n ): View? {\n // Inflate the layout for this fragment\n return inflater.inflate(R.layout.fragment_n_b_a, container, false)\n }\n}"
},
{
"code": null,
"e": 7033,
"s": 7014,
"text": "fragment_n_b_a.xml"
},
{
"code": null,
"e": 7569,
"s": 7033,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".NBA\">\n<!-- TODO: Update blank fragment layout -->\n<TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:text=\"NBA Fragment\"\n android:textAlignment=\"center\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n</FrameLayout>"
},
{
"code": null,
"e": 7624,
"s": 7569,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 8295,
"s": 7624,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 8643,
"s": 8295,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Increase the font size of a paragraph with Bootstrap | Use the .lead class in Bootstrap to increase the font size of a paragraph.
You can try to run the following code to implement lead class −
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 = "container">
<h2>Football</h2>
<h3>FIFA</h3>
<p>The 2018 FIFA World Cup is the 21st FIFA World Cup.</p>
<p class = "lead">FIFA, 2018 is going on in Russia.</p>
</div>
</body>
</html> | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "Use the .lead class in Bootstrap to increase the font size of a paragraph."
},
{
"code": null,
"e": 1201,
"s": 1137,
"text": "You can try to run the following code to implement lead class −"
},
{
"code": null,
"e": 1211,
"s": 1201,
"text": "Live Demo"
},
{
"code": null,
"e": 1743,
"s": 1211,
"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 = \"container\">\n <h2>Football</h2>\n <h3>FIFA</h3>\n <p>The 2018 FIFA World Cup is the 21st FIFA World Cup.</p>\n <p class = \"lead\">FIFA, 2018 is going on in Russia.</p>\n </div>\n </body>\n</html>"
}
] |
Bootstrap 4 - Typography | The typography feature creates headings, paragraphs, lists and other inline elements. It specifies how text elements should be rendered on the web page.
Let see each one of the feature of typography in the following sections.
Bootstrap 4 provides HTML headings from h1 to h6 as shown in the below example −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h1>h1 - Tutorialspoint</h1>
<h2>h2 - Tutorialspoint</h2>
<h3>h3 - Tutorialspoint</h3>
<h4>h4 - Tutorialspoint</h4>
<h5>h5 - Tutorialspoint</h5>
<h6>h6 - Tutorialspoint</h6>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
The display headings are used to display the text with larger font size and font weight than the normal headings by using 4 classes of display heading such as .display-1, .display-2, .display-3, and .display-4.
The following example demonstrates usage of above display heading classes −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h1 class = "display-1">Tutorialspoint</h1>
<h1 class = "display-2">Tutorialspoint</h1>
<h1 class = "display-3">Tutorialspoint</h1>
<h1 class = "display-4">Tutorialspoint</h1>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
Add some emphasis to a paragraph by using .lead class.
Add some emphasis to a paragraph by using .lead class.
The HTML <abbr> element provides markup for abbreviations or acronyms, like WWW or HTTP. It uses title attribute and display with a light dotted border along the bottom and reveals the full text on hover.
The HTML <abbr> element provides markup for abbreviations or acronyms, like WWW or HTTP. It uses title attribute and display with a light dotted border along the bottom and reveals the full text on hover.
You can quote the block of content in the document by using .blockquote class in the <blockquote> element.
You can quote the block of content in the document by using .blockquote class in the <blockquote> element.
Use the <mark> element to make the text as marked or highlighted.
Use the <mark> element to make the text as marked or highlighted.
The following example demonstrates each of the above types −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Lead</h2>
<p class = "lead">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.
</p>
<h2>Abbreviations</h2>
<p><abbr title = "World Wide Web">WWW</abbr></p>
<h2>Blockquote</h2>
<blockquote class = "blockquote">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.
</blockquote>
<h2>Marked Text</h2>
<p>Welcome to <mark>tutorialspoint</mark></p>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
WWW
Welcome to tutorialspoint
Bootstrap 4 provides various styles such as Unstyled, Inline, and Description list alignment lists.
Unstyled − You can display the list by removing default list-style and left margin.
Unstyled − You can display the list by removing default list-style and left margin.
Inline − You can also place all list items on a single line using the .list-inline and .list-inline-item classes.
Inline − You can also place all list items on a single line using the .list-inline and .list-inline-item classes.
Description list alignment − You can display the terms and descriptions horizontally by using .row class to <dl> tag.
Description list alignment − You can display the terms and descriptions horizontally by using .row class to <dl> tag.
The following example demonstrates usage of above list types −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Unstyled List</h2>
<ul class = "list-unstyled">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<h2>Inline List</h2>
<ul class = "list-inline">
<li class = "list-inline-item">HTML</li>
<li class = "list-inline-item">CSS</li>
<li class = "list-inline-item">JavaScript</li>
</ul>
<h2>Description list alignment</h2>
<dl class = "row">
<dt class = "col-sm-3">HTML</dt>
<dd class = "col-sm-9">To define the content of web pages</dd>
<dt class = "col-sm-3">CSS</dt>
<dd class = "col-sm-9">To specify the layout of web pages</dd>
<dt class = "col-sm-3">JavaScript</dt>
<dd class = "col-sm-9">To program the behavior of web pages</dd>
</dl>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
HTML
CSS
JavaScript
HTML
CSS
JavaScript
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1969,
"s": 1816,
"text": "The typography feature creates headings, paragraphs, lists and other inline elements. It specifies how text elements should be rendered on the web page."
},
{
"code": null,
"e": 2042,
"s": 1969,
"text": "Let see each one of the feature of typography in the following sections."
},
{
"code": null,
"e": 2123,
"s": 2042,
"text": "Bootstrap 4 provides HTML headings from h1 to h6 as shown in the below example −"
},
{
"code": null,
"e": 3766,
"s": 2123,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h1>h1 - Tutorialspoint</h1>\n <h2>h2 - Tutorialspoint</h2>\n <h3>h3 - Tutorialspoint</h3>\n <h4>h4 - Tutorialspoint</h4>\n <h5>h5 - Tutorialspoint</h5>\n <h6>h6 - Tutorialspoint</h6>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3805,
"s": 3766,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4017,
"s": 3805,
"text": "The display headings are used to display the text with larger font size and font weight than the normal headings by using 4 classes of display heading such as .display-1, .display-2, .display-3, and .display-4."
},
{
"code": null,
"e": 4093,
"s": 4017,
"text": "The following example demonstrates usage of above display heading classes −"
},
{
"code": null,
"e": 5720,
"s": 4093,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h1 class = \"display-1\">Tutorialspoint</h1>\n <h1 class = \"display-2\">Tutorialspoint</h1>\n <h1 class = \"display-3\">Tutorialspoint</h1>\n <h1 class = \"display-4\">Tutorialspoint</h1>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 5759,
"s": 5720,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5814,
"s": 5759,
"text": "Add some emphasis to a paragraph by using .lead class."
},
{
"code": null,
"e": 5869,
"s": 5814,
"text": "Add some emphasis to a paragraph by using .lead class."
},
{
"code": null,
"e": 6074,
"s": 5869,
"text": "The HTML <abbr> element provides markup for abbreviations or acronyms, like WWW or HTTP. It uses title attribute and display with a light dotted border along the bottom and reveals the full text on hover."
},
{
"code": null,
"e": 6279,
"s": 6074,
"text": "The HTML <abbr> element provides markup for abbreviations or acronyms, like WWW or HTTP. It uses title attribute and display with a light dotted border along the bottom and reveals the full text on hover."
},
{
"code": null,
"e": 6386,
"s": 6279,
"text": "You can quote the block of content in the document by using .blockquote class in the <blockquote> element."
},
{
"code": null,
"e": 6493,
"s": 6386,
"text": "You can quote the block of content in the document by using .blockquote class in the <blockquote> element."
},
{
"code": null,
"e": 6559,
"s": 6493,
"text": "Use the <mark> element to make the text as marked or highlighted."
},
{
"code": null,
"e": 6625,
"s": 6559,
"text": "Use the <mark> element to make the text as marked or highlighted."
},
{
"code": null,
"e": 6686,
"s": 6625,
"text": "The following example demonstrates each of the above types −"
},
{
"code": null,
"e": 9024,
"s": 6686,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Lead</h2>\n <p class = \"lead\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod \n tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \n veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \n commodo consequat. \n </p>\n \n <h2>Abbreviations</h2>\n <p><abbr title = \"World Wide Web\">WWW</abbr></p>\n <h2>Blockquote</h2>\n <blockquote class = \"blockquote\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod \n tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \n veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \n commodo consequat. \n </blockquote>\n \n <h2>Marked Text</h2>\n <p>Welcome to <mark>tutorialspoint</mark></p>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 9063,
"s": 9024,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 9319,
"s": 9063,
"text": "\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \n "
},
{
"code": null,
"e": 9323,
"s": 9319,
"text": "WWW"
},
{
"code": null,
"e": 9349,
"s": 9323,
"text": "Welcome to tutorialspoint"
},
{
"code": null,
"e": 9449,
"s": 9349,
"text": "Bootstrap 4 provides various styles such as Unstyled, Inline, and Description list alignment lists."
},
{
"code": null,
"e": 9533,
"s": 9449,
"text": "Unstyled − You can display the list by removing default list-style and left margin."
},
{
"code": null,
"e": 9617,
"s": 9533,
"text": "Unstyled − You can display the list by removing default list-style and left margin."
},
{
"code": null,
"e": 9731,
"s": 9617,
"text": "Inline − You can also place all list items on a single line using the .list-inline and .list-inline-item classes."
},
{
"code": null,
"e": 9845,
"s": 9731,
"text": "Inline − You can also place all list items on a single line using the .list-inline and .list-inline-item classes."
},
{
"code": null,
"e": 9963,
"s": 9845,
"text": "Description list alignment − You can display the terms and descriptions horizontally by using .row class to <dl> tag."
},
{
"code": null,
"e": 10081,
"s": 9963,
"text": "Description list alignment − You can display the terms and descriptions horizontally by using .row class to <dl> tag."
},
{
"code": null,
"e": 10144,
"s": 10081,
"text": "The following example demonstrates usage of above list types −"
},
{
"code": null,
"e": 12447,
"s": 10144,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Unstyled List</h2>\n <ul class = \"list-unstyled\">\n <li>HTML</li>\n <li>CSS</li>\n <li>JavaScript</li>\n </ul>\n \n <h2>Inline List</h2>\n <ul class = \"list-inline\">\n <li class = \"list-inline-item\">HTML</li>\n <li class = \"list-inline-item\">CSS</li>\n <li class = \"list-inline-item\">JavaScript</li>\n </ul>\n \n <h2>Description list alignment</h2>\n <dl class = \"row\">\n <dt class = \"col-sm-3\">HTML</dt>\n <dd class = \"col-sm-9\">To define the content of web pages</dd>\n <dt class = \"col-sm-3\">CSS</dt>\n <dd class = \"col-sm-9\">To specify the layout of web pages</dd>\n <dt class = \"col-sm-3\">JavaScript</dt>\n <dd class = \"col-sm-9\">To program the behavior of web pages</dd>\n </dl>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 12486,
"s": 12447,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 12491,
"s": 12486,
"text": "HTML"
},
{
"code": null,
"e": 12495,
"s": 12491,
"text": "CSS"
},
{
"code": null,
"e": 12506,
"s": 12495,
"text": "JavaScript"
},
{
"code": null,
"e": 12511,
"s": 12506,
"text": "HTML"
},
{
"code": null,
"e": 12515,
"s": 12511,
"text": "CSS"
},
{
"code": null,
"e": 12526,
"s": 12515,
"text": "JavaScript"
},
{
"code": null,
"e": 12559,
"s": 12526,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12573,
"s": 12559,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 12608,
"s": 12573,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12625,
"s": 12608,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12662,
"s": 12625,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 12690,
"s": 12662,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12723,
"s": 12690,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12735,
"s": 12723,
"text": " Azaz Patel"
},
{
"code": null,
"e": 12770,
"s": 12735,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12787,
"s": 12770,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 12820,
"s": 12787,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 12840,
"s": 12820,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 12847,
"s": 12840,
"text": " Print"
},
{
"code": null,
"e": 12858,
"s": 12847,
"text": " Add Notes"
}
] |
Find the length of the Largest subset such that all elements are Pairwise Coprime - GeeksforGeeks | 31 Aug, 2021
Given an array A of size N, our task is to find the length of the largest subset such that all elements in the subset are pairwise coprime that is for any two elements x and y where x and y are not the same, the gcd(x, y) is equal to 1.Note: All array elements are <= 50.
Examples:
Input: A = [2, 5, 2, 5, 2] Output: 2 Explanation: The largest subset satisfying the condition is: {2, 5}
Input: A = [2, 3, 13, 5, 14, 6, 7, 11] Output: 6
Naive Approach:To solve the problem mentioned above we have to generate all subsets, and for each subset check whether the given condition holds or not. But this method takes O(N2 * 2N) time and can be optimized further.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to Find the length of the Largest// subset such that all elements are Pairwise Coprime#include <bits/stdc++.h>using namespace std; // Function to find the largest subset possibleint largestSubset(int a[], int n){ int answer = 0; // Iterate through all the subsets for (int i = 1; i < (1 << n); i++) { vector<int> subset; /* Check if jth bit in the counter is set */ for (int j = 0; j < n; j++) { if (i & (1 << j)) subset.push_back(a[j]); } bool flag = true; for (int j = 0; j < subset.size(); j++) { for (int k = j + 1; k < subset.size(); k++) { // Check if the gcd is not equal to 1 if (__gcd(subset[j], subset[k]) != 1) flag = false; } } if (flag == true) // Update the answer with maximum value answer = max(answer, (int)subset.size()); } // Return the final result return answer;} // Driver codeint main(){ int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = sizeof(A) / sizeof(A[0]); cout << largestSubset(A, N); return 0;}
// Java implementation to find the length// of the largest subset such that all// elements are Pairwise Coprimeimport java.util.*; class GFG{ static int gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function to find the largest subset possiblestatic int largestSubset(int a[], int n){ int answer = 0; // Iterate through all the subsets for(int i = 1; i < (1 << n); i++) { Vector<Integer> subset = new Vector<Integer>(); // Check if jth bit in the counter is set for(int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) subset.add(a[j]); } boolean flag = true; for(int j = 0; j < subset.size(); j++) { for(int k = j + 1; k < subset.size(); k++) { // Check if the gcd is not equal to 1 if (gcd((int)subset.get(j), (int) subset.get(k)) != 1) flag = false; } } if (flag == true) // Update the answer with maximum value answer = Math.max(answer, (int)subset.size()); } // Return the final result return answer;} // Driver codepublic static void main(String args[]){ int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = A.length; System.out.println(largestSubset(A, N));}} // This code is contributed by Stream_Cipher
# Python3 implementation to Find# the length of the Largest subset# such that all elements are Pairwise Coprimeimport math # Function to find the largest subset possibledef largestSubset(a, n): answer = 0 # Iterate through all the subsets for i in range(1, (1 << n)): subset = [] # Check if jth bit in the counter is set for j in range(0, n): if (i & (1 << j)): subset.insert(j, a[j]) flag = True for j in range(0, len(subset)): for k in range(j + 1, len(subset)): # Check if the gcd is not equal to 1 if (math.gcd(subset[j], subset[k]) != 1) : flag = False if (flag == True): # Update the answer with maximum value answer = max(answer, len(subset)) # Return the final result return answer # Driver codeA = [ 2, 3, 13, 5, 14, 6, 7, 11 ]N = len(A)print(largestSubset(A, N)) # This code is contributed by Sanjit_Prasad
// C# implementation to Find the length// of the largest subset such that all// elements are Pairwise Coprimeusing System;using System.Collections.Generic; class GFG{ static int gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function to find the largest subset possiblestatic int largestSubset(int []a, int n){ int answer = 0; // Iterate through all the subsets for(int i = 1; i < (1 << n); i++) { List<int> subset = new List<int>(); // Check if jth bit in the counter is set for(int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) subset.Add(a[j]); } int flag = 1; for(int j = 0; j < subset.Count; j++) { for(int k = j + 1; k < subset.Count; k++) { // Check if the gcd is not equal to 1 if (gcd((int)subset[j], (int) subset[k]) != 1) flag = 0; } } if (flag == 1) // Update the answer with maximum value answer = Math.Max(answer, (int)subset.Count); } // Return the final result return answer;} // Driver codepublic static void Main(){ int []A = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = A.Length; Console.WriteLine(largestSubset(A, N));}} // This code is contributed by Stream_Cipher
<script> // Javascript implementation to Find the length // of the largest subset such that all // elements are Pairwise Coprime function gcd(a, b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Function to find the largest subset possible function largestSubset(a, n) { let answer = 0; // Iterate through all the subsets for(let i = 1; i < (1 << n); i++) { let subset = []; // Check if jth bit in the counter is set for(let j = 0; j < n; j++) { if ((i & (1 << j)) != 0) subset.push(a[j]); } let flag = 1; for(let j = 0; j < subset.length; j++) { for(let k = j + 1; k < subset.length; k++) { // Check if the gcd is not equal to 1 if (gcd(subset[j], subset[k]) != 1) flag = 0; } } if (flag == 1) // Update the answer with maximum value answer = Math.max(answer, subset.length); } // Return the final result return answer; } let A = [ 2, 3, 13, 5, 14, 6, 7, 11 ]; let N = A.length; document.write(largestSubset(A, N)); </script>
6
Efficient Approach:The above method can be optimized and the approach depends on the fact that there are only 15 prime numbers in the first 50 natural numbers. So all the numbers in array will have prime factors among these 15 numbers only. We will use Bitmasking and Dynamic Programming to optimize the problem.
Since there are 15 primes only, consider a 15-bit representation of every number where each bit is 1 if that index of prime is a factor of that number. We will index prime numbers by 0 indexing, which means 2 at 0th position 3 at index 1 and so on.
An integer variable ‘mask‘ indicates the prime factors which have already occurred in the subset. If i’th bit is set in the mask, then i’th prime factor has occurred, otherwise not.
At each step of recurrence relation, the element can either be included in the subset or cannot be included. If the element is not included in the subarray, then simply move to the next index. If it is included, change the mask by setting all the bits corresponding to the current element’s prime factors, ON in the mask. The current element can only be included if all of its prime factors have not occurred previously.
This condition will be satisfied only if the bits corresponding to the current element’s digits in the mask are OFF.
If we draw the complete recursion tree, we can observe that many subproblems are being solved which were occurring again and again. So we use a table dp[][] such that for every index dp[i][j], i is the position of the element in the array, and j is the mask.
Below is the implementation of the above approach:
C++
Java
Python
C#
Javascript
// C++ implementation to Find the length of the Largest// subset such that all elements are Pairwise Coprime#include <bits/stdc++.h>using namespace std; // Dynamic programming tableint dp[5000][(1 << 10) + 5]; // Function to obtain the mask for any integerint getmask(int val){ int mask = 0; // List of prime numbers till 50 int prime[15] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 }; // Iterate through all prime numbers to obtain the mask for (int i = 0; i < 15; i++) { if (val % prime[i] == 0) { // Set this prime's bit ON in the mask mask = mask | (1 << i); } } // Return the mask value return mask;} // Function to count the number of waysint calculate(int pos, int mask, int a[], int n){ if (pos == n || mask == (1 << n - 1)) return 0; // Check if subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; int size = 0; // Excluding current element in the subset size = max(size, calculate(pos + 1, mask, a, n)); // Check if there are no common prime factors // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask if this element is included int new_mask = (mask | (getmask(a[pos]))); size = max(size, 1 + calculate(pos + 1, new_mask, a, n)); } // Store and return the answer return dp[pos][mask] = size;} // Function to find the count of// subarray with all digits uniqueint largestSubset(int a[], int n){ // Initializing dp memset(dp, -1, sizeof(dp)); return calculate(0, 0, a, n);} // Driver codeint main(){ int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = sizeof(A) / sizeof(A[0]); cout << largestSubset(A, N); return 0;}
// Java implementation to find the length// of the largest subset such that all// elements are Pairwise Coprimeimport java.util.*; class GFG{ // Dynamic programming tablestatic int dp[][] = new int [5000][1029]; // Function to obtain the mask for any integerstatic int getmask(int val){ int mask = 0; // List of prime numbers till 50 int prime[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 }; // Iterate through all prime numbers // to obtain the mask for(int i = 0; i < 15; i++) { if (val % prime[i] == 0) { // Set this prime's bit ON in the mask mask = mask | (1 << i); } } // Return the mask value return mask;} // Function to count the number of waysstatic int calculate(int pos, int mask, int a[], int n){ if (pos == n || mask == (int)(1 << n - 1)) return 0; // Check if subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; int size = 0; // Excluding current element in the subset size = Math.max(size, calculate(pos + 1, mask, a, n)); // Check if there are no common prime factors // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask if this // element is included int new_mask = (mask | (getmask(a[pos]))); size = Math.max(size, 1 + calculate(pos + 1, new_mask, a, n)); } // Store and return the answer return dp[pos][mask] = size;} // Function to find the count of// subarray with all digits uniquestatic int largestSubset(int a[], int n){ for(int i = 0; i < 5000; i++) Arrays.fill(dp[i], -1); return calculate(0, 0, a, n);} // Driver codepublic static void main(String args[]){ int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = A.length; System.out.println(largestSubset(A, N));}} // This code is contributed by Stream_Cipher
# Python implementation to find the# length of the Largest subset such# that all elements are Pairwise Coprime # Dynamic programming tabledp = [[-1] * ((1 << 10) + 5)] * 5000 # Function to obtain the mask for any integerdef getmask(val): mask = 0 # List of prime numbers till 50 prime = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 ] # Iterate through all prime numbers # to obtain the mask for i in range(1, 15): if val % prime[i] == 0: # Set this prime's bit ON in the mask mask = mask | (1 << i) # Return the mask value return mask # Function to count the number of waysdef calculate(pos, mask, a, n): if ((pos == n) or (mask == (1 << n - 1))): return 0 # Check if subproblem has been solved if dp[pos][mask] != -1: return dp[pos][mask] size = 0 # Excluding current element in the subset size = max(size, calculate(pos + 1, mask, a, n)) # Check if there are no common prime factors # then only this element can be included if (getmask(a[pos]) & mask) == 0: # Calculate the new mask if this # element is included new_mask = (mask | (getmask(a[pos]))) size = max(size, 1 + calculate(pos + 1, new_mask, a, n)) # Store and return the answer dp[pos][mask] = size return dp[pos][mask] # Function to find the count of# subarray with all digits unique def largestSubset(A, n): return calculate(0, 0, A, n); # Driver codeA = [ 2, 3, 13, 5, 14, 6, 7, 11 ]N = len(A) print(largestSubset(A, N)) # This code is contributed by Stream_Cipher
// C# implementation to find the length// of the largest subset such that all// elements are Pairwise Coprimeusing System; class GFG{ // Dynamic programming tablestatic int [,] dp = new int [5000, 1029]; // Function to obtain the mask for any integerstatic int getmask(int val){ int mask = 0; // List of prime numbers till 50 int []prime = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 }; // Iterate through all prime // numbers to obtain the mask for(int i = 0; i < 15; i++) { if (val % prime[i] == 0) { // Set this prime's bit ON in the mask mask = mask | (1 << i); } } // Return the mask value return mask;} // Function to count the number of waysstatic int calculate(int pos, int mask, int []a, int n){ if (pos == n || mask == (int)(1 << n - 1)) return 0; // Check if subproblem has been solved if (dp[pos, mask] != -1) return dp[pos, mask]; int size = 0; // Excluding current element in the subset size = Math.Max(size, calculate(pos + 1, mask, a, n)); // Check if there are no common prime factors // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask if // this element is included int new_mask = (mask | (getmask(a[pos]))); size = Math.Max(size, 1 + calculate(pos + 1, new_mask, a, n)); } // Store and return the answer return dp[pos, mask] = size;} // Function to find the count of// subarray with all digits uniquestatic int largestSubset(int []a, int n){ for(int i = 0; i < 5000; i++) { for(int j = 0; j < 1029; j++) dp[i, j] = -1; } return calculate(0, 0, a, n);} // Driver codepublic static void Main(){ int []A = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = A.Length; Console.WriteLine(largestSubset(A, N));}} // This code is contributed by Stream_Cipher
<script> // JavaScript implementation to// Find the length of the Largest// subset such that all elements// are Pairwise Coprime // Dynamic programming tablevar dp = Array.from(Array(5000), ()=>Array((1 << 10) + 5)); // Function to obtain the mask for any integerfunction getmask( val){ var mask = 0; // List of prime numbers till 50 var prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]; // Iterate through all prime numbers to obtain the mask for (var i = 0; i < 15; i++) { if (val % prime[i] == 0) { // Set this prime's bit ON in the mask mask = mask | (1 << i); } } // Return the mask value return mask;} // Function to count the number of waysfunction calculate(pos, mask, a, n){ if (pos == n || mask == (1 << n - 1)) return 0; // Check if subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; var size = 0; // Excluding current element in the subset size = Math.max(size, calculate(pos + 1, mask, a, n)); // Check if there are no common prime factors // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask if this element is included var new_mask = (mask | (getmask(a[pos]))); size = Math.max(size, 1 + calculate(pos + 1, new_mask, a, n)); } // Store and return the answer return dp[pos][mask] = size;} // Function to find the count of// subarray with all digits uniquefunction largestSubset(a, n){ // Initializing dp dp = Array.from(Array(5000), ()=>Array((1 << 10) + 5).fill(-1)); return calculate(0, 0, a, n);} // Driver codevar A = [2, 3, 13, 5, 14, 6, 7, 11 ];var N = A.length;document.write( largestSubset(A, N)); </script>
6
Time Complexity: O(N * 15 * 215)
Sanjit_Prasad
Stream_Cipher
rrrtnx
decode2207
arorakashish0911
subset
Algorithms
Bit Magic
Competitive Programming
Dynamic Programming
Mathematical
Recursion
Dynamic Programming
Mathematical
Recursion
Bit Magic
subset
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Difference between Informed and Uninformed Search in AI
SCAN (Elevator) Disk Scheduling Algorithms
Quadratic Probing in Hashing
K means Clustering - Introduction
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable? | [
{
"code": null,
"e": 24275,
"s": 24247,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 24547,
"s": 24275,
"text": "Given an array A of size N, our task is to find the length of the largest subset such that all elements in the subset are pairwise coprime that is for any two elements x and y where x and y are not the same, the gcd(x, y) is equal to 1.Note: All array elements are <= 50."
},
{
"code": null,
"e": 24557,
"s": 24547,
"text": "Examples:"
},
{
"code": null,
"e": 24663,
"s": 24557,
"text": "Input: A = [2, 5, 2, 5, 2] Output: 2 Explanation: The largest subset satisfying the condition is: {2, 5} "
},
{
"code": null,
"e": 24713,
"s": 24663,
"text": "Input: A = [2, 3, 13, 5, 14, 6, 7, 11] Output: 6 "
},
{
"code": null,
"e": 24934,
"s": 24713,
"text": "Naive Approach:To solve the problem mentioned above we have to generate all subsets, and for each subset check whether the given condition holds or not. But this method takes O(N2 * 2N) time and can be optimized further."
},
{
"code": null,
"e": 24985,
"s": 24934,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24989,
"s": 24985,
"text": "C++"
},
{
"code": null,
"e": 24994,
"s": 24989,
"text": "Java"
},
{
"code": null,
"e": 25002,
"s": 24994,
"text": "Python3"
},
{
"code": null,
"e": 25005,
"s": 25002,
"text": "C#"
},
{
"code": null,
"e": 25016,
"s": 25005,
"text": "Javascript"
},
{
"code": "// C++ implementation to Find the length of the Largest// subset such that all elements are Pairwise Coprime#include <bits/stdc++.h>using namespace std; // Function to find the largest subset possibleint largestSubset(int a[], int n){ int answer = 0; // Iterate through all the subsets for (int i = 1; i < (1 << n); i++) { vector<int> subset; /* Check if jth bit in the counter is set */ for (int j = 0; j < n; j++) { if (i & (1 << j)) subset.push_back(a[j]); } bool flag = true; for (int j = 0; j < subset.size(); j++) { for (int k = j + 1; k < subset.size(); k++) { // Check if the gcd is not equal to 1 if (__gcd(subset[j], subset[k]) != 1) flag = false; } } if (flag == true) // Update the answer with maximum value answer = max(answer, (int)subset.size()); } // Return the final result return answer;} // Driver codeint main(){ int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = sizeof(A) / sizeof(A[0]); cout << largestSubset(A, N); return 0;}",
"e": 26179,
"s": 25016,
"text": null
},
{
"code": "// Java implementation to find the length// of the largest subset such that all// elements are Pairwise Coprimeimport java.util.*; class GFG{ static int gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function to find the largest subset possiblestatic int largestSubset(int a[], int n){ int answer = 0; // Iterate through all the subsets for(int i = 1; i < (1 << n); i++) { Vector<Integer> subset = new Vector<Integer>(); // Check if jth bit in the counter is set for(int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) subset.add(a[j]); } boolean flag = true; for(int j = 0; j < subset.size(); j++) { for(int k = j + 1; k < subset.size(); k++) { // Check if the gcd is not equal to 1 if (gcd((int)subset.get(j), (int) subset.get(k)) != 1) flag = false; } } if (flag == true) // Update the answer with maximum value answer = Math.max(answer, (int)subset.size()); } // Return the final result return answer;} // Driver codepublic static void main(String args[]){ int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = A.length; System.out.println(largestSubset(A, N));}} // This code is contributed by Stream_Cipher",
"e": 27861,
"s": 26179,
"text": null
},
{
"code": "# Python3 implementation to Find# the length of the Largest subset# such that all elements are Pairwise Coprimeimport math # Function to find the largest subset possibledef largestSubset(a, n): answer = 0 # Iterate through all the subsets for i in range(1, (1 << n)): subset = [] # Check if jth bit in the counter is set for j in range(0, n): if (i & (1 << j)): subset.insert(j, a[j]) flag = True for j in range(0, len(subset)): for k in range(j + 1, len(subset)): # Check if the gcd is not equal to 1 if (math.gcd(subset[j], subset[k]) != 1) : flag = False if (flag == True): # Update the answer with maximum value answer = max(answer, len(subset)) # Return the final result return answer # Driver codeA = [ 2, 3, 13, 5, 14, 6, 7, 11 ]N = len(A)print(largestSubset(A, N)) # This code is contributed by Sanjit_Prasad",
"e": 28879,
"s": 27861,
"text": null
},
{
"code": "// C# implementation to Find the length// of the largest subset such that all// elements are Pairwise Coprimeusing System;using System.Collections.Generic; class GFG{ static int gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function to find the largest subset possiblestatic int largestSubset(int []a, int n){ int answer = 0; // Iterate through all the subsets for(int i = 1; i < (1 << n); i++) { List<int> subset = new List<int>(); // Check if jth bit in the counter is set for(int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) subset.Add(a[j]); } int flag = 1; for(int j = 0; j < subset.Count; j++) { for(int k = j + 1; k < subset.Count; k++) { // Check if the gcd is not equal to 1 if (gcd((int)subset[j], (int) subset[k]) != 1) flag = 0; } } if (flag == 1) // Update the answer with maximum value answer = Math.Max(answer, (int)subset.Count); } // Return the final result return answer;} // Driver codepublic static void Main(){ int []A = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = A.Length; Console.WriteLine(largestSubset(A, N));}} // This code is contributed by Stream_Cipher",
"e": 30518,
"s": 28879,
"text": null
},
{
"code": "<script> // Javascript implementation to Find the length // of the largest subset such that all // elements are Pairwise Coprime function gcd(a, b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Function to find the largest subset possible function largestSubset(a, n) { let answer = 0; // Iterate through all the subsets for(let i = 1; i < (1 << n); i++) { let subset = []; // Check if jth bit in the counter is set for(let j = 0; j < n; j++) { if ((i & (1 << j)) != 0) subset.push(a[j]); } let flag = 1; for(let j = 0; j < subset.length; j++) { for(let k = j + 1; k < subset.length; k++) { // Check if the gcd is not equal to 1 if (gcd(subset[j], subset[k]) != 1) flag = 0; } } if (flag == 1) // Update the answer with maximum value answer = Math.max(answer, subset.length); } // Return the final result return answer; } let A = [ 2, 3, 13, 5, 14, 6, 7, 11 ]; let N = A.length; document.write(largestSubset(A, N)); </script>",
"e": 32085,
"s": 30518,
"text": null
},
{
"code": null,
"e": 32087,
"s": 32085,
"text": "6"
},
{
"code": null,
"e": 32402,
"s": 32089,
"text": "Efficient Approach:The above method can be optimized and the approach depends on the fact that there are only 15 prime numbers in the first 50 natural numbers. So all the numbers in array will have prime factors among these 15 numbers only. We will use Bitmasking and Dynamic Programming to optimize the problem."
},
{
"code": null,
"e": 32651,
"s": 32402,
"text": "Since there are 15 primes only, consider a 15-bit representation of every number where each bit is 1 if that index of prime is a factor of that number. We will index prime numbers by 0 indexing, which means 2 at 0th position 3 at index 1 and so on."
},
{
"code": null,
"e": 32833,
"s": 32651,
"text": "An integer variable ‘mask‘ indicates the prime factors which have already occurred in the subset. If i’th bit is set in the mask, then i’th prime factor has occurred, otherwise not."
},
{
"code": null,
"e": 33254,
"s": 32833,
"text": "At each step of recurrence relation, the element can either be included in the subset or cannot be included. If the element is not included in the subarray, then simply move to the next index. If it is included, change the mask by setting all the bits corresponding to the current element’s prime factors, ON in the mask. The current element can only be included if all of its prime factors have not occurred previously."
},
{
"code": null,
"e": 33371,
"s": 33254,
"text": "This condition will be satisfied only if the bits corresponding to the current element’s digits in the mask are OFF."
},
{
"code": null,
"e": 33630,
"s": 33371,
"text": "If we draw the complete recursion tree, we can observe that many subproblems are being solved which were occurring again and again. So we use a table dp[][] such that for every index dp[i][j], i is the position of the element in the array, and j is the mask."
},
{
"code": null,
"e": 33681,
"s": 33630,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 33685,
"s": 33681,
"text": "C++"
},
{
"code": null,
"e": 33690,
"s": 33685,
"text": "Java"
},
{
"code": null,
"e": 33697,
"s": 33690,
"text": "Python"
},
{
"code": null,
"e": 33700,
"s": 33697,
"text": "C#"
},
{
"code": null,
"e": 33711,
"s": 33700,
"text": "Javascript"
},
{
"code": "// C++ implementation to Find the length of the Largest// subset such that all elements are Pairwise Coprime#include <bits/stdc++.h>using namespace std; // Dynamic programming tableint dp[5000][(1 << 10) + 5]; // Function to obtain the mask for any integerint getmask(int val){ int mask = 0; // List of prime numbers till 50 int prime[15] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 }; // Iterate through all prime numbers to obtain the mask for (int i = 0; i < 15; i++) { if (val % prime[i] == 0) { // Set this prime's bit ON in the mask mask = mask | (1 << i); } } // Return the mask value return mask;} // Function to count the number of waysint calculate(int pos, int mask, int a[], int n){ if (pos == n || mask == (1 << n - 1)) return 0; // Check if subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; int size = 0; // Excluding current element in the subset size = max(size, calculate(pos + 1, mask, a, n)); // Check if there are no common prime factors // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask if this element is included int new_mask = (mask | (getmask(a[pos]))); size = max(size, 1 + calculate(pos + 1, new_mask, a, n)); } // Store and return the answer return dp[pos][mask] = size;} // Function to find the count of// subarray with all digits uniqueint largestSubset(int a[], int n){ // Initializing dp memset(dp, -1, sizeof(dp)); return calculate(0, 0, a, n);} // Driver codeint main(){ int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = sizeof(A) / sizeof(A[0]); cout << largestSubset(A, N); return 0;}",
"e": 35526,
"s": 33711,
"text": null
},
{
"code": "// Java implementation to find the length// of the largest subset such that all// elements are Pairwise Coprimeimport java.util.*; class GFG{ // Dynamic programming tablestatic int dp[][] = new int [5000][1029]; // Function to obtain the mask for any integerstatic int getmask(int val){ int mask = 0; // List of prime numbers till 50 int prime[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 }; // Iterate through all prime numbers // to obtain the mask for(int i = 0; i < 15; i++) { if (val % prime[i] == 0) { // Set this prime's bit ON in the mask mask = mask | (1 << i); } } // Return the mask value return mask;} // Function to count the number of waysstatic int calculate(int pos, int mask, int a[], int n){ if (pos == n || mask == (int)(1 << n - 1)) return 0; // Check if subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; int size = 0; // Excluding current element in the subset size = Math.max(size, calculate(pos + 1, mask, a, n)); // Check if there are no common prime factors // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask if this // element is included int new_mask = (mask | (getmask(a[pos]))); size = Math.max(size, 1 + calculate(pos + 1, new_mask, a, n)); } // Store and return the answer return dp[pos][mask] = size;} // Function to find the count of// subarray with all digits uniquestatic int largestSubset(int a[], int n){ for(int i = 0; i < 5000; i++) Arrays.fill(dp[i], -1); return calculate(0, 0, a, n);} // Driver codepublic static void main(String args[]){ int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = A.length; System.out.println(largestSubset(A, N));}} // This code is contributed by Stream_Cipher",
"e": 37680,
"s": 35526,
"text": null
},
{
"code": "# Python implementation to find the# length of the Largest subset such# that all elements are Pairwise Coprime # Dynamic programming tabledp = [[-1] * ((1 << 10) + 5)] * 5000 # Function to obtain the mask for any integerdef getmask(val): mask = 0 # List of prime numbers till 50 prime = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 ] # Iterate through all prime numbers # to obtain the mask for i in range(1, 15): if val % prime[i] == 0: # Set this prime's bit ON in the mask mask = mask | (1 << i) # Return the mask value return mask # Function to count the number of waysdef calculate(pos, mask, a, n): if ((pos == n) or (mask == (1 << n - 1))): return 0 # Check if subproblem has been solved if dp[pos][mask] != -1: return dp[pos][mask] size = 0 # Excluding current element in the subset size = max(size, calculate(pos + 1, mask, a, n)) # Check if there are no common prime factors # then only this element can be included if (getmask(a[pos]) & mask) == 0: # Calculate the new mask if this # element is included new_mask = (mask | (getmask(a[pos]))) size = max(size, 1 + calculate(pos + 1, new_mask, a, n)) # Store and return the answer dp[pos][mask] = size return dp[pos][mask] # Function to find the count of# subarray with all digits unique def largestSubset(A, n): return calculate(0, 0, A, n); # Driver codeA = [ 2, 3, 13, 5, 14, 6, 7, 11 ]N = len(A) print(largestSubset(A, N)) # This code is contributed by Stream_Cipher",
"e": 39507,
"s": 37680,
"text": null
},
{
"code": "// C# implementation to find the length// of the largest subset such that all// elements are Pairwise Coprimeusing System; class GFG{ // Dynamic programming tablestatic int [,] dp = new int [5000, 1029]; // Function to obtain the mask for any integerstatic int getmask(int val){ int mask = 0; // List of prime numbers till 50 int []prime = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 }; // Iterate through all prime // numbers to obtain the mask for(int i = 0; i < 15; i++) { if (val % prime[i] == 0) { // Set this prime's bit ON in the mask mask = mask | (1 << i); } } // Return the mask value return mask;} // Function to count the number of waysstatic int calculate(int pos, int mask, int []a, int n){ if (pos == n || mask == (int)(1 << n - 1)) return 0; // Check if subproblem has been solved if (dp[pos, mask] != -1) return dp[pos, mask]; int size = 0; // Excluding current element in the subset size = Math.Max(size, calculate(pos + 1, mask, a, n)); // Check if there are no common prime factors // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask if // this element is included int new_mask = (mask | (getmask(a[pos]))); size = Math.Max(size, 1 + calculate(pos + 1, new_mask, a, n)); } // Store and return the answer return dp[pos, mask] = size;} // Function to find the count of// subarray with all digits uniquestatic int largestSubset(int []a, int n){ for(int i = 0; i < 5000; i++) { for(int j = 0; j < 1029; j++) dp[i, j] = -1; } return calculate(0, 0, a, n);} // Driver codepublic static void Main(){ int []A = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = A.Length; Console.WriteLine(largestSubset(A, N));}} // This code is contributed by Stream_Cipher",
"e": 41672,
"s": 39507,
"text": null
},
{
"code": "<script> // JavaScript implementation to// Find the length of the Largest// subset such that all elements// are Pairwise Coprime // Dynamic programming tablevar dp = Array.from(Array(5000), ()=>Array((1 << 10) + 5)); // Function to obtain the mask for any integerfunction getmask( val){ var mask = 0; // List of prime numbers till 50 var prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]; // Iterate through all prime numbers to obtain the mask for (var i = 0; i < 15; i++) { if (val % prime[i] == 0) { // Set this prime's bit ON in the mask mask = mask | (1 << i); } } // Return the mask value return mask;} // Function to count the number of waysfunction calculate(pos, mask, a, n){ if (pos == n || mask == (1 << n - 1)) return 0; // Check if subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; var size = 0; // Excluding current element in the subset size = Math.max(size, calculate(pos + 1, mask, a, n)); // Check if there are no common prime factors // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask if this element is included var new_mask = (mask | (getmask(a[pos]))); size = Math.max(size, 1 + calculate(pos + 1, new_mask, a, n)); } // Store and return the answer return dp[pos][mask] = size;} // Function to find the count of// subarray with all digits uniquefunction largestSubset(a, n){ // Initializing dp dp = Array.from(Array(5000), ()=>Array((1 << 10) + 5).fill(-1)); return calculate(0, 0, a, n);} // Driver codevar A = [2, 3, 13, 5, 14, 6, 7, 11 ];var N = A.length;document.write( largestSubset(A, N)); </script>",
"e": 43476,
"s": 41672,
"text": null
},
{
"code": null,
"e": 43478,
"s": 43476,
"text": "6"
},
{
"code": null,
"e": 43512,
"s": 43478,
"text": "Time Complexity: O(N * 15 * 215) "
},
{
"code": null,
"e": 43526,
"s": 43512,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 43540,
"s": 43526,
"text": "Stream_Cipher"
},
{
"code": null,
"e": 43547,
"s": 43540,
"text": "rrrtnx"
},
{
"code": null,
"e": 43558,
"s": 43547,
"text": "decode2207"
},
{
"code": null,
"e": 43575,
"s": 43558,
"text": "arorakashish0911"
},
{
"code": null,
"e": 43582,
"s": 43575,
"text": "subset"
},
{
"code": null,
"e": 43593,
"s": 43582,
"text": "Algorithms"
},
{
"code": null,
"e": 43603,
"s": 43593,
"text": "Bit Magic"
},
{
"code": null,
"e": 43627,
"s": 43603,
"text": "Competitive Programming"
},
{
"code": null,
"e": 43647,
"s": 43627,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 43660,
"s": 43647,
"text": "Mathematical"
},
{
"code": null,
"e": 43670,
"s": 43660,
"text": "Recursion"
},
{
"code": null,
"e": 43690,
"s": 43670,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 43703,
"s": 43690,
"text": "Mathematical"
},
{
"code": null,
"e": 43713,
"s": 43703,
"text": "Recursion"
},
{
"code": null,
"e": 43723,
"s": 43713,
"text": "Bit Magic"
},
{
"code": null,
"e": 43730,
"s": 43723,
"text": "subset"
},
{
"code": null,
"e": 43741,
"s": 43730,
"text": "Algorithms"
},
{
"code": null,
"e": 43839,
"s": 43741,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43848,
"s": 43839,
"text": "Comments"
},
{
"code": null,
"e": 43861,
"s": 43848,
"text": "Old Comments"
},
{
"code": null,
"e": 43886,
"s": 43861,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 43942,
"s": 43886,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 43985,
"s": 43942,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 44014,
"s": 43985,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 44048,
"s": 44014,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 44075,
"s": 44048,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 44121,
"s": 44075,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 44189,
"s": 44121,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 44218,
"s": 44189,
"text": "Count set bits in an integer"
}
] |
Exploring Classifiers with Python Scikit-learn — Iris Dataset | by Dehao Zhang | Towards Data Science | For a moment, imagine that you are not a flower expert (if you are an expert, good for you!). Can you distinguish between three different species of iris — setosa, versicolor, and virginica?
I know I can’t...
BUT what if we have a dataset that contains instances of these species, with measurements of their sepals and petals?
In other words, can we learn anything from this dataset that would help us distinguish between the three species?
Why are we choosing this dataset?What questions are we trying to answer?What can we find in this dataset?Which classifiers are we building?What can we do next?
Why are we choosing this dataset?
What questions are we trying to answer?
What can we find in this dataset?
Which classifiers are we building?
What can we do next?
In this blog post, I will explore the Iris dataset from the UCI Machine Learning Repository. Excerpted from its website, it is said to be “perhaps the best known database to be found in the pattern recognition literature” [1]. In addition, Jason Brownlee who started the community of Machine Learning Mastery called it the “Hello World” of machine learning [2].
I would recommend this dataset to anyone who is a beginner in data science and is eager to build their first ML model. See below for some of nice characteristics of this dataset:
150 samples, with 4 attributes (same units, all numeric)Balanced class distribution (50 samples for each class)No missing data
150 samples, with 4 attributes (same units, all numeric)
Balanced class distribution (50 samples for each class)
No missing data
As you can see, these characteristics can help minimize the time you need to spend in the data preparation process so you can focus on building the ML model. It is NOT that the preparation stage is not important. On the contrary, this process is so important that it can be too time-consuming for some beginners that they may overwhelm themselves before getting to the model development stage.
As an example, the popular dataset House Prices: Advanced Regression Techniques from Kaggle has about 80 features and more than 20% of them contain some level of missing data. In that case, you might need to spend some time understanding the attributes and imputing missing values.
Now hopefully your confidence level (no stats pun intended) is relatively high. Here are some resources on data wrangling that you can read through as you work on more complex datasets and tasks: Dimensionality reduction, Imbalanced classification, Feature engineering, and Imputation.
There are two questions that we want to be able to answer after exploring this dataset, which are quite typical in most classification problems:
Prediction — given new data points, how accurately can the model predict their classes (species)?Inference — Which predictor(s) can effectively help with the predictions?
Prediction — given new data points, how accurately can the model predict their classes (species)?
Inference — Which predictor(s) can effectively help with the predictions?
Classification is a type of supervised machine learning problem where the target (response) variable is categorical. Given the training data, which contains the known label, the classifier approximates a mapping function (f) from the input variables (X) to output variables (Y). For more sources on classification, see Chapter 3 in An Introduction to Statistical Learning, Andrew Ng’s Machine Learning Course (Week 3), and Simplilearn’s tutorial on Classification.
Now it’s time to write some code! See my Github page for my full Python code (written in Jupyter Notebook).
First, we need to import some libraries: pandas (loading dataset), numpy (matrix manipulation), matplotlib and seaborn (visualization), and sklearn (building classifiers). Make sure they are installed already before importing them (guide on installing packages here).
import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitfrom pandas.plotting import parallel_coordinatesfrom sklearn.tree import DecisionTreeClassifier, plot_treefrom sklearn import metricsfrom sklearn.naive_bayes import GaussianNBfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysisfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVCfrom sklearn.linear_model import LogisticRegression
To load the dataset, we can use the read_csv function from pandas (my code also includes the option of loading through url).
data = pd.read_csv('data.csv')
After we load the data, we can take a look at the first couple of rows through the head function:
data.head(5)
Note: all four measurements are in centimeters.
First, let’s look at a numerical summary of each attribute through describe:
data.describe()
We can also check the class distribution using groupby and size:
data.groupby('species').size()
We can see that each class has the same number of instances.
Now, we can split the dataset into a training set and a test set. In general, we should also have a validation set, which is used to evaluate the performance of each classifier and fine-tune the model parameters in order to determine the best model. The test set is mainly used for reporting purposes. However, due to the small size of this dataset, we can simplify this process by using the test set to serve the purpose of the validation set.
In addition, I used a stratified hold-out approach to estimate model accuracy. The other approach is to do cross-validation to reduce bias and variances.
train, test = train_test_split(data, test_size = 0.4, stratify = data[‘species’], random_state = 42)
Note: The general rule of thumb is have 20–30% of dataset as the test set. Due to the small size of this dataset, I chose 40% to ensure there are enough data points to test the model performance.
After we split the dataset, we can go ahead to explore the training data. Both matplotlib and seaborn have great plotting tools then we can use for visualization.
Let’s first create some univariate plots, through a histogram for each feature:
n_bins = 10fig, axs = plt.subplots(2, 2)axs[0,0].hist(train['sepal_length'], bins = n_bins);axs[0,0].set_title('Sepal Length');axs[0,1].hist(train['sepal_width'], bins = n_bins);axs[0,1].set_title('Sepal Width');axs[1,0].hist(train['petal_length'], bins = n_bins);axs[1,0].set_title('Petal Length');axs[1,1].hist(train['petal_width'], bins = n_bins);axs[1,1].set_title('Petal Width');# add some spacing between subplotsfig.tight_layout(pad=1.0);
Note that for both petal_length and petal_width, there seems to be a group of data points that have smaller values than the others, suggesting that there might be different groups in this data.
Next, let’s try some side-by-side box plots:
fig, axs = plt.subplots(2, 2)fn = ["sepal_length", "sepal_width", "petal_length", "petal_width"]cn = ['setosa', 'versicolor', 'virginica']sns.boxplot(x = 'species', y = 'sepal_length', data = train, order = cn, ax = axs[0,0]);sns.boxplot(x = 'species', y = 'sepal_width', data = train, order = cn, ax = axs[0,1]);sns.boxplot(x = 'species', y = 'petal_length', data = train, order = cn, ax = axs[1,0]);sns.boxplot(x = 'species', y = 'petal_width', data = train, order = cn, ax = axs[1,1]);# add some spacing between subplotsfig.tight_layout(pad=1.0);
The two plots at the bottom suggest that that group of data points we saw earlier are setosas. Their petal measurements are smaller and less spread-out than those of the other two species as well. Comparing the other two species, versicolor has lower values than virginica on average.
Violin plot is another type of visualization, which combines the benefit of both histogram and box plot:
sns.violinplot(x="species", y="petal_length", data=train, size=5, order = cn, palette = 'colorblind');
Now we can make scatterplots of all-paired attributes by using seaborn’s pairplot function:
sns.pairplot(train, hue="species", height = 2, palette = 'colorblind');
Note that some variables seem to be highly correlated, e.g., petal_length and petal_width. In addition, the petal measurements separate the different species better than the sepal ones.
Next, let’s make a correlation matrix to quantitatively examine the relationship between variables:
corrmat = train.corr()sns.heatmap(corrmat, annot = True, square = True);
The main takeaway is that the petal measurements have highly positive correlation, while the sepal one are uncorrelated. Note that the petal features also have relatively high correlation with sepal_length, but not with sepal_width.
Another cool visualization tool is parallel coordinate plot, which represents each sample as a line.
parallel_coordinates(train, "species", color = ['blue', 'red', 'green']);
As we have seen before, petal measurements can separate species better than the sepal ones.
Now we are ready to build some classifiers (woo-hoo!)
To make our lives easier, let’s separate out the class label and features first:
X_train = train[['sepal_length','sepal_width','petal_length','petal_width']]y_train = train.speciesX_test = test[['sepal_length','sepal_width','petal_length','petal_width']]y_test = test.species
Classification Tree
The first classifier that comes up to my mind is a discriminative classification model called classification trees (read more here). The reason is that we get to see the classification rules and it is easy to interpret.
Let’s build one using sklearn (documentation), with a maximum depth of 3, and we can check its accuracy on the test data:
mod_dt = DecisionTreeClassifier(max_depth = 3, random_state = 1)mod_dt.fit(X_train,y_train)prediction=mod_dt.predict(X_test)print(‘The accuracy of the Decision Tree is’,”{:.3f}”.format(metrics.accuracy_score(prediction,y_test)))--------------------------------------------------------------------The accuracy of the Decision Tree is 0.983.
This decision tree predicts 98.3% of the test data correctly. One nice thing about this model is that you can see the importance of each predictor through its feature_importances_ attribute:
mod_dt.feature_importances_--------------------------------------------------------------------array([0. , 0. , 0.42430866, 0.57569134])
From the output and based on the indices of the four features, we know that the first two features (sepal measurements) are of no importance, and only the petal ones are used to build this tree.
Another nice thing about the decision tree is that we can visualize the classification rules through plot_tree:
plt.figure(figsize = (10,8))plot_tree(mod_dt, feature_names = fn, class_names = cn, filled = True);
Apart from each rule (e.g. the first criterion is petal_width ≤ 0.7), we can also see the Gini index (impurity measure) at each split, assigned class, etc. Note that all terminal nodes are pure besides the two “light purple” boxes at the bottom. We can less confident regarding instances in those two categories.
To demonstrate how easy it is to classify new data points, say a new instance has a petal length of 4.5cm and a petal width of 1.5cm, then we can predict it to be versicolor following the rules.
Since only the petal features are being used, we can visualize the decision boundary and plot the test data in 2D:
Out of the 60 data points, 59 are correctly classified. Another way to show the prediction results is through a confusion matrix:
disp = metrics.plot_confusion_matrix(mod_dt, X_test, y_test, display_labels=cn, cmap=plt.cm.Blues, normalize=None)disp.ax_.set_title('Decision Tree Confusion matrix, without normalization');
Through this matrix, we see that there is one versicolor which we predict to be virginica.
One downside is building a single tree is its instability, which can be improved through ensemble techniques such as random forests, boosting, etc. For now, let’s move on to the next model.
Gaussian Naive Bayes Classifier
One of the most popular classification models is Naive Bayes. It contains the word “Naive” because it has a key assumption of class-conditional independence, which means that given the class, each feature’s value is assumed to be independent of that of any other feature (read more here).
We know that it is clearly not the case here, evidenced by the high correlation between the petal features. Let’s examine the test accuracy using this model to see whether this assumption is robust:
The accuracy of the Guassian Naive Bayes Classifier on test data is 0.933
What about the result if we only use the petal features:
The accuracy of the Guassian Naive Bayes Classifier with 2 predictors on test data is 0.950
Interestingly, using only two features results in more correctly classified points, suggesting possibility of over-fitting when using all features. Seems that our Naive Bayes classifier did a decent job.
Linear Discriminant Analysis (LDA)
If we use multivariate Gaussian distribution to calculate the class conditional density instead of taking a product of univariate Gaussian distribution (used in Naive Bayes), we would then get a LDA model (read more here). The key assumption of LDA is that the covariances are equal among classes. We can examine the test accuracy using all features and only petal features:
The accuracy of the LDA Classifier on test data is 0.983The accuracy of the LDA Classifier with two predictors on test data is 0.933
Using all features boosts the test accuracy of our LDA model.
To visualize the decision boundary in 2D, we can use our LDA model with only petals and also plot the test data:
Four test points are misclassified — three virginica and one versicolor.
Now suppose we want to classify new data points with this model, we can just plot the point on this graph, and predicts according to the colored region it belonged to.
Quadratic Discriminant Analysis (QDA)
The difference between LDA and QDA is that QDA does NOT assume the covariances to be equal across classes, and it is called “quadratic” because the decision boundary is a quadratic function.
The accuracy of the QDA Classifier is 0.983The accuracy of the QDA Classifier with two predictors is 0.967
It has the same accuracy with LDA in the case of all features, and it performs slightly better when only using petals.
Similarly, let’s plot the decision boundary for QDA (model with only petals):
K Nearest Neighbors (K-NN)
Now, let’s switch gears a little and take a look at a non-parametric generative model called KNN (read more here). It is a popular model since it is relatively simple and easy to implement. However, we need to be aware of the curse of dimensionality when number of features gets large.
Let’s plot the test accuracy with different choices of K:
We can see that the accuracy is highest (about 0.965) when K is 3, or between 7 and 10. Compare to the previous models, it is less straightforward to classify new data points since we would need to look at its K closest neighbors in four-dimensional space.
Other Models
I also explored other models such as logistic regression, support vector machine classifier, etc. See my code on Github for details.
Note that the SVC (with linear kernel) achieved a test accuracy of 100%!
We should be pretty confident now since most of our models performed better than 95% accuracy.
Here are a few ideas for future studies:
Create a validation set and run cross-validation to get accurate estimates and compare the spread and mean accuracy between each of them.Find other data sources that include other iris species and their sepal/petal measurements (include other attributes too if possible), and examine the new classification accuracy.Make an interactive web app that predicts species given measurements inputted from users (Check out my simple web demo with Heroku deployment here)
Create a validation set and run cross-validation to get accurate estimates and compare the spread and mean accuracy between each of them.
Find other data sources that include other iris species and their sepal/petal measurements (include other attributes too if possible), and examine the new classification accuracy.
Make an interactive web app that predicts species given measurements inputted from users (Check out my simple web demo with Heroku deployment here)
Let’s recap.
We explored the Iris dataset, and then built a few popular classifiers using sklearn. We saw that the petal measurements are more helpful at classifying instances than the sepal ones. Furthermore, most models achieved a test accuracy of over 95%.
I hope you enjoy this blog post and please share any thought that you may have :)
Check out my other post on exploring the Yelp dataset:
towardsdatascience.com
[1] https://archive.ics.uci.edu/ml/datasets/iris[2] https://machinelearningmastery.com/machine-learning-in-python-step-by-step/ | [
{
"code": null,
"e": 363,
"s": 172,
"text": "For a moment, imagine that you are not a flower expert (if you are an expert, good for you!). Can you distinguish between three different species of iris — setosa, versicolor, and virginica?"
},
{
"code": null,
"e": 381,
"s": 363,
"text": "I know I can’t..."
},
{
"code": null,
"e": 499,
"s": 381,
"text": "BUT what if we have a dataset that contains instances of these species, with measurements of their sepals and petals?"
},
{
"code": null,
"e": 613,
"s": 499,
"text": "In other words, can we learn anything from this dataset that would help us distinguish between the three species?"
},
{
"code": null,
"e": 773,
"s": 613,
"text": "Why are we choosing this dataset?What questions are we trying to answer?What can we find in this dataset?Which classifiers are we building?What can we do next?"
},
{
"code": null,
"e": 807,
"s": 773,
"text": "Why are we choosing this dataset?"
},
{
"code": null,
"e": 847,
"s": 807,
"text": "What questions are we trying to answer?"
},
{
"code": null,
"e": 881,
"s": 847,
"text": "What can we find in this dataset?"
},
{
"code": null,
"e": 916,
"s": 881,
"text": "Which classifiers are we building?"
},
{
"code": null,
"e": 937,
"s": 916,
"text": "What can we do next?"
},
{
"code": null,
"e": 1299,
"s": 937,
"text": "In this blog post, I will explore the Iris dataset from the UCI Machine Learning Repository. Excerpted from its website, it is said to be “perhaps the best known database to be found in the pattern recognition literature” [1]. In addition, Jason Brownlee who started the community of Machine Learning Mastery called it the “Hello World” of machine learning [2]."
},
{
"code": null,
"e": 1478,
"s": 1299,
"text": "I would recommend this dataset to anyone who is a beginner in data science and is eager to build their first ML model. See below for some of nice characteristics of this dataset:"
},
{
"code": null,
"e": 1605,
"s": 1478,
"text": "150 samples, with 4 attributes (same units, all numeric)Balanced class distribution (50 samples for each class)No missing data"
},
{
"code": null,
"e": 1662,
"s": 1605,
"text": "150 samples, with 4 attributes (same units, all numeric)"
},
{
"code": null,
"e": 1718,
"s": 1662,
"text": "Balanced class distribution (50 samples for each class)"
},
{
"code": null,
"e": 1734,
"s": 1718,
"text": "No missing data"
},
{
"code": null,
"e": 2128,
"s": 1734,
"text": "As you can see, these characteristics can help minimize the time you need to spend in the data preparation process so you can focus on building the ML model. It is NOT that the preparation stage is not important. On the contrary, this process is so important that it can be too time-consuming for some beginners that they may overwhelm themselves before getting to the model development stage."
},
{
"code": null,
"e": 2410,
"s": 2128,
"text": "As an example, the popular dataset House Prices: Advanced Regression Techniques from Kaggle has about 80 features and more than 20% of them contain some level of missing data. In that case, you might need to spend some time understanding the attributes and imputing missing values."
},
{
"code": null,
"e": 2696,
"s": 2410,
"text": "Now hopefully your confidence level (no stats pun intended) is relatively high. Here are some resources on data wrangling that you can read through as you work on more complex datasets and tasks: Dimensionality reduction, Imbalanced classification, Feature engineering, and Imputation."
},
{
"code": null,
"e": 2841,
"s": 2696,
"text": "There are two questions that we want to be able to answer after exploring this dataset, which are quite typical in most classification problems:"
},
{
"code": null,
"e": 3012,
"s": 2841,
"text": "Prediction — given new data points, how accurately can the model predict their classes (species)?Inference — Which predictor(s) can effectively help with the predictions?"
},
{
"code": null,
"e": 3110,
"s": 3012,
"text": "Prediction — given new data points, how accurately can the model predict their classes (species)?"
},
{
"code": null,
"e": 3184,
"s": 3110,
"text": "Inference — Which predictor(s) can effectively help with the predictions?"
},
{
"code": null,
"e": 3649,
"s": 3184,
"text": "Classification is a type of supervised machine learning problem where the target (response) variable is categorical. Given the training data, which contains the known label, the classifier approximates a mapping function (f) from the input variables (X) to output variables (Y). For more sources on classification, see Chapter 3 in An Introduction to Statistical Learning, Andrew Ng’s Machine Learning Course (Week 3), and Simplilearn’s tutorial on Classification."
},
{
"code": null,
"e": 3757,
"s": 3649,
"text": "Now it’s time to write some code! See my Github page for my full Python code (written in Jupyter Notebook)."
},
{
"code": null,
"e": 4025,
"s": 3757,
"text": "First, we need to import some libraries: pandas (loading dataset), numpy (matrix manipulation), matplotlib and seaborn (visualization), and sklearn (building classifiers). Make sure they are installed already before importing them (guide on installing packages here)."
},
{
"code": null,
"e": 4569,
"s": 4025,
"text": "import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitfrom pandas.plotting import parallel_coordinatesfrom sklearn.tree import DecisionTreeClassifier, plot_treefrom sklearn import metricsfrom sklearn.naive_bayes import GaussianNBfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysisfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVCfrom sklearn.linear_model import LogisticRegression"
},
{
"code": null,
"e": 4694,
"s": 4569,
"text": "To load the dataset, we can use the read_csv function from pandas (my code also includes the option of loading through url)."
},
{
"code": null,
"e": 4725,
"s": 4694,
"text": "data = pd.read_csv('data.csv')"
},
{
"code": null,
"e": 4823,
"s": 4725,
"text": "After we load the data, we can take a look at the first couple of rows through the head function:"
},
{
"code": null,
"e": 4836,
"s": 4823,
"text": "data.head(5)"
},
{
"code": null,
"e": 4884,
"s": 4836,
"text": "Note: all four measurements are in centimeters."
},
{
"code": null,
"e": 4961,
"s": 4884,
"text": "First, let’s look at a numerical summary of each attribute through describe:"
},
{
"code": null,
"e": 4977,
"s": 4961,
"text": "data.describe()"
},
{
"code": null,
"e": 5042,
"s": 4977,
"text": "We can also check the class distribution using groupby and size:"
},
{
"code": null,
"e": 5073,
"s": 5042,
"text": "data.groupby('species').size()"
},
{
"code": null,
"e": 5134,
"s": 5073,
"text": "We can see that each class has the same number of instances."
},
{
"code": null,
"e": 5579,
"s": 5134,
"text": "Now, we can split the dataset into a training set and a test set. In general, we should also have a validation set, which is used to evaluate the performance of each classifier and fine-tune the model parameters in order to determine the best model. The test set is mainly used for reporting purposes. However, due to the small size of this dataset, we can simplify this process by using the test set to serve the purpose of the validation set."
},
{
"code": null,
"e": 5733,
"s": 5579,
"text": "In addition, I used a stratified hold-out approach to estimate model accuracy. The other approach is to do cross-validation to reduce bias and variances."
},
{
"code": null,
"e": 5834,
"s": 5733,
"text": "train, test = train_test_split(data, test_size = 0.4, stratify = data[‘species’], random_state = 42)"
},
{
"code": null,
"e": 6030,
"s": 5834,
"text": "Note: The general rule of thumb is have 20–30% of dataset as the test set. Due to the small size of this dataset, I chose 40% to ensure there are enough data points to test the model performance."
},
{
"code": null,
"e": 6193,
"s": 6030,
"text": "After we split the dataset, we can go ahead to explore the training data. Both matplotlib and seaborn have great plotting tools then we can use for visualization."
},
{
"code": null,
"e": 6273,
"s": 6193,
"text": "Let’s first create some univariate plots, through a histogram for each feature:"
},
{
"code": null,
"e": 6719,
"s": 6273,
"text": "n_bins = 10fig, axs = plt.subplots(2, 2)axs[0,0].hist(train['sepal_length'], bins = n_bins);axs[0,0].set_title('Sepal Length');axs[0,1].hist(train['sepal_width'], bins = n_bins);axs[0,1].set_title('Sepal Width');axs[1,0].hist(train['petal_length'], bins = n_bins);axs[1,0].set_title('Petal Length');axs[1,1].hist(train['petal_width'], bins = n_bins);axs[1,1].set_title('Petal Width');# add some spacing between subplotsfig.tight_layout(pad=1.0);"
},
{
"code": null,
"e": 6913,
"s": 6719,
"text": "Note that for both petal_length and petal_width, there seems to be a group of data points that have smaller values than the others, suggesting that there might be different groups in this data."
},
{
"code": null,
"e": 6958,
"s": 6913,
"text": "Next, let’s try some side-by-side box plots:"
},
{
"code": null,
"e": 7509,
"s": 6958,
"text": "fig, axs = plt.subplots(2, 2)fn = [\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\"]cn = ['setosa', 'versicolor', 'virginica']sns.boxplot(x = 'species', y = 'sepal_length', data = train, order = cn, ax = axs[0,0]);sns.boxplot(x = 'species', y = 'sepal_width', data = train, order = cn, ax = axs[0,1]);sns.boxplot(x = 'species', y = 'petal_length', data = train, order = cn, ax = axs[1,0]);sns.boxplot(x = 'species', y = 'petal_width', data = train, order = cn, ax = axs[1,1]);# add some spacing between subplotsfig.tight_layout(pad=1.0);"
},
{
"code": null,
"e": 7794,
"s": 7509,
"text": "The two plots at the bottom suggest that that group of data points we saw earlier are setosas. Their petal measurements are smaller and less spread-out than those of the other two species as well. Comparing the other two species, versicolor has lower values than virginica on average."
},
{
"code": null,
"e": 7899,
"s": 7794,
"text": "Violin plot is another type of visualization, which combines the benefit of both histogram and box plot:"
},
{
"code": null,
"e": 8002,
"s": 7899,
"text": "sns.violinplot(x=\"species\", y=\"petal_length\", data=train, size=5, order = cn, palette = 'colorblind');"
},
{
"code": null,
"e": 8094,
"s": 8002,
"text": "Now we can make scatterplots of all-paired attributes by using seaborn’s pairplot function:"
},
{
"code": null,
"e": 8166,
"s": 8094,
"text": "sns.pairplot(train, hue=\"species\", height = 2, palette = 'colorblind');"
},
{
"code": null,
"e": 8352,
"s": 8166,
"text": "Note that some variables seem to be highly correlated, e.g., petal_length and petal_width. In addition, the petal measurements separate the different species better than the sepal ones."
},
{
"code": null,
"e": 8452,
"s": 8352,
"text": "Next, let’s make a correlation matrix to quantitatively examine the relationship between variables:"
},
{
"code": null,
"e": 8525,
"s": 8452,
"text": "corrmat = train.corr()sns.heatmap(corrmat, annot = True, square = True);"
},
{
"code": null,
"e": 8758,
"s": 8525,
"text": "The main takeaway is that the petal measurements have highly positive correlation, while the sepal one are uncorrelated. Note that the petal features also have relatively high correlation with sepal_length, but not with sepal_width."
},
{
"code": null,
"e": 8859,
"s": 8758,
"text": "Another cool visualization tool is parallel coordinate plot, which represents each sample as a line."
},
{
"code": null,
"e": 8933,
"s": 8859,
"text": "parallel_coordinates(train, \"species\", color = ['blue', 'red', 'green']);"
},
{
"code": null,
"e": 9025,
"s": 8933,
"text": "As we have seen before, petal measurements can separate species better than the sepal ones."
},
{
"code": null,
"e": 9079,
"s": 9025,
"text": "Now we are ready to build some classifiers (woo-hoo!)"
},
{
"code": null,
"e": 9160,
"s": 9079,
"text": "To make our lives easier, let’s separate out the class label and features first:"
},
{
"code": null,
"e": 9355,
"s": 9160,
"text": "X_train = train[['sepal_length','sepal_width','petal_length','petal_width']]y_train = train.speciesX_test = test[['sepal_length','sepal_width','petal_length','petal_width']]y_test = test.species"
},
{
"code": null,
"e": 9375,
"s": 9355,
"text": "Classification Tree"
},
{
"code": null,
"e": 9595,
"s": 9375,
"text": "The first classifier that comes up to my mind is a discriminative classification model called classification trees (read more here). The reason is that we get to see the classification rules and it is easy to interpret."
},
{
"code": null,
"e": 9717,
"s": 9595,
"text": "Let’s build one using sklearn (documentation), with a maximum depth of 3, and we can check its accuracy on the test data:"
},
{
"code": null,
"e": 10057,
"s": 9717,
"text": "mod_dt = DecisionTreeClassifier(max_depth = 3, random_state = 1)mod_dt.fit(X_train,y_train)prediction=mod_dt.predict(X_test)print(‘The accuracy of the Decision Tree is’,”{:.3f}”.format(metrics.accuracy_score(prediction,y_test)))--------------------------------------------------------------------The accuracy of the Decision Tree is 0.983."
},
{
"code": null,
"e": 10248,
"s": 10057,
"text": "This decision tree predicts 98.3% of the test data correctly. One nice thing about this model is that you can see the importance of each predictor through its feature_importances_ attribute:"
},
{
"code": null,
"e": 10399,
"s": 10248,
"text": "mod_dt.feature_importances_--------------------------------------------------------------------array([0. , 0. , 0.42430866, 0.57569134])"
},
{
"code": null,
"e": 10594,
"s": 10399,
"text": "From the output and based on the indices of the four features, we know that the first two features (sepal measurements) are of no importance, and only the petal ones are used to build this tree."
},
{
"code": null,
"e": 10706,
"s": 10594,
"text": "Another nice thing about the decision tree is that we can visualize the classification rules through plot_tree:"
},
{
"code": null,
"e": 10806,
"s": 10706,
"text": "plt.figure(figsize = (10,8))plot_tree(mod_dt, feature_names = fn, class_names = cn, filled = True);"
},
{
"code": null,
"e": 11119,
"s": 10806,
"text": "Apart from each rule (e.g. the first criterion is petal_width ≤ 0.7), we can also see the Gini index (impurity measure) at each split, assigned class, etc. Note that all terminal nodes are pure besides the two “light purple” boxes at the bottom. We can less confident regarding instances in those two categories."
},
{
"code": null,
"e": 11314,
"s": 11119,
"text": "To demonstrate how easy it is to classify new data points, say a new instance has a petal length of 4.5cm and a petal width of 1.5cm, then we can predict it to be versicolor following the rules."
},
{
"code": null,
"e": 11429,
"s": 11314,
"text": "Since only the petal features are being used, we can visualize the decision boundary and plot the test data in 2D:"
},
{
"code": null,
"e": 11559,
"s": 11429,
"text": "Out of the 60 data points, 59 are correctly classified. Another way to show the prediction results is through a confusion matrix:"
},
{
"code": null,
"e": 11846,
"s": 11559,
"text": "disp = metrics.plot_confusion_matrix(mod_dt, X_test, y_test, display_labels=cn, cmap=plt.cm.Blues, normalize=None)disp.ax_.set_title('Decision Tree Confusion matrix, without normalization');"
},
{
"code": null,
"e": 11937,
"s": 11846,
"text": "Through this matrix, we see that there is one versicolor which we predict to be virginica."
},
{
"code": null,
"e": 12127,
"s": 11937,
"text": "One downside is building a single tree is its instability, which can be improved through ensemble techniques such as random forests, boosting, etc. For now, let’s move on to the next model."
},
{
"code": null,
"e": 12159,
"s": 12127,
"text": "Gaussian Naive Bayes Classifier"
},
{
"code": null,
"e": 12448,
"s": 12159,
"text": "One of the most popular classification models is Naive Bayes. It contains the word “Naive” because it has a key assumption of class-conditional independence, which means that given the class, each feature’s value is assumed to be independent of that of any other feature (read more here)."
},
{
"code": null,
"e": 12647,
"s": 12448,
"text": "We know that it is clearly not the case here, evidenced by the high correlation between the petal features. Let’s examine the test accuracy using this model to see whether this assumption is robust:"
},
{
"code": null,
"e": 12721,
"s": 12647,
"text": "The accuracy of the Guassian Naive Bayes Classifier on test data is 0.933"
},
{
"code": null,
"e": 12778,
"s": 12721,
"text": "What about the result if we only use the petal features:"
},
{
"code": null,
"e": 12870,
"s": 12778,
"text": "The accuracy of the Guassian Naive Bayes Classifier with 2 predictors on test data is 0.950"
},
{
"code": null,
"e": 13074,
"s": 12870,
"text": "Interestingly, using only two features results in more correctly classified points, suggesting possibility of over-fitting when using all features. Seems that our Naive Bayes classifier did a decent job."
},
{
"code": null,
"e": 13109,
"s": 13074,
"text": "Linear Discriminant Analysis (LDA)"
},
{
"code": null,
"e": 13484,
"s": 13109,
"text": "If we use multivariate Gaussian distribution to calculate the class conditional density instead of taking a product of univariate Gaussian distribution (used in Naive Bayes), we would then get a LDA model (read more here). The key assumption of LDA is that the covariances are equal among classes. We can examine the test accuracy using all features and only petal features:"
},
{
"code": null,
"e": 13617,
"s": 13484,
"text": "The accuracy of the LDA Classifier on test data is 0.983The accuracy of the LDA Classifier with two predictors on test data is 0.933"
},
{
"code": null,
"e": 13679,
"s": 13617,
"text": "Using all features boosts the test accuracy of our LDA model."
},
{
"code": null,
"e": 13792,
"s": 13679,
"text": "To visualize the decision boundary in 2D, we can use our LDA model with only petals and also plot the test data:"
},
{
"code": null,
"e": 13865,
"s": 13792,
"text": "Four test points are misclassified — three virginica and one versicolor."
},
{
"code": null,
"e": 14033,
"s": 13865,
"text": "Now suppose we want to classify new data points with this model, we can just plot the point on this graph, and predicts according to the colored region it belonged to."
},
{
"code": null,
"e": 14071,
"s": 14033,
"text": "Quadratic Discriminant Analysis (QDA)"
},
{
"code": null,
"e": 14262,
"s": 14071,
"text": "The difference between LDA and QDA is that QDA does NOT assume the covariances to be equal across classes, and it is called “quadratic” because the decision boundary is a quadratic function."
},
{
"code": null,
"e": 14369,
"s": 14262,
"text": "The accuracy of the QDA Classifier is 0.983The accuracy of the QDA Classifier with two predictors is 0.967"
},
{
"code": null,
"e": 14488,
"s": 14369,
"text": "It has the same accuracy with LDA in the case of all features, and it performs slightly better when only using petals."
},
{
"code": null,
"e": 14566,
"s": 14488,
"text": "Similarly, let’s plot the decision boundary for QDA (model with only petals):"
},
{
"code": null,
"e": 14593,
"s": 14566,
"text": "K Nearest Neighbors (K-NN)"
},
{
"code": null,
"e": 14879,
"s": 14593,
"text": "Now, let’s switch gears a little and take a look at a non-parametric generative model called KNN (read more here). It is a popular model since it is relatively simple and easy to implement. However, we need to be aware of the curse of dimensionality when number of features gets large."
},
{
"code": null,
"e": 14937,
"s": 14879,
"text": "Let’s plot the test accuracy with different choices of K:"
},
{
"code": null,
"e": 15194,
"s": 14937,
"text": "We can see that the accuracy is highest (about 0.965) when K is 3, or between 7 and 10. Compare to the previous models, it is less straightforward to classify new data points since we would need to look at its K closest neighbors in four-dimensional space."
},
{
"code": null,
"e": 15207,
"s": 15194,
"text": "Other Models"
},
{
"code": null,
"e": 15340,
"s": 15207,
"text": "I also explored other models such as logistic regression, support vector machine classifier, etc. See my code on Github for details."
},
{
"code": null,
"e": 15413,
"s": 15340,
"text": "Note that the SVC (with linear kernel) achieved a test accuracy of 100%!"
},
{
"code": null,
"e": 15508,
"s": 15413,
"text": "We should be pretty confident now since most of our models performed better than 95% accuracy."
},
{
"code": null,
"e": 15549,
"s": 15508,
"text": "Here are a few ideas for future studies:"
},
{
"code": null,
"e": 16013,
"s": 15549,
"text": "Create a validation set and run cross-validation to get accurate estimates and compare the spread and mean accuracy between each of them.Find other data sources that include other iris species and their sepal/petal measurements (include other attributes too if possible), and examine the new classification accuracy.Make an interactive web app that predicts species given measurements inputted from users (Check out my simple web demo with Heroku deployment here)"
},
{
"code": null,
"e": 16151,
"s": 16013,
"text": "Create a validation set and run cross-validation to get accurate estimates and compare the spread and mean accuracy between each of them."
},
{
"code": null,
"e": 16331,
"s": 16151,
"text": "Find other data sources that include other iris species and their sepal/petal measurements (include other attributes too if possible), and examine the new classification accuracy."
},
{
"code": null,
"e": 16479,
"s": 16331,
"text": "Make an interactive web app that predicts species given measurements inputted from users (Check out my simple web demo with Heroku deployment here)"
},
{
"code": null,
"e": 16492,
"s": 16479,
"text": "Let’s recap."
},
{
"code": null,
"e": 16739,
"s": 16492,
"text": "We explored the Iris dataset, and then built a few popular classifiers using sklearn. We saw that the petal measurements are more helpful at classifying instances than the sepal ones. Furthermore, most models achieved a test accuracy of over 95%."
},
{
"code": null,
"e": 16821,
"s": 16739,
"text": "I hope you enjoy this blog post and please share any thought that you may have :)"
},
{
"code": null,
"e": 16876,
"s": 16821,
"text": "Check out my other post on exploring the Yelp dataset:"
},
{
"code": null,
"e": 16899,
"s": 16876,
"text": "towardsdatascience.com"
}
] |
Descending order in Map and Multimap of C++ STL | Generally, the default behavior of map and multimap map is to store elements is in ascending order. But we can store element in descending order by using the greater function.
The map in descending order:
m::find() – Returns an iterator to the element with key value ‘b’ in the map if found, else returns the iterator to end.
m::find() – Returns an iterator to the element with key value ‘b’ in the map if found, else returns the iterator to end.
m::erase() – Removes the key value from the map.
m::erase() – Removes the key value from the map.
m:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key.
m:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key.
m insert() – To insert elements in the map container.
m insert() – To insert elements in the map container.
m size() – Returns the number of elements in the map container.
m size() – Returns the number of elements in the map container.
m count() – Returns the number of matches to element with key value ‘a’ or ‘f’ in the map.
m count() – Returns the number of matches to element with key value ‘a’ or ‘f’ in the map.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main () {
map<char, int,greater <int>> m;
map<char, int>::iterator it;
m.insert (pair<char, int>('a', 10));
m.insert (pair<char, int>('b', 20));
m.insert (pair<char, int>('c', 30));
m.insert (pair<char, int>('d', 40));
cout<<"Size of the map: "<< m.size() <<endl;
cout << "map contains:\n";
for (it = m.begin(); it != m.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
for (char c = 'a'; c <= 'd'; c++) {
cout << "There are " << m.count(c) << " element(s) with key " << c << ":";
map<char, int>::iterator it;
for (it = m.equal_range(c).first; it != m.equal_range(c).second; ++it)
cout << ' ' << (*it).second;
cout << endl;
}
if (m.count('a'))
cout << "The key a is present\n";
else
cout << "The key a is not present\n";
if (m.count('f'))
cout << "The key f is present\n";
else
cout << "The key f is not present\n";
it = m.find('b');
m.erase (it);
cout<<"Size of the map: "<<m.size()<<endl;
cout << "map contains:\n";
for (it = m.begin(); it != m.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
return 0;
}
Size of the map: 4
map contains:
d => 40
c => 30
b => 20
a => 10
There are 1 element(s) with key a: 10
There are 1 element(s) with key b: 20
There are 1 element(s) with key c: 30
There are 1 element(s) with key d: 40
The key a is present
The key f is not present
Size of the map: 3
map contains:
d => 40
c => 30
a => 10
Multimap in descending order:
Functions are used here:
mm::find() – Returns an iterator to the element with key value ‘b’ in the multimap if found, else returns the iterator to end.
mm::find() – Returns an iterator to the element with key value ‘b’ in the multimap if found, else returns the iterator to end.
mm::erase() – Removes the key value from the multimap.
mm::erase() – Removes the key value from the multimap.
mm:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key.
mm:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key.
mm insert() – To insert elements in the multimap container.
mm insert() – To insert elements in the multimap container.
mm size() – Returns the number of elements in the multimap container.
mm size() – Returns the number of elements in the multimap container.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main () {
multimap<char, int,greater <char>> mm;
multimap<char, int>::iterator it;
mm.insert (pair<char, int>('a', 10));
mm.insert (pair<char, int>('b', 20));
mm.insert (pair<char, int>('a', 30));
mm.insert (pair<char, int>('b', 40));
cout<<"Size of the multimap: "<< mm.size() <<endl;
cout << "multimap contains:\n";
for (it = mm.begin(); it != mm.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
for (char c = 'a'; c <= 'd'; c++) {
cout << "There are " << mm.count(c) << " elements with key " << c << ":";
map<char, int>::iterator it;
for (it = mm.equal_range(c).first; it != mm.equal_range(c).second; ++it)
cout << ' ' << (*it).second;
cout << endl;
}
if (mm.count('a'))
cout << "The key a is present\n";
else
cout << "The key a is not present\n";
if (mm.count('f'))
cout << "The key f is present\n";
else
cout << "The key f is not present\n";
it = mm.find('b');
mm.erase (it);
cout<<"Size of the multimap: "<<mm.size()<<endl;
cout << "multiap contains:\n";
for (it = mm.begin(); it != mm.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
return 0;
}
Size of the multimap: 4
multimap contains:
b => 20
b => 40
a => 10
a => 30
There are 2 elements with key a: 10 30
There are 2 elements with key b: 20 40
There are 0 elements with key c:
There are 0 elements with key d:
The key a is present
The key f is not present
Size of the multimap: 3
multiap contains:
b => 40
a => 10
a => 30 | [
{
"code": null,
"e": 1238,
"s": 1062,
"text": "Generally, the default behavior of map and multimap map is to store elements is in ascending order. But we can store element in descending order by using the greater function."
},
{
"code": null,
"e": 1267,
"s": 1238,
"text": "The map in descending order:"
},
{
"code": null,
"e": 1388,
"s": 1267,
"text": "m::find() – Returns an iterator to the element with key value ‘b’ in the map if found, else returns the iterator to end."
},
{
"code": null,
"e": 1509,
"s": 1388,
"text": "m::find() – Returns an iterator to the element with key value ‘b’ in the map if found, else returns the iterator to end."
},
{
"code": null,
"e": 1558,
"s": 1509,
"text": "m::erase() – Removes the key value from the map."
},
{
"code": null,
"e": 1607,
"s": 1558,
"text": "m::erase() – Removes the key value from the map."
},
{
"code": null,
"e": 1782,
"s": 1607,
"text": "m:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key."
},
{
"code": null,
"e": 1957,
"s": 1782,
"text": "m:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key."
},
{
"code": null,
"e": 2011,
"s": 1957,
"text": "m insert() – To insert elements in the map container."
},
{
"code": null,
"e": 2065,
"s": 2011,
"text": "m insert() – To insert elements in the map container."
},
{
"code": null,
"e": 2129,
"s": 2065,
"text": "m size() – Returns the number of elements in the map container."
},
{
"code": null,
"e": 2193,
"s": 2129,
"text": "m size() – Returns the number of elements in the map container."
},
{
"code": null,
"e": 2284,
"s": 2193,
"text": "m count() – Returns the number of matches to element with key value ‘a’ or ‘f’ in the map."
},
{
"code": null,
"e": 2375,
"s": 2284,
"text": "m count() – Returns the number of matches to element with key value ‘a’ or ‘f’ in the map."
},
{
"code": null,
"e": 3639,
"s": 2375,
"text": "#include <iostream>\n#include <map>\n#include <string>\nusing namespace std;\nint main () {\n map<char, int,greater <int>> m;\n map<char, int>::iterator it;\n m.insert (pair<char, int>('a', 10));\n m.insert (pair<char, int>('b', 20));\n m.insert (pair<char, int>('c', 30));\n m.insert (pair<char, int>('d', 40));\n cout<<\"Size of the map: \"<< m.size() <<endl;\n cout << \"map contains:\\n\";\n for (it = m.begin(); it != m.end(); ++it)\n cout << (*it).first << \" => \" << (*it).second << '\\n';\n for (char c = 'a'; c <= 'd'; c++) {\n cout << \"There are \" << m.count(c) << \" element(s) with key \" << c << \":\";\n map<char, int>::iterator it;\n for (it = m.equal_range(c).first; it != m.equal_range(c).second; ++it)\n cout << ' ' << (*it).second;\n cout << endl;\n }\n if (m.count('a'))\n cout << \"The key a is present\\n\";\n else\n cout << \"The key a is not present\\n\";\n if (m.count('f'))\n cout << \"The key f is present\\n\";\n else\n cout << \"The key f is not present\\n\";\n it = m.find('b');\n m.erase (it);\n cout<<\"Size of the map: \"<<m.size()<<endl;\n cout << \"map contains:\\n\";\n for (it = m.begin(); it != m.end(); ++it)\n cout << (*it).first << \" => \" << (*it).second << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 3959,
"s": 3639,
"text": "Size of the map: 4\nmap contains:\nd => 40\nc => 30\nb => 20\na => 10\nThere are 1 element(s) with key a: 10\nThere are 1 element(s) with key b: 20\nThere are 1 element(s) with key c: 30\nThere are 1 element(s) with key d: 40\nThe key a is present\nThe key f is not present\nSize of the map: 3\nmap contains:\nd => 40\nc => 30\na => 10"
},
{
"code": null,
"e": 3989,
"s": 3959,
"text": "Multimap in descending order:"
},
{
"code": null,
"e": 4014,
"s": 3989,
"text": "Functions are used here:"
},
{
"code": null,
"e": 4141,
"s": 4014,
"text": "mm::find() – Returns an iterator to the element with key value ‘b’ in the multimap if found, else returns the iterator to end."
},
{
"code": null,
"e": 4268,
"s": 4141,
"text": "mm::find() – Returns an iterator to the element with key value ‘b’ in the multimap if found, else returns the iterator to end."
},
{
"code": null,
"e": 4323,
"s": 4268,
"text": "mm::erase() – Removes the key value from the multimap."
},
{
"code": null,
"e": 4378,
"s": 4323,
"text": "mm::erase() – Removes the key value from the multimap."
},
{
"code": null,
"e": 4554,
"s": 4378,
"text": "mm:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key."
},
{
"code": null,
"e": 4730,
"s": 4554,
"text": "mm:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key."
},
{
"code": null,
"e": 4790,
"s": 4730,
"text": "mm insert() – To insert elements in the multimap container."
},
{
"code": null,
"e": 4850,
"s": 4790,
"text": "mm insert() – To insert elements in the multimap container."
},
{
"code": null,
"e": 4920,
"s": 4850,
"text": "mm size() – Returns the number of elements in the multimap container."
},
{
"code": null,
"e": 4990,
"s": 4920,
"text": "mm size() – Returns the number of elements in the multimap container."
},
{
"code": null,
"e": 6286,
"s": 4990,
"text": "#include <iostream>\n#include <map>\n#include <string>\nusing namespace std;\nint main () {\n multimap<char, int,greater <char>> mm;\n multimap<char, int>::iterator it;\n mm.insert (pair<char, int>('a', 10));\n mm.insert (pair<char, int>('b', 20));\n mm.insert (pair<char, int>('a', 30));\n mm.insert (pair<char, int>('b', 40));\n cout<<\"Size of the multimap: \"<< mm.size() <<endl;\n cout << \"multimap contains:\\n\";\n for (it = mm.begin(); it != mm.end(); ++it)\n cout << (*it).first << \" => \" << (*it).second << '\\n';\n for (char c = 'a'; c <= 'd'; c++) {\n cout << \"There are \" << mm.count(c) << \" elements with key \" << c << \":\";\n map<char, int>::iterator it;\n for (it = mm.equal_range(c).first; it != mm.equal_range(c).second; ++it)\n cout << ' ' << (*it).second;\n cout << endl;\n }\n if (mm.count('a'))\n cout << \"The key a is present\\n\";\n else\n cout << \"The key a is not present\\n\";\n if (mm.count('f'))\n cout << \"The key f is present\\n\";\n else\n cout << \"The key f is not present\\n\";\n it = mm.find('b');\n mm.erase (it);\n cout<<\"Size of the multimap: \"<<mm.size()<<endl;\n cout << \"multiap contains:\\n\";\n for (it = mm.begin(); it != mm.end(); ++it)\n cout << (*it).first << \" => \" << (*it).second << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 6617,
"s": 6286,
"text": "Size of the multimap: 4\nmultimap contains:\nb => 20\nb => 40\na => 10\na => 30\nThere are 2 elements with key a: 10 30\nThere are 2 elements with key b: 20 40\nThere are 0 elements with key c:\nThere are 0 elements with key d:\nThe key a is present\nThe key f is not present\nSize of the multimap: 3\nmultiap contains:\nb => 40\na => 10\na => 30"
}
] |
Bye-bye PowerPoint. Hello Marp!. Could this free Markdown-based tool... | by Dario Radečić | Towards Data Science | Do you find PowerPoint annoying? Me too. It can be laggy at times and has an overwhelming number of options. If you’re in the market for something simpler, today’s your lucky day. Marp might be the right tool to save you time and nerves.
It’s a Visual Studio Code extension based on Markdown, and lets you create presentations that can be exported as PPTX, PDF, and HTML. Today you’ll learn the basics and create your first presentation.
Don’t feel like reading? Watch my video instead:
You should already have Visual Studio Code installed. It’s a code editor that lets you write anything from readme files to machine learning models. You won’t write code today — if you don’t count Markdown as code, which you shouldn’t.
Once in Visual Studio Code, click on the Extensions tab and search for Marp:
Hit the Install button and you’ll be good to go after a couple of seconds. Then create a folder anywhere on your machine and open it in VSCode.
I’ve named mine marp_slideshow and created a slideshow.md file inside. Feel free to change the names per your liking.
And that’s it — you’re now ready to create your first slide.
Do you have the slideshow.md file open? Good. Proceed with the boilerplate. You’ll have to specify you’re using Marp, because the Markdown document can’t know it by default:
---marp: true---
Let’s also add an H1 tag below, just so there’s something to see on the screen:
# Slide 1 Title
You can now click on the Preview icon to see your presentation:
So far, so good. Leave the Preview window open — it will update automatically as you write.
You can also change the presentation theme:
---marp: true:theme: gaia---
I’m not the biggest fan of the yellow color, so I’ll show you how to change it a bit later.
You can press CTRL + SPACE to list all available properties. Two of these are author and size, so let’s tweak them:
---marp: true:theme: gaiaauthor: Dario Radečićsize: 4:3---
You can see how we’ve moved from 16:9 to 4:3 aspect ratio, but it’s a personal preference thing.
Next, let’s see how you can use Markdown to add content to your slides. The snippet below adds two bullet points. The second one has child elements, and each one is styled differently. These are here to show you how to bold, italicize, and preformat your text:
# Welcome to MARP- It's an awesome VSCode extension for making presentations.- It's based on Markdown: - **Bold** - _Italic_ - `code`
Easy, right? Here’s how everything should look by now:
You can create a new slide by typing ---.
Let’s add an image to the second slide. I’ve found one showing a neural network on Wikimedia Commons, but you’re free to use any other.
The following snippet adds heading, bullet point, and the image to the slide:
# Welcome to Slide 2- This is a neural network:
Here’s how it should look like:
Let’s keep things simple today, so we’ll stop here with the content. Next, I’ll show you how to customize the style of your presentation.
You can customize MARP presentations by adding stylesheets, but it will require basic CSS knowledge. You’ll want to go back to the start of the document and open up the CSS Style tag:
<style></style>
You can then customize the colors by editing the CSS variables. For example, here’s how to change the text and background color:
<style> :root { --color-background: #101010 !important; --color-foreground: #FFFFFF !important; }</style>
Your presentation will suddenly get a dark theme:
You can also change the fonts. For example, the snippet below sets all Heading 1 elements to a monospace font:
h1 { font-family: IBM Plex Mono;}
This one is a custom font, so go with Courier New if you don’t have it installed. You can style any other element to your liking — the only limiting factor is your CSS knowledge.
Finally, I want to show you how to export the presentation.
You can save your presentation as a PowerPoint document, PDF file, or HTML. The PNG and JPG options do exist, but they will only export the first slide.
Here’s how to get started with exporting:
I’ll save it both as a PDF and as a Powerpoint presentation document.
Let’s open the PDF now to verify the export was successful:
Everything looks good, so let’s check the PPTX next:
The PowerPoint document opens up, but there’s nothing you can do to the slides. You can’t modify text or images, so this could be a potential dealbreaker.
And that’s just enough for today. Let’s wrap things up next.
To summarize, Marp looks like a viable PowerPoint alternative to me, because writing and editing Markdown documents is easy, and it doesn’t overwhelm you with options. Don’t get me wrong, there’s nothing wrong with having options, but most of what I do with slideshows is relatively simple.
I almost never add animations and transitions to the presentation, and I always save it as a PDF document. PDFs are just easier to share and open, as you don’t need to launch a resource-heavy app. Besides, PowerPoint can sometimes be laggy, and that’s just another I don’t want to deal with.
If your needs all the capabilities Powerpoint has to offer, then MARP might be too basic for you.
What are your thoughts on Marp? Do you see it as a viable PowerPoint alternative, or is the functionality too basic for your needs? Let me know in the comment section below.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Sign up for my newsletter
Subscribe on YouTube
Connect on LinkedIn | [
{
"code": null,
"e": 409,
"s": 171,
"text": "Do you find PowerPoint annoying? Me too. It can be laggy at times and has an overwhelming number of options. If you’re in the market for something simpler, today’s your lucky day. Marp might be the right tool to save you time and nerves."
},
{
"code": null,
"e": 609,
"s": 409,
"text": "It’s a Visual Studio Code extension based on Markdown, and lets you create presentations that can be exported as PPTX, PDF, and HTML. Today you’ll learn the basics and create your first presentation."
},
{
"code": null,
"e": 658,
"s": 609,
"text": "Don’t feel like reading? Watch my video instead:"
},
{
"code": null,
"e": 893,
"s": 658,
"text": "You should already have Visual Studio Code installed. It’s a code editor that lets you write anything from readme files to machine learning models. You won’t write code today — if you don’t count Markdown as code, which you shouldn’t."
},
{
"code": null,
"e": 970,
"s": 893,
"text": "Once in Visual Studio Code, click on the Extensions tab and search for Marp:"
},
{
"code": null,
"e": 1114,
"s": 970,
"text": "Hit the Install button and you’ll be good to go after a couple of seconds. Then create a folder anywhere on your machine and open it in VSCode."
},
{
"code": null,
"e": 1232,
"s": 1114,
"text": "I’ve named mine marp_slideshow and created a slideshow.md file inside. Feel free to change the names per your liking."
},
{
"code": null,
"e": 1293,
"s": 1232,
"text": "And that’s it — you’re now ready to create your first slide."
},
{
"code": null,
"e": 1467,
"s": 1293,
"text": "Do you have the slideshow.md file open? Good. Proceed with the boilerplate. You’ll have to specify you’re using Marp, because the Markdown document can’t know it by default:"
},
{
"code": null,
"e": 1484,
"s": 1467,
"text": "---marp: true---"
},
{
"code": null,
"e": 1564,
"s": 1484,
"text": "Let’s also add an H1 tag below, just so there’s something to see on the screen:"
},
{
"code": null,
"e": 1580,
"s": 1564,
"text": "# Slide 1 Title"
},
{
"code": null,
"e": 1644,
"s": 1580,
"text": "You can now click on the Preview icon to see your presentation:"
},
{
"code": null,
"e": 1736,
"s": 1644,
"text": "So far, so good. Leave the Preview window open — it will update automatically as you write."
},
{
"code": null,
"e": 1780,
"s": 1736,
"text": "You can also change the presentation theme:"
},
{
"code": null,
"e": 1809,
"s": 1780,
"text": "---marp: true:theme: gaia---"
},
{
"code": null,
"e": 1901,
"s": 1809,
"text": "I’m not the biggest fan of the yellow color, so I’ll show you how to change it a bit later."
},
{
"code": null,
"e": 2017,
"s": 1901,
"text": "You can press CTRL + SPACE to list all available properties. Two of these are author and size, so let’s tweak them:"
},
{
"code": null,
"e": 2078,
"s": 2017,
"text": "---marp: true:theme: gaiaauthor: Dario Radečićsize: 4:3---"
},
{
"code": null,
"e": 2175,
"s": 2078,
"text": "You can see how we’ve moved from 16:9 to 4:3 aspect ratio, but it’s a personal preference thing."
},
{
"code": null,
"e": 2436,
"s": 2175,
"text": "Next, let’s see how you can use Markdown to add content to your slides. The snippet below adds two bullet points. The second one has child elements, and each one is styled differently. These are here to show you how to bold, italicize, and preformat your text:"
},
{
"code": null,
"e": 2573,
"s": 2436,
"text": "# Welcome to MARP- It's an awesome VSCode extension for making presentations.- It's based on Markdown: - **Bold** - _Italic_ - `code`"
},
{
"code": null,
"e": 2628,
"s": 2573,
"text": "Easy, right? Here’s how everything should look by now:"
},
{
"code": null,
"e": 2670,
"s": 2628,
"text": "You can create a new slide by typing ---."
},
{
"code": null,
"e": 2806,
"s": 2670,
"text": "Let’s add an image to the second slide. I’ve found one showing a neural network on Wikimedia Commons, but you’re free to use any other."
},
{
"code": null,
"e": 2884,
"s": 2806,
"text": "The following snippet adds heading, bullet point, and the image to the slide:"
},
{
"code": null,
"e": 3023,
"s": 2884,
"text": "# Welcome to Slide 2- This is a neural network:"
},
{
"code": null,
"e": 3055,
"s": 3023,
"text": "Here’s how it should look like:"
},
{
"code": null,
"e": 3193,
"s": 3055,
"text": "Let’s keep things simple today, so we’ll stop here with the content. Next, I’ll show you how to customize the style of your presentation."
},
{
"code": null,
"e": 3377,
"s": 3193,
"text": "You can customize MARP presentations by adding stylesheets, but it will require basic CSS knowledge. You’ll want to go back to the start of the document and open up the CSS Style tag:"
},
{
"code": null,
"e": 3393,
"s": 3377,
"text": "<style></style>"
},
{
"code": null,
"e": 3522,
"s": 3393,
"text": "You can then customize the colors by editing the CSS variables. For example, here’s how to change the text and background color:"
},
{
"code": null,
"e": 3641,
"s": 3522,
"text": "<style> :root { --color-background: #101010 !important;\t--color-foreground: #FFFFFF !important; }</style>"
},
{
"code": null,
"e": 3691,
"s": 3641,
"text": "Your presentation will suddenly get a dark theme:"
},
{
"code": null,
"e": 3802,
"s": 3691,
"text": "You can also change the fonts. For example, the snippet below sets all Heading 1 elements to a monospace font:"
},
{
"code": null,
"e": 3839,
"s": 3802,
"text": "h1 { font-family: IBM Plex Mono;}"
},
{
"code": null,
"e": 4018,
"s": 3839,
"text": "This one is a custom font, so go with Courier New if you don’t have it installed. You can style any other element to your liking — the only limiting factor is your CSS knowledge."
},
{
"code": null,
"e": 4078,
"s": 4018,
"text": "Finally, I want to show you how to export the presentation."
},
{
"code": null,
"e": 4231,
"s": 4078,
"text": "You can save your presentation as a PowerPoint document, PDF file, or HTML. The PNG and JPG options do exist, but they will only export the first slide."
},
{
"code": null,
"e": 4273,
"s": 4231,
"text": "Here’s how to get started with exporting:"
},
{
"code": null,
"e": 4343,
"s": 4273,
"text": "I’ll save it both as a PDF and as a Powerpoint presentation document."
},
{
"code": null,
"e": 4403,
"s": 4343,
"text": "Let’s open the PDF now to verify the export was successful:"
},
{
"code": null,
"e": 4456,
"s": 4403,
"text": "Everything looks good, so let’s check the PPTX next:"
},
{
"code": null,
"e": 4611,
"s": 4456,
"text": "The PowerPoint document opens up, but there’s nothing you can do to the slides. You can’t modify text or images, so this could be a potential dealbreaker."
},
{
"code": null,
"e": 4672,
"s": 4611,
"text": "And that’s just enough for today. Let’s wrap things up next."
},
{
"code": null,
"e": 4963,
"s": 4672,
"text": "To summarize, Marp looks like a viable PowerPoint alternative to me, because writing and editing Markdown documents is easy, and it doesn’t overwhelm you with options. Don’t get me wrong, there’s nothing wrong with having options, but most of what I do with slideshows is relatively simple."
},
{
"code": null,
"e": 5255,
"s": 4963,
"text": "I almost never add animations and transitions to the presentation, and I always save it as a PDF document. PDFs are just easier to share and open, as you don’t need to launch a resource-heavy app. Besides, PowerPoint can sometimes be laggy, and that’s just another I don’t want to deal with."
},
{
"code": null,
"e": 5353,
"s": 5255,
"text": "If your needs all the capabilities Powerpoint has to offer, then MARP might be too basic for you."
},
{
"code": null,
"e": 5527,
"s": 5353,
"text": "What are your thoughts on Marp? Do you see it as a viable PowerPoint alternative, or is the functionality too basic for your needs? Let me know in the comment section below."
},
{
"code": null,
"e": 5710,
"s": 5527,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 5721,
"s": 5710,
"text": "medium.com"
},
{
"code": null,
"e": 5747,
"s": 5721,
"text": "Sign up for my newsletter"
},
{
"code": null,
"e": 5768,
"s": 5747,
"text": "Subscribe on YouTube"
}
] |
Python 3 - File readline() Method | The method readline()reads one entire line from the file. A trailing newline character is kept in the string. If the size argument is present and non-negative, it is a maximum byte count including the trailing newline and an incomplete line may be returned.
An empty string is returned only when EOF is encountered immediately.
Following is the syntax for readline() method −
fileObject.readline( size );
size − This is the number of bytes to be read from the file.
This method returns the line read from the file.
The following example shows the usage of readline() method.
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
line = fo.readline(5)
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file: foo.txt
Read Line: This is 1st line
Read Line: This
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2598,
"s": 2340,
"text": "The method readline()reads one entire line from the file. A trailing newline character is kept in the string. If the size argument is present and non-negative, it is a maximum byte count including the trailing newline and an incomplete line may be returned."
},
{
"code": null,
"e": 2668,
"s": 2598,
"text": "An empty string is returned only when EOF is encountered immediately."
},
{
"code": null,
"e": 2716,
"s": 2668,
"text": "Following is the syntax for readline() method −"
},
{
"code": null,
"e": 2746,
"s": 2716,
"text": "fileObject.readline( size );\n"
},
{
"code": null,
"e": 2807,
"s": 2746,
"text": "size − This is the number of bytes to be read from the file."
},
{
"code": null,
"e": 2856,
"s": 2807,
"text": "This method returns the line read from the file."
},
{
"code": null,
"e": 2916,
"s": 2856,
"text": "The following example shows the usage of readline() method."
},
{
"code": null,
"e": 3056,
"s": 2916,
"text": "Assuming that 'foo.txt' file contains following text:\nThis is 1st line\nThis is 2nd line\nThis is 3rd line\nThis is 4th line\nThis is 5th line\n"
},
{
"code": null,
"e": 3298,
"s": 3056,
"text": "#!/usr/bin/python3\n\n# Open a file\nfo = open(\"foo.txt\", \"r+\")\nprint (\"Name of the file: \", fo.name)\n\nline = fo.readline()\nprint (\"Read Line: %s\" % (line))\n\nline = fo.readline(5)\nprint (\"Read Line: %s\" % (line))\n\n# Close opened file\nfo.close()"
},
{
"code": null,
"e": 3364,
"s": 3298,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 3437,
"s": 3364,
"text": "Name of the file: foo.txt\nRead Line: This is 1st line\n\nRead Line: This\n"
},
{
"code": null,
"e": 3474,
"s": 3437,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3490,
"s": 3474,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3523,
"s": 3490,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3542,
"s": 3523,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3577,
"s": 3542,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3599,
"s": 3577,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3633,
"s": 3599,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3661,
"s": 3633,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3696,
"s": 3661,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3710,
"s": 3696,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3743,
"s": 3710,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3760,
"s": 3743,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3767,
"s": 3760,
"text": " Print"
},
{
"code": null,
"e": 3778,
"s": 3767,
"text": " Add Notes"
}
] |
Line Generation Algorithm | A line connects two points. It is a basic element in graphics. To draw a line, you need two points between which you can draw a line. In the following three algorithms, we refer the one point of line as X0,Y0 and the second point of line as X1,Y1.
Digital Differential Analyzer DDA algorithm is the simple line generation algorithm which is explained step by step here.
Step 1 − Get the input of two end points (X0,Y0) and (X1,Y1).
Step 2 − Calculate the difference between two end points.
dx = X1 - X0
dy = Y1 - Y0
Step 3 − Based on the calculated difference in step-2, you need to identify the number of steps to put pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate.
if (absolute(dx) > absolute(dy))
Steps = absolute(dx);
else
Steps = absolute(dy);
Step 4 − Calculate the increment in x coordinate and y coordinate.
Xincrement = dx / (float) steps;
Yincrement = dy / (float) steps;
Step 5 − Put the pixel by successfully incrementing x and y coordinates accordingly and complete the drawing of the line.
for(int v=0; v < Steps; v++)
{
x = x + Xincrement;
y = y + Yincrement;
putpixel(Round(x), Round(y));
}
The Bresenham algorithm is another incremental scan conversion algorithm. The big advantage of this algorithm is that, it uses only integer calculations. Moving across the x axis in unit intervals and at each step choose between two different y coordinates.
For example, as shown in the following illustration, from position 2,3 you need to choose between 3,3 and 3,4. You would like the point that is closer to the original line.
At sample position Xk+1, the vertical separations from the mathematical line are labelled as dupper and dlower.
From the above illustration, the y coordinate on the mathematical line at xk+1 is −
Y = m$Xk$+1 + b
So, dupper and dlower are given as follows −
dlower=y−yk
=m(Xk+1)+b−Yk
and
dupper=(yk+1)−y
=Yk+1−m(Xk+1)−b
You can use these to make a simple decision about which pixel is closer to the mathematical line. This simple decision is based on the difference between the two pixel positions.
dlower−dupper=2m(xk+1)−2yk+2b−1
Let us substitute m with dy/dx where dx and dy are the differences between the end-points.
dx(dlower−dupper)=dx(2dydx(xk+1)−2yk+2b−1)
=2dy.xk−2dx.yk+2dy+2dx(2b−1)
=2dy.xk−2dx.yk+C
So, a decision parameter Pk for the kth step along a line is given by −
pk=dx(dlower−dupper)
=2dy.xk−2dx.yk+C
The sign of the decision parameter Pk is the same as that of dlower−dupper.
If pk is negative, then choose the lower pixel, otherwise choose the upper pixel.
Remember, the coordinate changes occur along the x axis in unit steps, so you can do everything with integer calculations. At step k+1, the decision parameter is given as −
pk+1=2dy.xk+1−2dx.yk+1+C
Subtracting pk from this we get −
pk+1−pk=2dy(xk+1−xk)−2dx(yk+1−yk)
But, xk+1 is the same as (xk)+1. So −
pk+1=pk+2dy−2dx(yk+1−yk)
Where, Yk+1–Yk is either 0 or 1 depending on the sign of Pk.
The first decision parameter p0 is evaluated at (x0,y0) is given as −
p0=2dy−dx
Now, keeping in mind all the above points and calculations, here is the Bresenham algorithm for slope m < 1 −
Step 1 − Input the two end-points of line, storing the left end-point in (x0,y0).
Step 2 − Plot the point (x0,y0).
Step 3 − Calculate the constants dx, dy, 2dy, and 2dy–2dx and get the first value for the decision parameter as −
p0=2dy−dx
Step 4 − At each Xk along the line, starting at k = 0, perform the following test −
If pk < 0, the next point to plot is (xk+1,yk) and
pk+1=pk+2dy Otherwise,
(xk,yk+1)
pk+1=pk+2dy−2dx
Step 5 − Repeat step 4 dx–1 times.
For m > 1, find out whether you need to increment x while incrementing y each time.
After solving, the equation for decision parameter Pk will be very similar, just the x and y in the equation gets interchanged.
Mid-point algorithm is due to Bresenham which was modified by Pitteway and Van Aken. Assume that you have already put the point P at x,y coordinate and the slope of the line is 0 ≤ k ≤ 1 as shown in the following illustration.
Now you need to decide whether to put the next point at E or N. This can be chosen by identifying the intersection point Q closest to the point N or E. If the intersection point Q is closest to the point N then N is considered as the next point; otherwise E.
To determine that, first calculate the mid-point M1⁄2x+1,y+1⁄2. If the intersection point Q of the line with the vertical line connecting E and N is below M, then take E as the next point; otherwise take N as the next point.
In order to check this, we need to consider the implicit equation −
Fx,y = mx + b - y
For positive m at any given X,
If y is on the line, then Fx,y = 0
If y is above the line, then Fx,y < 0
If y is below the line, then Fx,y > 0
107 Lectures
13.5 hours
Arnab Chakraborty
106 Lectures
8 hours
Arnab Chakraborty
99 Lectures
6 hours
Arnab Chakraborty
46 Lectures
2.5 hours
Shweta
70 Lectures
9 hours
Abhilash Nelson
52 Lectures
7 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2167,
"s": 1919,
"text": "A line connects two points. It is a basic element in graphics. To draw a line, you need two points between which you can draw a line. In the following three algorithms, we refer the one point of line as X0,Y0 and the second point of line as X1,Y1."
},
{
"code": null,
"e": 2289,
"s": 2167,
"text": "Digital Differential Analyzer DDA algorithm is the simple line generation algorithm which is explained step by step here."
},
{
"code": null,
"e": 2351,
"s": 2289,
"text": "Step 1 − Get the input of two end points (X0,Y0) and (X1,Y1)."
},
{
"code": null,
"e": 2409,
"s": 2351,
"text": "Step 2 − Calculate the difference between two end points."
},
{
"code": null,
"e": 2436,
"s": 2409,
"text": "dx = X1 - X0\ndy = Y1 - Y0\n"
},
{
"code": null,
"e": 2627,
"s": 2436,
"text": "Step 3 − Based on the calculated difference in step-2, you need to identify the number of steps to put pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate."
},
{
"code": null,
"e": 2715,
"s": 2627,
"text": "if (absolute(dx) > absolute(dy))\n Steps = absolute(dx);\nelse\n Steps = absolute(dy);"
},
{
"code": null,
"e": 2782,
"s": 2715,
"text": "Step 4 − Calculate the increment in x coordinate and y coordinate."
},
{
"code": null,
"e": 2849,
"s": 2782,
"text": "Xincrement = dx / (float) steps;\nYincrement = dy / (float) steps;\n"
},
{
"code": null,
"e": 2971,
"s": 2849,
"text": "Step 5 − Put the pixel by successfully incrementing x and y coordinates accordingly and complete the drawing of the line."
},
{
"code": null,
"e": 3083,
"s": 2971,
"text": "for(int v=0; v < Steps; v++)\n{\n x = x + Xincrement;\n y = y + Yincrement;\n putpixel(Round(x), Round(y));\n}"
},
{
"code": null,
"e": 3341,
"s": 3083,
"text": "The Bresenham algorithm is another incremental scan conversion algorithm. The big advantage of this algorithm is that, it uses only integer calculations. Moving across the x axis in unit intervals and at each step choose between two different y coordinates."
},
{
"code": null,
"e": 3514,
"s": 3341,
"text": "For example, as shown in the following illustration, from position 2,3 you need to choose between 3,3 and 3,4. You would like the point that is closer to the original line."
},
{
"code": null,
"e": 3626,
"s": 3514,
"text": "At sample position Xk+1, the vertical separations from the mathematical line are labelled as dupper and dlower."
},
{
"code": null,
"e": 3710,
"s": 3626,
"text": "From the above illustration, the y coordinate on the mathematical line at xk+1 is −"
},
{
"code": null,
"e": 3726,
"s": 3710,
"text": "Y = m$Xk$+1 + b"
},
{
"code": null,
"e": 3771,
"s": 3726,
"text": "So, dupper and dlower are given as follows −"
},
{
"code": null,
"e": 3783,
"s": 3771,
"text": "dlower=y−yk"
},
{
"code": null,
"e": 3797,
"s": 3783,
"text": "=m(Xk+1)+b−Yk"
},
{
"code": null,
"e": 3801,
"s": 3797,
"text": "and"
},
{
"code": null,
"e": 3817,
"s": 3801,
"text": "dupper=(yk+1)−y"
},
{
"code": null,
"e": 3833,
"s": 3817,
"text": "=Yk+1−m(Xk+1)−b"
},
{
"code": null,
"e": 4012,
"s": 3833,
"text": "You can use these to make a simple decision about which pixel is closer to the mathematical line. This simple decision is based on the difference between the two pixel positions."
},
{
"code": null,
"e": 4044,
"s": 4012,
"text": "dlower−dupper=2m(xk+1)−2yk+2b−1"
},
{
"code": null,
"e": 4135,
"s": 4044,
"text": "Let us substitute m with dy/dx where dx and dy are the differences between the end-points."
},
{
"code": null,
"e": 4178,
"s": 4135,
"text": "dx(dlower−dupper)=dx(2dydx(xk+1)−2yk+2b−1)"
},
{
"code": null,
"e": 4207,
"s": 4178,
"text": "=2dy.xk−2dx.yk+2dy+2dx(2b−1)"
},
{
"code": null,
"e": 4224,
"s": 4207,
"text": "=2dy.xk−2dx.yk+C"
},
{
"code": null,
"e": 4296,
"s": 4224,
"text": "So, a decision parameter Pk for the kth step along a line is given by −"
},
{
"code": null,
"e": 4317,
"s": 4296,
"text": "pk=dx(dlower−dupper)"
},
{
"code": null,
"e": 4334,
"s": 4317,
"text": "=2dy.xk−2dx.yk+C"
},
{
"code": null,
"e": 4410,
"s": 4334,
"text": "The sign of the decision parameter Pk is the same as that of dlower−dupper."
},
{
"code": null,
"e": 4492,
"s": 4410,
"text": "If pk is negative, then choose the lower pixel, otherwise choose the upper pixel."
},
{
"code": null,
"e": 4665,
"s": 4492,
"text": "Remember, the coordinate changes occur along the x axis in unit steps, so you can do everything with integer calculations. At step k+1, the decision parameter is given as −"
},
{
"code": null,
"e": 4690,
"s": 4665,
"text": "pk+1=2dy.xk+1−2dx.yk+1+C"
},
{
"code": null,
"e": 4724,
"s": 4690,
"text": "Subtracting pk from this we get −"
},
{
"code": null,
"e": 4758,
"s": 4724,
"text": "pk+1−pk=2dy(xk+1−xk)−2dx(yk+1−yk)"
},
{
"code": null,
"e": 4796,
"s": 4758,
"text": "But, xk+1 is the same as (xk)+1. So −"
},
{
"code": null,
"e": 4821,
"s": 4796,
"text": "pk+1=pk+2dy−2dx(yk+1−yk)"
},
{
"code": null,
"e": 4882,
"s": 4821,
"text": "Where, Yk+1–Yk is either 0 or 1 depending on the sign of Pk."
},
{
"code": null,
"e": 4952,
"s": 4882,
"text": "The first decision parameter p0 is evaluated at (x0,y0) is given as −"
},
{
"code": null,
"e": 4962,
"s": 4952,
"text": "p0=2dy−dx"
},
{
"code": null,
"e": 5072,
"s": 4962,
"text": "Now, keeping in mind all the above points and calculations, here is the Bresenham algorithm for slope m < 1 −"
},
{
"code": null,
"e": 5154,
"s": 5072,
"text": "Step 1 − Input the two end-points of line, storing the left end-point in (x0,y0)."
},
{
"code": null,
"e": 5187,
"s": 5154,
"text": "Step 2 − Plot the point (x0,y0)."
},
{
"code": null,
"e": 5301,
"s": 5187,
"text": "Step 3 − Calculate the constants dx, dy, 2dy, and 2dy–2dx and get the first value for the decision parameter as −"
},
{
"code": null,
"e": 5311,
"s": 5301,
"text": "p0=2dy−dx"
},
{
"code": null,
"e": 5395,
"s": 5311,
"text": "Step 4 − At each Xk along the line, starting at k = 0, perform the following test −"
},
{
"code": null,
"e": 5446,
"s": 5395,
"text": "If pk < 0, the next point to plot is (xk+1,yk) and"
},
{
"code": null,
"e": 5469,
"s": 5446,
"text": "pk+1=pk+2dy Otherwise,"
},
{
"code": null,
"e": 5479,
"s": 5469,
"text": "(xk,yk+1)"
},
{
"code": null,
"e": 5495,
"s": 5479,
"text": "pk+1=pk+2dy−2dx"
},
{
"code": null,
"e": 5530,
"s": 5495,
"text": "Step 5 − Repeat step 4 dx–1 times."
},
{
"code": null,
"e": 5614,
"s": 5530,
"text": "For m > 1, find out whether you need to increment x while incrementing y each time."
},
{
"code": null,
"e": 5742,
"s": 5614,
"text": "After solving, the equation for decision parameter Pk will be very similar, just the x and y in the equation gets interchanged."
},
{
"code": null,
"e": 5969,
"s": 5742,
"text": "Mid-point algorithm is due to Bresenham which was modified by Pitteway and Van Aken. Assume that you have already put the point P at x,y coordinate and the slope of the line is 0 ≤ k ≤ 1 as shown in the following illustration."
},
{
"code": null,
"e": 6228,
"s": 5969,
"text": "Now you need to decide whether to put the next point at E or N. This can be chosen by identifying the intersection point Q closest to the point N or E. If the intersection point Q is closest to the point N then N is considered as the next point; otherwise E."
},
{
"code": null,
"e": 6453,
"s": 6228,
"text": "To determine that, first calculate the mid-point M1⁄2x+1,y+1⁄2. If the intersection point Q of the line with the vertical line connecting E and N is below M, then take E as the next point; otherwise take N as the next point."
},
{
"code": null,
"e": 6521,
"s": 6453,
"text": "In order to check this, we need to consider the implicit equation −"
},
{
"code": null,
"e": 6539,
"s": 6521,
"text": "Fx,y = mx + b - y"
},
{
"code": null,
"e": 6570,
"s": 6539,
"text": "For positive m at any given X,"
},
{
"code": null,
"e": 6605,
"s": 6570,
"text": "If y is on the line, then Fx,y = 0"
},
{
"code": null,
"e": 6643,
"s": 6605,
"text": "If y is above the line, then Fx,y < 0"
},
{
"code": null,
"e": 6681,
"s": 6643,
"text": "If y is below the line, then Fx,y > 0"
},
{
"code": null,
"e": 6718,
"s": 6681,
"text": "\n 107 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 6737,
"s": 6718,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6771,
"s": 6737,
"text": "\n 106 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6790,
"s": 6771,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6823,
"s": 6790,
"text": "\n 99 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6842,
"s": 6823,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6877,
"s": 6842,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6885,
"s": 6877,
"text": " Shweta"
},
{
"code": null,
"e": 6918,
"s": 6885,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6935,
"s": 6918,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6968,
"s": 6935,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6990,
"s": 6968,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 6997,
"s": 6990,
"text": " Print"
},
{
"code": null,
"e": 7008,
"s": 6997,
"text": " Add Notes"
}
] |
Logging in Node.js | 01 Apr, 2021
Node.js is a JavaScript runtime that’s built on Chrome’s V8 JavaScript engine and its run-time environment includes everything which we’d like to execute a program written in JavaScript. Logging is an essential part of understanding the complete application life cycle of the Node.js program. From starting to debugging and adding new features, logs provide support by analyzing the data, and we can resolve bugs much easier and quicker by detecting errors as soon as they occur. There are common levels of logging in Node.js: error, warn, info, debug. Logging involves recording information about the application’s runtime behavior in a more persistent manner.
There are following ways to log in Node.js:
console.log: The original method of logging is console.log which is a function that writes a message to log on the debugging console, but you have little control over it where things log from outside the code.
Syntax:
console.log(level, message)
Debug module: The advantage of using debug is that a lot of packages use it. You can turn it on to urge additional information on what’s happening in web middleware like Express and Koa when your back-end gets an internet request. The good frameworks will offer you how to attach logging middleware, but you would possibly not get all the small print sent there too.
Middleware Middleware is simply something you’ll put into the request pipeline. Ways to setup logging middleware:
Application:JavascriptJavascriptconst app = express()const loggingMiddleware = require('my-logging-middleware')app.use(loggingMiddleware)
Javascript
const app = express()const loggingMiddleware = require('my-logging-middleware')app.use(loggingMiddleware)
Router:JavascriptJavascriptconst router = express.Router()const routeLoggingMiddleware = require('my-route-logging-middleware')router.use(routeLoggingMiddleware)
Javascript
const router = express.Router()const routeLoggingMiddleware = require('my-route-logging-middleware')router.use(routeLoggingMiddleware)
Winston Package: Winston includes storage options,different log levels & queries and a profiler.
Javascript
const app = express()const winston = require('winston')const consoleTransport = new winston.transports.Console()const myWinstonOptions = { transports: [consoleTransport]}const logger = new winston.createLogger(myWinstonOptions) function logRequest(req, res, next) { logger.info(req.url) next()}app.use(logRequest) function logError(err, req, res, next) { logger.error(err) next()}app.use(logError)
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Express.js req.params Property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 690,
"s": 28,
"text": "Node.js is a JavaScript runtime that’s built on Chrome’s V8 JavaScript engine and its run-time environment includes everything which we’d like to execute a program written in JavaScript. Logging is an essential part of understanding the complete application life cycle of the Node.js program. From starting to debugging and adding new features, logs provide support by analyzing the data, and we can resolve bugs much easier and quicker by detecting errors as soon as they occur. There are common levels of logging in Node.js: error, warn, info, debug. Logging involves recording information about the application’s runtime behavior in a more persistent manner."
},
{
"code": null,
"e": 734,
"s": 690,
"text": "There are following ways to log in Node.js:"
},
{
"code": null,
"e": 944,
"s": 734,
"text": "console.log: The original method of logging is console.log which is a function that writes a message to log on the debugging console, but you have little control over it where things log from outside the code."
},
{
"code": null,
"e": 952,
"s": 944,
"text": "Syntax:"
},
{
"code": null,
"e": 980,
"s": 952,
"text": "console.log(level, message)"
},
{
"code": null,
"e": 1347,
"s": 980,
"text": "Debug module: The advantage of using debug is that a lot of packages use it. You can turn it on to urge additional information on what’s happening in web middleware like Express and Koa when your back-end gets an internet request. The good frameworks will offer you how to attach logging middleware, but you would possibly not get all the small print sent there too."
},
{
"code": null,
"e": 1461,
"s": 1347,
"text": "Middleware Middleware is simply something you’ll put into the request pipeline. Ways to setup logging middleware:"
},
{
"code": null,
"e": 1599,
"s": 1461,
"text": "Application:JavascriptJavascriptconst app = express()const loggingMiddleware = require('my-logging-middleware')app.use(loggingMiddleware)"
},
{
"code": null,
"e": 1610,
"s": 1599,
"text": "Javascript"
},
{
"code": "const app = express()const loggingMiddleware = require('my-logging-middleware')app.use(loggingMiddleware)",
"e": 1716,
"s": 1610,
"text": null
},
{
"code": null,
"e": 1878,
"s": 1716,
"text": "Router:JavascriptJavascriptconst router = express.Router()const routeLoggingMiddleware = require('my-route-logging-middleware')router.use(routeLoggingMiddleware)"
},
{
"code": null,
"e": 1889,
"s": 1878,
"text": "Javascript"
},
{
"code": "const router = express.Router()const routeLoggingMiddleware = require('my-route-logging-middleware')router.use(routeLoggingMiddleware)",
"e": 2024,
"s": 1889,
"text": null
},
{
"code": null,
"e": 2122,
"s": 2024,
"text": "Winston Package: Winston includes storage options,different log levels & queries and a profiler. "
},
{
"code": null,
"e": 2133,
"s": 2122,
"text": "Javascript"
},
{
"code": "const app = express()const winston = require('winston')const consoleTransport = new winston.transports.Console()const myWinstonOptions = { transports: [consoleTransport]}const logger = new winston.createLogger(myWinstonOptions) function logRequest(req, res, next) { logger.info(req.url) next()}app.use(logRequest) function logError(err, req, res, next) { logger.error(err) next()}app.use(logError)",
"e": 2548,
"s": 2133,
"text": null
},
{
"code": null,
"e": 2563,
"s": 2548,
"text": "Node.js-Basics"
},
{
"code": null,
"e": 2570,
"s": 2563,
"text": "Picked"
},
{
"code": null,
"e": 2578,
"s": 2570,
"text": "Node.js"
},
{
"code": null,
"e": 2595,
"s": 2578,
"text": "Web Technologies"
},
{
"code": null,
"e": 2693,
"s": 2595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2725,
"s": 2693,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 2760,
"s": 2725,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2830,
"s": 2760,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 2857,
"s": 2830,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 2888,
"s": 2857,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 2950,
"s": 2888,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2992,
"s": 2950,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3053,
"s": 2992,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3096,
"s": 3053,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python program to capitalize the first and last character of each word in a string | 01 Jun, 2022
Given the string, the task is to capitalise the first and last character of each word in a string. Examples:
Input: hello world
Output: HellO WorlD
Input: welcome to geeksforgeeks
Output: WelcomE TO GeeksforgeekS
Approach:
Access the last element using indexing.
Capitalize the first word using title() method.
Then join the each word using join() method.
Perform all the operations inside lambda for writing the code in one-line.
Below is the implementation.
Python3
# Python program to capitalize# first and last character of# each word of a String # Function to do the samedef word_both_cap(str): #lambda function for capitalizing the # first and last letter of words in # the string return ' '.join(map(lambda s: s[:-1]+s[-1].upper(), s.title().split())) # Driver's codes = "welcome to geeksforgeeks"print("String before:", s)print("String after:", word_both_cap(str))
Output:
String before: welcome to geeksforgeeks
String after: WelcomE TO GeeksforgeekS
sweetyty
Python string-programs
python-string
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 163,
"s": 54,
"text": "Given the string, the task is to capitalise the first and last character of each word in a string. Examples:"
},
{
"code": null,
"e": 269,
"s": 163,
"text": "Input: hello world \nOutput: HellO WorlD\n\nInput: welcome to geeksforgeeks\nOutput: WelcomE TO GeeksforgeekS"
},
{
"code": null,
"e": 279,
"s": 269,
"text": "Approach:"
},
{
"code": null,
"e": 319,
"s": 279,
"text": "Access the last element using indexing."
},
{
"code": null,
"e": 367,
"s": 319,
"text": "Capitalize the first word using title() method."
},
{
"code": null,
"e": 412,
"s": 367,
"text": "Then join the each word using join() method."
},
{
"code": null,
"e": 487,
"s": 412,
"text": "Perform all the operations inside lambda for writing the code in one-line."
},
{
"code": null,
"e": 517,
"s": 487,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 525,
"s": 517,
"text": "Python3"
},
{
"code": "# Python program to capitalize# first and last character of# each word of a String # Function to do the samedef word_both_cap(str): #lambda function for capitalizing the # first and last letter of words in # the string return ' '.join(map(lambda s: s[:-1]+s[-1].upper(), s.title().split())) # Driver's codes = \"welcome to geeksforgeeks\"print(\"String before:\", s)print(\"String after:\", word_both_cap(str))",
"e": 980,
"s": 525,
"text": null
},
{
"code": null,
"e": 988,
"s": 980,
"text": "Output:"
},
{
"code": null,
"e": 1067,
"s": 988,
"text": "String before: welcome to geeksforgeeks\nString after: WelcomE TO GeeksforgeekS"
},
{
"code": null,
"e": 1076,
"s": 1067,
"text": "sweetyty"
},
{
"code": null,
"e": 1099,
"s": 1076,
"text": "Python string-programs"
},
{
"code": null,
"e": 1113,
"s": 1099,
"text": "python-string"
},
{
"code": null,
"e": 1137,
"s": 1113,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 1144,
"s": 1137,
"text": "Python"
},
{
"code": null,
"e": 1163,
"s": 1144,
"text": "Technical Scripter"
}
] |
Introduction of Embedded Systems | Set-1 | 09 Jun, 2022
Before going to the overview of Embedded System, Let’s first know the two basic things i.e embedded and system, and what actually do they mean.
What is a System?
In simple, a system is a set of interrelated parts/components which are designed/developed to perform a common tasks or to do some specific work for which it has been created.
What does Embedded mean?
Embedded means including something with anything for a reason. Or in simple we can say something which is integrated or attached to another thing. Now after getting what actually system and embedded mean we can easily understand what is Embedded Systems.
What are Embedded Systems?
An Embedded System is an integrated system which is formed as an combination of computer hardware and software for a specific function. It can be said as a dedicated computer system which has been developed for some particular reason. But it is not our traditional computer system or general-purpose computers, these are the Embedded systems which may work independently or attached to a larger system to work on few specific functions. These embedded systems can work without human intervention or with little human intervention.
Three main components of Embedded systems are:
1. Hardware
2. Software
3. Firmware
Digital watches
Washing Machine
Toys
Televisions
Digital phones
Laser Printer
Cameras
Industrial machines
Electronic Calculators
Automobiles
Medical Equipment
Mostly Embedded systems are present everywhere. We use it in our everyday life unknowingly as in most of the cases it is integrated insides the larger systems. So, here are some of the application areas of Embedded systems:
Home appliances
Transportation
Health care
Business sector & offices
Defense sector
Aerospace
Agricultural Sector
Performs specific task: Embedded systems performs some specific function or tasks.Low Cost: The price of an embedded system is not so expensive.Time Specific: It performs the tasks with in a certain time frame.Low Power: Embedded Systems don’t require much power to operate.High Efficiency: The efficiency level of embedded systems are so high.Minimal User interface: These systems require less user interface and easy to use.Less Human intervention: Embedded systems require no human intervention or very less human intervention.Highly Stable: Embedded systems not change frequently mostly fixed maintaining stability.High Reliability: Embedded systems are reliable they perform the tasks consistently well.Use microprocessors or micro controllers: Embedded systems use microprocessors or micro controllers to design and use limited memory.
Performs specific task: Embedded systems performs some specific function or tasks.
Low Cost: The price of an embedded system is not so expensive.
Time Specific: It performs the tasks with in a certain time frame.
Low Power: Embedded Systems don’t require much power to operate.
High Efficiency: The efficiency level of embedded systems are so high.
Minimal User interface: These systems require less user interface and easy to use.
Less Human intervention: Embedded systems require no human intervention or very less human intervention.
Highly Stable: Embedded systems not change frequently mostly fixed maintaining stability.
High Reliability: Embedded systems are reliable they perform the tasks consistently well.
Use microprocessors or micro controllers: Embedded systems use microprocessors or micro controllers to design and use limited memory.
Small size.
Enhanced real-time performance.
Easily customizable for a specific application.
High development cost.
Time-consuming design process.
As it application-specific less market available.
Top Embedded Programming Languages: Embedded systems can be programmed using different programming languages like Embedded C, Embedded C++, Embedded Java, Embedded Python. However it entirely depends on the developer to use which programming language for the development of the embedded systems.
akshaybotre203
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 197,
"s": 52,
"text": "Before going to the overview of Embedded System, Let’s first know the two basic things i.e embedded and system, and what actually do they mean. "
},
{
"code": null,
"e": 216,
"s": 197,
"text": "What is a System? "
},
{
"code": null,
"e": 393,
"s": 216,
"text": "In simple, a system is a set of interrelated parts/components which are designed/developed to perform a common tasks or to do some specific work for which it has been created. "
},
{
"code": null,
"e": 419,
"s": 393,
"text": "What does Embedded mean? "
},
{
"code": null,
"e": 675,
"s": 419,
"text": "Embedded means including something with anything for a reason. Or in simple we can say something which is integrated or attached to another thing. Now after getting what actually system and embedded mean we can easily understand what is Embedded Systems. "
},
{
"code": null,
"e": 703,
"s": 675,
"text": "What are Embedded Systems? "
},
{
"code": null,
"e": 1235,
"s": 703,
"text": "An Embedded System is an integrated system which is formed as an combination of computer hardware and software for a specific function. It can be said as a dedicated computer system which has been developed for some particular reason. But it is not our traditional computer system or general-purpose computers, these are the Embedded systems which may work independently or attached to a larger system to work on few specific functions. These embedded systems can work without human intervention or with little human intervention. "
},
{
"code": null,
"e": 1282,
"s": 1235,
"text": "Three main components of Embedded systems are:"
},
{
"code": null,
"e": 1319,
"s": 1282,
"text": "1. Hardware\n2. Software\n3. Firmware "
},
{
"code": null,
"e": 1335,
"s": 1319,
"text": "Digital watches"
},
{
"code": null,
"e": 1351,
"s": 1335,
"text": "Washing Machine"
},
{
"code": null,
"e": 1356,
"s": 1351,
"text": "Toys"
},
{
"code": null,
"e": 1368,
"s": 1356,
"text": "Televisions"
},
{
"code": null,
"e": 1383,
"s": 1368,
"text": "Digital phones"
},
{
"code": null,
"e": 1397,
"s": 1383,
"text": "Laser Printer"
},
{
"code": null,
"e": 1405,
"s": 1397,
"text": "Cameras"
},
{
"code": null,
"e": 1425,
"s": 1405,
"text": "Industrial machines"
},
{
"code": null,
"e": 1448,
"s": 1425,
"text": "Electronic Calculators"
},
{
"code": null,
"e": 1460,
"s": 1448,
"text": "Automobiles"
},
{
"code": null,
"e": 1478,
"s": 1460,
"text": "Medical Equipment"
},
{
"code": null,
"e": 1702,
"s": 1478,
"text": "Mostly Embedded systems are present everywhere. We use it in our everyday life unknowingly as in most of the cases it is integrated insides the larger systems. So, here are some of the application areas of Embedded systems:"
},
{
"code": null,
"e": 1718,
"s": 1702,
"text": "Home appliances"
},
{
"code": null,
"e": 1733,
"s": 1718,
"text": "Transportation"
},
{
"code": null,
"e": 1745,
"s": 1733,
"text": "Health care"
},
{
"code": null,
"e": 1771,
"s": 1745,
"text": "Business sector & offices"
},
{
"code": null,
"e": 1786,
"s": 1771,
"text": "Defense sector"
},
{
"code": null,
"e": 1796,
"s": 1786,
"text": "Aerospace"
},
{
"code": null,
"e": 1816,
"s": 1796,
"text": "Agricultural Sector"
},
{
"code": null,
"e": 2658,
"s": 1816,
"text": "Performs specific task: Embedded systems performs some specific function or tasks.Low Cost: The price of an embedded system is not so expensive.Time Specific: It performs the tasks with in a certain time frame.Low Power: Embedded Systems don’t require much power to operate.High Efficiency: The efficiency level of embedded systems are so high.Minimal User interface: These systems require less user interface and easy to use.Less Human intervention: Embedded systems require no human intervention or very less human intervention.Highly Stable: Embedded systems not change frequently mostly fixed maintaining stability.High Reliability: Embedded systems are reliable they perform the tasks consistently well.Use microprocessors or micro controllers: Embedded systems use microprocessors or micro controllers to design and use limited memory."
},
{
"code": null,
"e": 2741,
"s": 2658,
"text": "Performs specific task: Embedded systems performs some specific function or tasks."
},
{
"code": null,
"e": 2804,
"s": 2741,
"text": "Low Cost: The price of an embedded system is not so expensive."
},
{
"code": null,
"e": 2871,
"s": 2804,
"text": "Time Specific: It performs the tasks with in a certain time frame."
},
{
"code": null,
"e": 2936,
"s": 2871,
"text": "Low Power: Embedded Systems don’t require much power to operate."
},
{
"code": null,
"e": 3007,
"s": 2936,
"text": "High Efficiency: The efficiency level of embedded systems are so high."
},
{
"code": null,
"e": 3090,
"s": 3007,
"text": "Minimal User interface: These systems require less user interface and easy to use."
},
{
"code": null,
"e": 3195,
"s": 3090,
"text": "Less Human intervention: Embedded systems require no human intervention or very less human intervention."
},
{
"code": null,
"e": 3285,
"s": 3195,
"text": "Highly Stable: Embedded systems not change frequently mostly fixed maintaining stability."
},
{
"code": null,
"e": 3375,
"s": 3285,
"text": "High Reliability: Embedded systems are reliable they perform the tasks consistently well."
},
{
"code": null,
"e": 3509,
"s": 3375,
"text": "Use microprocessors or micro controllers: Embedded systems use microprocessors or micro controllers to design and use limited memory."
},
{
"code": null,
"e": 3521,
"s": 3509,
"text": "Small size."
},
{
"code": null,
"e": 3553,
"s": 3521,
"text": "Enhanced real-time performance."
},
{
"code": null,
"e": 3601,
"s": 3553,
"text": "Easily customizable for a specific application."
},
{
"code": null,
"e": 3624,
"s": 3601,
"text": "High development cost."
},
{
"code": null,
"e": 3655,
"s": 3624,
"text": "Time-consuming design process."
},
{
"code": null,
"e": 3706,
"s": 3655,
"text": "As it application-specific less market available. "
},
{
"code": null,
"e": 4002,
"s": 3706,
"text": "Top Embedded Programming Languages: Embedded systems can be programmed using different programming languages like Embedded C, Embedded C++, Embedded Java, Embedded Python. However it entirely depends on the developer to use which programming language for the development of the embedded systems."
},
{
"code": null,
"e": 4017,
"s": 4002,
"text": "akshaybotre203"
},
{
"code": null,
"e": 4054,
"s": 4017,
"text": "Computer Organization & Architecture"
}
] |
How to draw a circle with gradient border using CSS ? | 13 May, 2020
CSS is used to create various shapes and styles with different colors or gradient. In this article, we will learn how to draw a circle with a gradient border.
Approach: We are going to create two div one is outer div with class outer_circle and another is inner div with class inner_circle. Outer div contains the big circle with gradient colour and inner div contains a small white circle which acts as an inner end of the circle creating a border of the circle. The linear-gradient is a CSS function which we are going to use to set a linear gradient as the background image.
Syntax:
.class_name { background-image: linear-gradient(direction, color1, color2 }
Parameters: This function accept three parameters as mentioned above and described below:
$direction: It specifies the direction to move the gradient.
$color1: It specifies the first colour stop.
$color2: It specifies the second colour stop.
Program: We can use the linear-gradient function to draw a circle with gradient border as given below:
<!DOCTYPE html><html> <head> <!-- CSS --> <style> .outer_circle { position: relative; margin: 50px; width: 100px; height: 100px; border-radius: 50%; background: #ffffff; } .inner_circle { background-image: linear-gradient( to bottom, rgb(9, 112, 26) 0%, rgb(21, 255, 0) 100%); content: ''; position: absolute; top: -20px; bottom: -20px; right: -20px; left: -20px; z-index: -1; border-radius: inherit; } </style></head> <body> <div class="outer_circle"> <div class="inner_circle"></div> </div></body> </html>
Output:
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 May, 2020"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "CSS is used to create various shapes and styles with different colors or gradient. In this article, we will learn how to draw a circle with a gradient border."
},
{
"code": null,
"e": 606,
"s": 187,
"text": "Approach: We are going to create two div one is outer div with class outer_circle and another is inner div with class inner_circle. Outer div contains the big circle with gradient colour and inner div contains a small white circle which acts as an inner end of the circle creating a border of the circle. The linear-gradient is a CSS function which we are going to use to set a linear gradient as the background image."
},
{
"code": null,
"e": 614,
"s": 606,
"text": "Syntax:"
},
{
"code": null,
"e": 692,
"s": 614,
"text": " .class_name { background-image: linear-gradient(direction, color1, color2 } "
},
{
"code": null,
"e": 782,
"s": 692,
"text": "Parameters: This function accept three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 843,
"s": 782,
"text": "$direction: It specifies the direction to move the gradient."
},
{
"code": null,
"e": 888,
"s": 843,
"text": "$color1: It specifies the first colour stop."
},
{
"code": null,
"e": 934,
"s": 888,
"text": "$color2: It specifies the second colour stop."
},
{
"code": null,
"e": 1037,
"s": 934,
"text": "Program: We can use the linear-gradient function to draw a circle with gradient border as given below:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- CSS --> <style> .outer_circle { position: relative; margin: 50px; width: 100px; height: 100px; border-radius: 50%; background: #ffffff; } .inner_circle { background-image: linear-gradient( to bottom, rgb(9, 112, 26) 0%, rgb(21, 255, 0) 100%); content: ''; position: absolute; top: -20px; bottom: -20px; right: -20px; left: -20px; z-index: -1; border-radius: inherit; } </style></head> <body> <div class=\"outer_circle\"> <div class=\"inner_circle\"></div> </div></body> </html>",
"e": 1813,
"s": 1037,
"text": null
},
{
"code": null,
"e": 1821,
"s": 1813,
"text": "Output:"
},
{
"code": null,
"e": 1830,
"s": 1821,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1840,
"s": 1830,
"text": "HTML-Misc"
},
{
"code": null,
"e": 1844,
"s": 1840,
"text": "CSS"
},
{
"code": null,
"e": 1849,
"s": 1844,
"text": "HTML"
},
{
"code": null,
"e": 1866,
"s": 1849,
"text": "Web Technologies"
},
{
"code": null,
"e": 1893,
"s": 1866,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1898,
"s": 1893,
"text": "HTML"
}
] |
Scala | Try-Catch Exceptions | 12 Apr, 2019
The Try-Catch construct is different in Scala than in Java, Try-Catch in Scala is an expression. the Scala make use of pattern matching in the catch clause. Suppose, we have to implement a series of code which can throw an exception and if we want to control that exception then we should utilize the Try-Catch segment as it permits us to try-catch each and every type of exception in only one block, we need to write a series of case statements in catch as Scala uses matching in order to analyze and handle the exceptions.
Example :// Scala program of try-catch// exception // Creating objectobject Arithmetic{ // Main methoddef main(args: Array[String]) { // Try clause try { // Dividing a number val result = 11/0 } // Catch clause catch { // Case statement case x: ArithmeticException => { // Display this if exception is found println("Exception: A number is not divisible by zero.") } }}}Output:Exception: A number is not divisible by zero.
Here, an exception is thrown as a number is not divisible by zero.
// Scala program of try-catch// exception // Creating objectobject Arithmetic{ // Main methoddef main(args: Array[String]) { // Try clause try { // Dividing a number val result = 11/0 } // Catch clause catch { // Case statement case x: ArithmeticException => { // Display this if exception is found println("Exception: A number is not divisible by zero.") } }}}
Exception: A number is not divisible by zero.
Here, an exception is thrown as a number is not divisible by zero.
Example :// Scala program of Try-Catch// Exceptionimport java.io.FileReaderimport java.io.FileNotFoundExceptionimport java.io.IOException // Creating objectobject GfG{ // Main methoddef main(args: Array[String]) { // Try clause try { // Creating object for FileReader val t = new FileReader("input.txt") } // Catch clause catch { // Case statement-1 case x: FileNotFoundException => { // Displays this if the file is // missing println("Exception: File missing") } // Case statement-2 case x: IOException => { // Displays this if input/output // exception is found println("Input/output Exception") } }}}Output:Exception: File missing
Here, the try block is executed first and if any exception is thrown then each of the cases of the catch clause is checked and the one which matches the exception thrown is returned as output.
// Scala program of Try-Catch// Exceptionimport java.io.FileReaderimport java.io.FileNotFoundExceptionimport java.io.IOException // Creating objectobject GfG{ // Main methoddef main(args: Array[String]) { // Try clause try { // Creating object for FileReader val t = new FileReader("input.txt") } // Catch clause catch { // Case statement-1 case x: FileNotFoundException => { // Displays this if the file is // missing println("Exception: File missing") } // Case statement-2 case x: IOException => { // Displays this if input/output // exception is found println("Input/output Exception") } }}}
Exception: File missing
Here, the try block is executed first and if any exception is thrown then each of the cases of the catch clause is checked and the one which matches the exception thrown is returned as output.
Picked
Scala
scala-exception
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Apr, 2019"
},
{
"code": null,
"e": 553,
"s": 28,
"text": "The Try-Catch construct is different in Scala than in Java, Try-Catch in Scala is an expression. the Scala make use of pattern matching in the catch clause. Suppose, we have to implement a series of code which can throw an exception and if we want to control that exception then we should utilize the Try-Catch segment as it permits us to try-catch each and every type of exception in only one block, we need to write a series of case statements in catch as Scala uses matching in order to analyze and handle the exceptions."
},
{
"code": null,
"e": 1170,
"s": 553,
"text": "Example :// Scala program of try-catch// exception // Creating objectobject Arithmetic{ // Main methoddef main(args: Array[String]) { // Try clause try { // Dividing a number val result = 11/0 } // Catch clause catch { // Case statement case x: ArithmeticException => { // Display this if exception is found println(\"Exception: A number is not divisible by zero.\") } }}}Output:Exception: A number is not divisible by zero.\nHere, an exception is thrown as a number is not divisible by zero."
},
{
"code": "// Scala program of try-catch// exception // Creating objectobject Arithmetic{ // Main methoddef main(args: Array[String]) { // Try clause try { // Dividing a number val result = 11/0 } // Catch clause catch { // Case statement case x: ArithmeticException => { // Display this if exception is found println(\"Exception: A number is not divisible by zero.\") } }}}",
"e": 1659,
"s": 1170,
"text": null
},
{
"code": null,
"e": 1706,
"s": 1659,
"text": "Exception: A number is not divisible by zero.\n"
},
{
"code": null,
"e": 1773,
"s": 1706,
"text": "Here, an exception is thrown as a number is not divisible by zero."
},
{
"code": null,
"e": 2827,
"s": 1773,
"text": "Example :// Scala program of Try-Catch// Exceptionimport java.io.FileReaderimport java.io.FileNotFoundExceptionimport java.io.IOException // Creating objectobject GfG{ // Main methoddef main(args: Array[String]) { // Try clause try { // Creating object for FileReader val t = new FileReader(\"input.txt\") } // Catch clause catch { // Case statement-1 case x: FileNotFoundException => { // Displays this if the file is // missing println(\"Exception: File missing\") } // Case statement-2 case x: IOException => { // Displays this if input/output // exception is found println(\"Input/output Exception\") } }}}Output:Exception: File missing\nHere, the try block is executed first and if any exception is thrown then each of the cases of the catch clause is checked and the one which matches the exception thrown is returned as output."
},
{
"code": "// Scala program of Try-Catch// Exceptionimport java.io.FileReaderimport java.io.FileNotFoundExceptionimport java.io.IOException // Creating objectobject GfG{ // Main methoddef main(args: Array[String]) { // Try clause try { // Creating object for FileReader val t = new FileReader(\"input.txt\") } // Catch clause catch { // Case statement-1 case x: FileNotFoundException => { // Displays this if the file is // missing println(\"Exception: File missing\") } // Case statement-2 case x: IOException => { // Displays this if input/output // exception is found println(\"Input/output Exception\") } }}}",
"e": 3649,
"s": 2827,
"text": null
},
{
"code": null,
"e": 3674,
"s": 3649,
"text": "Exception: File missing\n"
},
{
"code": null,
"e": 3867,
"s": 3674,
"text": "Here, the try block is executed first and if any exception is thrown then each of the cases of the catch clause is checked and the one which matches the exception thrown is returned as output."
},
{
"code": null,
"e": 3874,
"s": 3867,
"text": "Picked"
},
{
"code": null,
"e": 3880,
"s": 3874,
"text": "Scala"
},
{
"code": null,
"e": 3896,
"s": 3880,
"text": "scala-exception"
},
{
"code": null,
"e": 3902,
"s": 3896,
"text": "Scala"
}
] |
How To Make Barplots with Error bars in ggplot2 in R? | 12 Nov, 2021
In this article, we will discuss how to make a barplot with an error bar using ggplot2 in the R programming language.
Error Bars helps us to visualize the distribution of the data. Error Bars can be applied to any type of plot, to provide an additional layer of detail on the presented data. Often there may be uncertainty around the count values in data due to error margins and we could represent them as an error bar. Error bars are used to show the range of uncertainty around the distribution of data.
We can draw error bars to a plot using the geom_errorbar() function of the ggplot2 package of the R Language.
Syntax: plot + geom_errorbar( aes( ymin= value – standard_error, ymax= value + standard_error ))
where,
value: determines the column for mean values
standard_error: determines the mean error
Here is a basic bar plot with error bars plotted on top using the geom_errorbar() function.
R
# Create sample dataset.seed(5642) sample_data <- data.frame(name = c("Geek1","Geek2", "Geek3","Geek4", "Geeek5") , value = c(31,12,15,28,45)) # create standard errorstandard_error = 5 # Load ggplot2 packagelibrary("ggplot2") # Create bar plot using ggplot() functionggplot(sample_data, aes(name,value)) + # geom_bar function is used to plot bars of barplotgeom_bar(stat = "identity")+ # geom_errorbar function is used to plot error barsgeom_errorbar(aes(ymin=value-standard_error, ymax=value+standard_error), width=.2)
Output:
We can color customize the error bars to suit our requirements using the color, width, and size parameter of the geom_errorbar() function.
Syntax: plot + geom_errorbar( aes( ymin, ymax, color ), width, size)
where,
color: determines the color of the error bar
width: determines the horizontal spread of the error bar.
size: determines the thickness of the error bar.
Here, is a barplot with error bars colored by column name. Error bars are formatted using width and size parameters to give contrasting appeal and look.
R
# Create sample dataset.seed(5642) sample_data <- data.frame(name = c("Geek1","Geek2", "Geek3","Geek4", "Geeek5") , value = c(31,12,15,28,45)) # create standard errorstandard_error = 5 # Load ggplot2 packagelibrary("ggplot2") # Create bar plot using ggplot() functionggplot(sample_data, aes(name,value,, color=name)) + # geom_bar function is used to plot bars of barplotgeom_bar(stat = "identity", fill="white")+ # geom_errorbar function is used to plot error bars# color width and size parameter are used to format# the error barsgeom_errorbar(aes(ymin=value-standard_error, ymax=value+standard_error, color=name), width=0.2, size=2)
Output:
We can customize the line shape of the error bar using the linetype parameter of the geom_errorbar function of the ggplot2 package in the R Language.
Syntax: plot + geom_errorbar( aes( ymin, ymax ), linetype)
where,
linetype: determines the shape of stroke of the error bar
Here, is a basic ggplot2 bar plot with error bars with striped lines made using the linetype property of geom_errorbar() function.
R
# Create sample dataset.seed(5642) sample_data <- data.frame(name = c("Geek1","Geek2", "Geek3","Geek4", "Geeek5") , value = c(31,12,15,28,45)) # create standard errorstandard_error = 5 # Load ggplot2 packagelibrary("ggplot2") # Create bar plot using ggplot() functionggplot(sample_data, aes(name,value,, color=name)) + # geom_bar function is used to plot bars of barplotgeom_bar(stat = "identity", fill="white")+ # geom_errorbar function is used to plot error bars# color width and size parameter are used to# format the error barsgeom_errorbar(aes(ymin=value-standard_error, ymax=value+standard_error, color=name), width=0.2, size=2, linetype=2)
Output:
To emphasize the mean of the error bar we can even add a point at the center of the error bar using the geom_point() function of the ggplot2 package.
Syntax: plot+ geom_point( aes( x, y), size, shape, fill)
where,
size: determines the size of the point
shape: determines the shape of the point
fill: determines the fill color of the point
Here, is a bar plot with error bars and a point at the middle of the error bar made using the geom_errorbar() and the geom_point() function of the ggplot2 package.
R
# Create sample dataset.seed(5642) sample_data <- data.frame(name = c("Geek1","Geek2", "Geek3","Geek4", "Geeek5") , value = c(31,12,15,28,45)) # create standard errorstandard_error = 5 # Load ggplot2 packagelibrary("ggplot2") # Create bar plot using ggplot() functionggplot(sample_data, aes(name,value,, color=name)) + # geom_bar function is used to plot bars of barplotgeom_bar(stat = "identity", fill="white")+ # geom_errorbar function is used to plot error bars# color width and size parameter are used to format# the error barsgeom_errorbar(aes(ymin=value-standard_error, ymax=value+standard_error, color=name), width=0.2, size=1, linetype=1)+ # geom_point is used to give a point at meangeom_point(mapping=aes(name, value), size=4, shape=21, fill="white")
Output:
sumitgumber28
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "In this article, we will discuss how to make a barplot with an error bar using ggplot2 in the R programming language. "
},
{
"code": null,
"e": 536,
"s": 147,
"text": "Error Bars helps us to visualize the distribution of the data. Error Bars can be applied to any type of plot, to provide an additional layer of detail on the presented data. Often there may be uncertainty around the count values in data due to error margins and we could represent them as an error bar. Error bars are used to show the range of uncertainty around the distribution of data."
},
{
"code": null,
"e": 646,
"s": 536,
"text": "We can draw error bars to a plot using the geom_errorbar() function of the ggplot2 package of the R Language."
},
{
"code": null,
"e": 743,
"s": 646,
"text": "Syntax: plot + geom_errorbar( aes( ymin= value – standard_error, ymax= value + standard_error ))"
},
{
"code": null,
"e": 751,
"s": 743,
"text": "where, "
},
{
"code": null,
"e": 796,
"s": 751,
"text": "value: determines the column for mean values"
},
{
"code": null,
"e": 839,
"s": 796,
"text": "standard_error: determines the mean error "
},
{
"code": null,
"e": 931,
"s": 839,
"text": "Here is a basic bar plot with error bars plotted on top using the geom_errorbar() function."
},
{
"code": null,
"e": 933,
"s": 931,
"text": "R"
},
{
"code": "# Create sample dataset.seed(5642) sample_data <- data.frame(name = c(\"Geek1\",\"Geek2\", \"Geek3\",\"Geek4\", \"Geeek5\") , value = c(31,12,15,28,45)) # create standard errorstandard_error = 5 # Load ggplot2 packagelibrary(\"ggplot2\") # Create bar plot using ggplot() functionggplot(sample_data, aes(name,value)) + # geom_bar function is used to plot bars of barplotgeom_bar(stat = \"identity\")+ # geom_errorbar function is used to plot error barsgeom_errorbar(aes(ymin=value-standard_error, ymax=value+standard_error), width=.2)",
"e": 1619,
"s": 933,
"text": null
},
{
"code": null,
"e": 1627,
"s": 1619,
"text": "Output:"
},
{
"code": null,
"e": 1766,
"s": 1627,
"text": "We can color customize the error bars to suit our requirements using the color, width, and size parameter of the geom_errorbar() function."
},
{
"code": null,
"e": 1835,
"s": 1766,
"text": "Syntax: plot + geom_errorbar( aes( ymin, ymax, color ), width, size)"
},
{
"code": null,
"e": 1842,
"s": 1835,
"text": "where,"
},
{
"code": null,
"e": 1887,
"s": 1842,
"text": "color: determines the color of the error bar"
},
{
"code": null,
"e": 1945,
"s": 1887,
"text": "width: determines the horizontal spread of the error bar."
},
{
"code": null,
"e": 1994,
"s": 1945,
"text": "size: determines the thickness of the error bar."
},
{
"code": null,
"e": 2147,
"s": 1994,
"text": "Here, is a barplot with error bars colored by column name. Error bars are formatted using width and size parameters to give contrasting appeal and look."
},
{
"code": null,
"e": 2149,
"s": 2147,
"text": "R"
},
{
"code": "# Create sample dataset.seed(5642) sample_data <- data.frame(name = c(\"Geek1\",\"Geek2\", \"Geek3\",\"Geek4\", \"Geeek5\") , value = c(31,12,15,28,45)) # create standard errorstandard_error = 5 # Load ggplot2 packagelibrary(\"ggplot2\") # Create bar plot using ggplot() functionggplot(sample_data, aes(name,value,, color=name)) + # geom_bar function is used to plot bars of barplotgeom_bar(stat = \"identity\", fill=\"white\")+ # geom_errorbar function is used to plot error bars# color width and size parameter are used to format# the error barsgeom_errorbar(aes(ymin=value-standard_error, ymax=value+standard_error, color=name), width=0.2, size=2)",
"e": 2950,
"s": 2149,
"text": null
},
{
"code": null,
"e": 2958,
"s": 2950,
"text": "Output:"
},
{
"code": null,
"e": 3108,
"s": 2958,
"text": "We can customize the line shape of the error bar using the linetype parameter of the geom_errorbar function of the ggplot2 package in the R Language."
},
{
"code": null,
"e": 3167,
"s": 3108,
"text": "Syntax: plot + geom_errorbar( aes( ymin, ymax ), linetype)"
},
{
"code": null,
"e": 3174,
"s": 3167,
"text": "where,"
},
{
"code": null,
"e": 3232,
"s": 3174,
"text": "linetype: determines the shape of stroke of the error bar"
},
{
"code": null,
"e": 3363,
"s": 3232,
"text": "Here, is a basic ggplot2 bar plot with error bars with striped lines made using the linetype property of geom_errorbar() function."
},
{
"code": null,
"e": 3365,
"s": 3363,
"text": "R"
},
{
"code": "# Create sample dataset.seed(5642) sample_data <- data.frame(name = c(\"Geek1\",\"Geek2\", \"Geek3\",\"Geek4\", \"Geeek5\") , value = c(31,12,15,28,45)) # create standard errorstandard_error = 5 # Load ggplot2 packagelibrary(\"ggplot2\") # Create bar plot using ggplot() functionggplot(sample_data, aes(name,value,, color=name)) + # geom_bar function is used to plot bars of barplotgeom_bar(stat = \"identity\", fill=\"white\")+ # geom_errorbar function is used to plot error bars# color width and size parameter are used to# format the error barsgeom_errorbar(aes(ymin=value-standard_error, ymax=value+standard_error, color=name), width=0.2, size=2, linetype=2)",
"e": 4178,
"s": 3365,
"text": null
},
{
"code": null,
"e": 4186,
"s": 4178,
"text": "Output:"
},
{
"code": null,
"e": 4337,
"s": 4186,
"text": "To emphasize the mean of the error bar we can even add a point at the center of the error bar using the geom_point() function of the ggplot2 package. "
},
{
"code": null,
"e": 4394,
"s": 4337,
"text": "Syntax: plot+ geom_point( aes( x, y), size, shape, fill)"
},
{
"code": null,
"e": 4401,
"s": 4394,
"text": "where,"
},
{
"code": null,
"e": 4440,
"s": 4401,
"text": "size: determines the size of the point"
},
{
"code": null,
"e": 4481,
"s": 4440,
"text": "shape: determines the shape of the point"
},
{
"code": null,
"e": 4526,
"s": 4481,
"text": "fill: determines the fill color of the point"
},
{
"code": null,
"e": 4690,
"s": 4526,
"text": "Here, is a bar plot with error bars and a point at the middle of the error bar made using the geom_errorbar() and the geom_point() function of the ggplot2 package."
},
{
"code": null,
"e": 4692,
"s": 4690,
"text": "R"
},
{
"code": "# Create sample dataset.seed(5642) sample_data <- data.frame(name = c(\"Geek1\",\"Geek2\", \"Geek3\",\"Geek4\", \"Geeek5\") , value = c(31,12,15,28,45)) # create standard errorstandard_error = 5 # Load ggplot2 packagelibrary(\"ggplot2\") # Create bar plot using ggplot() functionggplot(sample_data, aes(name,value,, color=name)) + # geom_bar function is used to plot bars of barplotgeom_bar(stat = \"identity\", fill=\"white\")+ # geom_errorbar function is used to plot error bars# color width and size parameter are used to format# the error barsgeom_errorbar(aes(ymin=value-standard_error, ymax=value+standard_error, color=name), width=0.2, size=1, linetype=1)+ # geom_point is used to give a point at meangeom_point(mapping=aes(name, value), size=4, shape=21, fill=\"white\")",
"e": 5619,
"s": 4692,
"text": null
},
{
"code": null,
"e": 5627,
"s": 5619,
"text": "Output:"
},
{
"code": null,
"e": 5641,
"s": 5627,
"text": "sumitgumber28"
},
{
"code": null,
"e": 5648,
"s": 5641,
"text": "Picked"
},
{
"code": null,
"e": 5657,
"s": 5648,
"text": "R-ggplot"
},
{
"code": null,
"e": 5668,
"s": 5657,
"text": "R Language"
}
] |
What is the use of EXIST and EXIST NOT operator with MySQL subqueries? | The EXIST operator test for the existence of rows in the result set of the subquery. If a subquery row value is found then EXISTS subquery is TRUE and NOT EXISTS subquery if FALSE. To illustrate it we are using the tables ‘Cars’, ‘Customers’ and ‘Reservations’ having the following data −
mysql> Select * from Cars;
+------+--------------+---------+
| ID | Name | Price |
+------+--------------+---------+
| 1 | Nexa | 750000 |
| 2 | Maruti Swift | 450000 |
| 3 | BMW | 4450000 |
| 4 | VOLVO | 2250000 |
| 5 | Alto | 250000 |
| 6 | Skoda | 1250000 |
| 7 | Toyota | 2400000 |
| 8 | Ford | 1100000 |
+------+--------------+---------+
8 rows in set (0.02 sec)
mysql> Select * from Customers;
+-------------+----------+
| Customer_Id | Name |
+-------------+----------+
| 1 | Rahul |
| 2 | Yashpal |
| 3 | Gaurav |
| 4 | Virender |
+-------------+----------+
4 rows in set (0.00 sec)
mysql> Select * from Reservations;
+------+-------------+------------+
| ID | Customer_id | Day |
+------+-------------+------------+
| 1 | 1 | 2017-12-30 |
| 2 | 2 | 2017-12-28 |
| 3 | 2 | 2017-12-29 |
| 4 | 1 | 2017-12-25 |
| 5 | 3 | 2017-12-26 |
+------+-------------+------------+
5 rows in set (0.00 sec)
Following is MySQL subquery with EXIST using the above-mentioned tables −
mysql> Select Name from customers WHERE EXISTS (SELECT * FROM Reservations WHERE Customers.customer_id = Reservations.customer_id);
+---------+
| Name |
+---------+
| Rahul |
| Yashpal |
| Gaurav |
+---------+
3 rows in set (0.06 sec)
The above query gives the names of the customers who have made a reservation.
Following is MySQL subquery with NOT EXIST using the above-mentioned tables −
mysql> Select Name from customers WHERE NOT EXISTS (SELECT * FROM Reservations WHERE Customers.customer_id = Reservations.customer_id);
+----------+
| Name |
+----------+
| Virender |
+----------+
1 row in set (0.04 sec)
The above query gives the names of the customers who have not made any reservation. | [
{
"code": null,
"e": 1351,
"s": 1062,
"text": "The EXIST operator test for the existence of rows in the result set of the subquery. If a subquery row value is found then EXISTS subquery is TRUE and NOT EXISTS subquery if FALSE. To illustrate it we are using the tables ‘Cars’, ‘Customers’ and ‘Reservations’ having the following data −"
},
{
"code": null,
"e": 2470,
"s": 1351,
"text": "mysql> Select * from Cars;\n+------+--------------+---------+\n| ID | Name | Price |\n+------+--------------+---------+\n| 1 | Nexa | 750000 |\n| 2 | Maruti Swift | 450000 |\n| 3 | BMW | 4450000 |\n| 4 | VOLVO | 2250000 |\n| 5 | Alto | 250000 |\n| 6 | Skoda | 1250000 |\n| 7 | Toyota | 2400000 |\n| 8 | Ford | 1100000 |\n+------+--------------+---------+\n8 rows in set (0.02 sec)\n\nmysql> Select * from Customers;\n+-------------+----------+\n| Customer_Id | Name |\n+-------------+----------+\n| 1 | Rahul |\n| 2 | Yashpal |\n| 3 | Gaurav |\n| 4 | Virender |\n+-------------+----------+\n4 rows in set (0.00 sec)\n\nmysql> Select * from Reservations;\n+------+-------------+------------+\n| ID | Customer_id | Day |\n+------+-------------+------------+\n| 1 | 1 | 2017-12-30 |\n| 2 | 2 | 2017-12-28 |\n| 3 | 2 | 2017-12-29 |\n| 4 | 1 | 2017-12-25 |\n| 5 | 3 | 2017-12-26 |\n+------+-------------+------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2544,
"s": 2470,
"text": "Following is MySQL subquery with EXIST using the above-mentioned tables −"
},
{
"code": null,
"e": 2785,
"s": 2544,
"text": "mysql> Select Name from customers WHERE EXISTS (SELECT * FROM Reservations WHERE Customers.customer_id = Reservations.customer_id);\n+---------+\n| Name |\n+---------+\n| Rahul |\n| Yashpal |\n| Gaurav |\n+---------+\n3 rows in set (0.06 sec)"
},
{
"code": null,
"e": 2863,
"s": 2785,
"text": "The above query gives the names of the customers who have made a reservation."
},
{
"code": null,
"e": 2941,
"s": 2863,
"text": "Following is MySQL subquery with NOT EXIST using the above-mentioned tables −"
},
{
"code": null,
"e": 3166,
"s": 2941,
"text": "mysql> Select Name from customers WHERE NOT EXISTS (SELECT * FROM Reservations WHERE Customers.customer_id = Reservations.customer_id);\n+----------+\n| Name |\n+----------+\n| Virender |\n+----------+\n1 row in set (0.04 sec)"
},
{
"code": null,
"e": 3250,
"s": 3166,
"text": "The above query gives the names of the customers who have not made any reservation."
}
] |
SQLAlchemy ORM - Building Relationship | This session describes creation of another table which is related to already existing one in our database. The customers table contains master data of customers. We now need to create invoices table which may have any number of invoices belonging to a customer. This is a case of one to many relationships.
Using declarative, we define this table along with its mapped class, Invoices as given below −
from sqlalchemy import create_engine, ForeignKey, Column, Integer, String
engine = create_engine('sqlite:///sales.db', echo = True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy.orm import relationship
class Customer(Base):
__tablename__ = 'customers'
id = Column(Integer, primary_key = True)
name = Column(String)
address = Column(String)
email = Column(String)
class Invoice(Base):
__tablename__ = 'invoices'
id = Column(Integer, primary_key = True)
custid = Column(Integer, ForeignKey('customers.id'))
invno = Column(Integer)
amount = Column(Integer)
customer = relationship("Customer", back_populates = "invoices")
Customer.invoices = relationship("Invoice", order_by = Invoice.id, back_populates = "customer")
Base.metadata.create_all(engine)
This will send a CREATE TABLE query to SQLite engine as below −
CREATE TABLE invoices (
id INTEGER NOT NULL,
custid INTEGER,
invno INTEGER,
amount INTEGER,
PRIMARY KEY (id),
FOREIGN KEY(custid) REFERENCES customers (id)
)
We can check that new table is created in sales.db with the help of SQLiteStudio tool.
Invoices class applies ForeignKey construct on custid attribute. This directive indicates that values in this column should be constrained to be values present in id column in customers table. This is a core feature of relational databases, and is the “glue” that transforms unconnected collection of tables to have rich overlapping relationships.
A second directive, known as relationship(), tells the ORM that the Invoice class should be linked to the Customer class using the attribute Invoice.customer. The relationship() uses the foreign key relationships between the two tables to determine the nature of this linkage, determining that it is many to one.
An additional relationship() directive is placed on the Customer mapped class under the attribute Customer.invoices. The parameter relationship.back_populates is assigned to refer to the complementary attribute names, so that each relationship() can make intelligent decision about the same relationship as expressed in reverse. On one side, Invoices.customer refers to Invoices instance, and on the other side, Customer.invoices refers to a list of Customers instances.
The relationship function is a part of Relationship API of SQLAlchemy ORM package. It provides a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship.
Following are the basic Relationship Patterns found −
A One to Many relationship refers to parent with the help of a foreign key on the child table. relationship() is then specified on the parent, as referencing a collection of items represented by the child. The relationship.back_populates parameter is used to establish a bidirectional relationship in one-to-many, where the “reverse” side is a many to one.
On the other hand, Many to One relationship places a foreign key in the parent table to refer to the child. relationship() is declared on the parent, where a new scalar-holding attribute will be created. Here again the relationship.back_populates parameter is used for Bidirectionalbehaviour.
One To One relationship is essentially a bidirectional relationship in nature. The uselist flag indicates the placement of a scalar attribute instead of a collection on the “many” side of the relationship. To convert one-to-many into one-to-one type of relation, set uselist parameter to false.
Many to Many relationship is established by adding an association table related to two classes by defining attributes with their foreign keys. It is indicated by the secondary argument to relationship(). Usually, the Table uses the MetaData object associated with the declarative base class, so that the ForeignKey directives can locate the remote tables with which to link. The relationship.back_populates parameter for each relationship() establishes a bidirectional relationship. Both sides of the relationship contain a collection.
21 Lectures
1.5 hours
Jack Chan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2647,
"s": 2340,
"text": "This session describes creation of another table which is related to already existing one in our database. The customers table contains master data of customers. We now need to create invoices table which may have any number of invoices belonging to a customer. This is a case of one to many relationships."
},
{
"code": null,
"e": 2742,
"s": 2647,
"text": "Using declarative, we define this table along with its mapped class, Invoices as given below −"
},
{
"code": null,
"e": 3583,
"s": 2742,
"text": "from sqlalchemy import create_engine, ForeignKey, Column, Integer, String\nengine = create_engine('sqlite:///sales.db', echo = True)\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\nfrom sqlalchemy.orm import relationship\n\nclass Customer(Base):\n __tablename__ = 'customers'\n\n id = Column(Integer, primary_key = True)\n name = Column(String)\n address = Column(String)\n email = Column(String)\n\nclass Invoice(Base):\n __tablename__ = 'invoices'\n \n id = Column(Integer, primary_key = True)\n custid = Column(Integer, ForeignKey('customers.id'))\n invno = Column(Integer)\n amount = Column(Integer)\n customer = relationship(\"Customer\", back_populates = \"invoices\")\n\nCustomer.invoices = relationship(\"Invoice\", order_by = Invoice.id, back_populates = \"customer\")\nBase.metadata.create_all(engine)"
},
{
"code": null,
"e": 3647,
"s": 3583,
"text": "This will send a CREATE TABLE query to SQLite engine as below −"
},
{
"code": null,
"e": 3823,
"s": 3647,
"text": "CREATE TABLE invoices (\n id INTEGER NOT NULL,\n custid INTEGER,\n invno INTEGER,\n amount INTEGER,\n PRIMARY KEY (id),\n FOREIGN KEY(custid) REFERENCES customers (id)\n)"
},
{
"code": null,
"e": 3910,
"s": 3823,
"text": "We can check that new table is created in sales.db with the help of SQLiteStudio tool."
},
{
"code": null,
"e": 4258,
"s": 3910,
"text": "Invoices class applies ForeignKey construct on custid attribute. This directive indicates that values in this column should be constrained to be values present in id column in customers table. This is a core feature of relational databases, and is the “glue” that transforms unconnected collection of tables to have rich overlapping relationships."
},
{
"code": null,
"e": 4571,
"s": 4258,
"text": "A second directive, known as relationship(), tells the ORM that the Invoice class should be linked to the Customer class using the attribute Invoice.customer. The relationship() uses the foreign key relationships between the two tables to determine the nature of this linkage, determining that it is many to one."
},
{
"code": null,
"e": 5042,
"s": 4571,
"text": "An additional relationship() directive is placed on the Customer mapped class under the attribute Customer.invoices. The parameter relationship.back_populates is assigned to refer to the complementary attribute names, so that each relationship() can make intelligent decision about the same relationship as expressed in reverse. On one side, Invoices.customer refers to Invoices instance, and on the other side, Customer.invoices refers to a list of Customers instances."
},
{
"code": null,
"e": 5250,
"s": 5042,
"text": "The relationship function is a part of Relationship API of SQLAlchemy ORM package. It provides a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship."
},
{
"code": null,
"e": 5304,
"s": 5250,
"text": "Following are the basic Relationship Patterns found −"
},
{
"code": null,
"e": 5661,
"s": 5304,
"text": "A One to Many relationship refers to parent with the help of a foreign key on the child table. relationship() is then specified on the parent, as referencing a collection of items represented by the child. The relationship.back_populates parameter is used to establish a bidirectional relationship in one-to-many, where the “reverse” side is a many to one."
},
{
"code": null,
"e": 5954,
"s": 5661,
"text": "On the other hand, Many to One relationship places a foreign key in the parent table to refer to the child. relationship() is declared on the parent, where a new scalar-holding attribute will be created. Here again the relationship.back_populates parameter is used for Bidirectionalbehaviour."
},
{
"code": null,
"e": 6249,
"s": 5954,
"text": "One To One relationship is essentially a bidirectional relationship in nature. The uselist flag indicates the placement of a scalar attribute instead of a collection on the “many” side of the relationship. To convert one-to-many into one-to-one type of relation, set uselist parameter to false."
},
{
"code": null,
"e": 6785,
"s": 6249,
"text": "Many to Many relationship is established by adding an association table related to two classes by defining attributes with their foreign keys. It is indicated by the secondary argument to relationship(). Usually, the Table uses the MetaData object associated with the declarative base class, so that the ForeignKey directives can locate the remote tables with which to link. The relationship.back_populates parameter for each relationship() establishes a bidirectional relationship. Both sides of the relationship contain a collection."
},
{
"code": null,
"e": 6820,
"s": 6785,
"text": "\n 21 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6831,
"s": 6820,
"text": " Jack Chan"
},
{
"code": null,
"e": 6838,
"s": 6831,
"text": " Print"
},
{
"code": null,
"e": 6849,
"s": 6838,
"text": " Add Notes"
}
] |
Stack.Peek Method in C# - GeeksforGeeks | 04 Feb, 2019
This method(comes under System.Collections namespace) is used to return the object at the top of the Stack without removing it. This method is similar to the Pop method, but Peek does not modify the Stack.
Syntax:
public virtual object Peek ();
Return Value: It returns the Object at the top of the Stack.
Exception: Calling Peek() method on empty stack will throw InvalidOperationException. So always check for elements in the stack before retrieving elements using the Peek() method.
Below given are some examples to understand the implementation in a better way.
Example 1:
// C# code to illustrate the// Stack.Peek Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("1st Element"); myStack.Push("2nd Element"); myStack.Push("3rd Element"); myStack.Push("4th Element"); myStack.Push("5th Element"); myStack.Push("6th Element"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements"+ " in the Stack are : "); Console.WriteLine(myStack.Count); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine("Element at the top is : " + myStack.Peek()); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine("Element at the top is : " + myStack.Peek()); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements "+ "in the Stack are : "); Console.WriteLine(myStack.Count); }}
Output:
Total number of elements in the Stack are : 6
Element at the top is : 6th Element
Element at the top is : 6th Element
Total number of elements in the Stack are : 6
Example 2:
// C# code to illustrate the// Stack.Peek Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Displaying the top element of Stack // without removing it from the Stack // Calling Peek() method on empty stack // will throw InvalidOperationException. Console.WriteLine("Element at the top is : " + myStack.Peek()); }}
Runtime Error:
Unhandled Exception:System.InvalidOperationException: Stack empty.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.peek?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Stack
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Arrays of Strings
C# Dictionary with examples
C# | Method Overriding
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates | [
{
"code": null,
"e": 23288,
"s": 23260,
"text": "\n04 Feb, 2019"
},
{
"code": null,
"e": 23494,
"s": 23288,
"text": "This method(comes under System.Collections namespace) is used to return the object at the top of the Stack without removing it. This method is similar to the Pop method, but Peek does not modify the Stack."
},
{
"code": null,
"e": 23502,
"s": 23494,
"text": "Syntax:"
},
{
"code": null,
"e": 23534,
"s": 23502,
"text": "public virtual object Peek ();\n"
},
{
"code": null,
"e": 23595,
"s": 23534,
"text": "Return Value: It returns the Object at the top of the Stack."
},
{
"code": null,
"e": 23775,
"s": 23595,
"text": "Exception: Calling Peek() method on empty stack will throw InvalidOperationException. So always check for elements in the stack before retrieving elements using the Peek() method."
},
{
"code": null,
"e": 23855,
"s": 23775,
"text": "Below given are some examples to understand the implementation in a better way."
},
{
"code": null,
"e": 23866,
"s": 23855,
"text": "Example 1:"
},
{
"code": "// C# code to illustrate the// Stack.Peek Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"1st Element\"); myStack.Push(\"2nd Element\"); myStack.Push(\"3rd Element\"); myStack.Push(\"4th Element\"); myStack.Push(\"5th Element\"); myStack.Push(\"6th Element\"); // Displaying the count of elements // contained in the Stack Console.Write(\"Total number of elements\"+ \" in the Stack are : \"); Console.WriteLine(myStack.Count); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine(\"Element at the top is : \" + myStack.Peek()); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine(\"Element at the top is : \" + myStack.Peek()); // Displaying the count of elements // contained in the Stack Console.Write(\"Total number of elements \"+ \"in the Stack are : \"); Console.WriteLine(myStack.Count); }}",
"e": 25191,
"s": 23866,
"text": null
},
{
"code": null,
"e": 25199,
"s": 25191,
"text": "Output:"
},
{
"code": null,
"e": 25364,
"s": 25199,
"text": "Total number of elements in the Stack are : 6\nElement at the top is : 6th Element\nElement at the top is : 6th Element\nTotal number of elements in the Stack are : 6\n"
},
{
"code": null,
"e": 25375,
"s": 25364,
"text": "Example 2:"
},
{
"code": "// C# code to illustrate the// Stack.Peek Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Displaying the top element of Stack // without removing it from the Stack // Calling Peek() method on empty stack // will throw InvalidOperationException. Console.WriteLine(\"Element at the top is : \" + myStack.Peek()); }}",
"e": 25890,
"s": 25375,
"text": null
},
{
"code": null,
"e": 25905,
"s": 25890,
"text": "Runtime Error:"
},
{
"code": null,
"e": 25972,
"s": 25905,
"text": "Unhandled Exception:System.InvalidOperationException: Stack empty."
},
{
"code": null,
"e": 25983,
"s": 25972,
"text": "Reference:"
},
{
"code": null,
"e": 26081,
"s": 25983,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.peek?view=netframework-4.7.2"
},
{
"code": null,
"e": 26110,
"s": 26081,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 26135,
"s": 26110,
"text": "CSharp-Collections-Stack"
},
{
"code": null,
"e": 26149,
"s": 26135,
"text": "CSharp-method"
},
{
"code": null,
"e": 26152,
"s": 26149,
"text": "C#"
},
{
"code": null,
"e": 26250,
"s": 26152,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26304,
"s": 26250,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 26366,
"s": 26304,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 26394,
"s": 26366,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 26436,
"s": 26394,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 26459,
"s": 26436,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 26487,
"s": 26459,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 26510,
"s": 26487,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 26528,
"s": 26510,
"text": "Destructors in C#"
},
{
"code": null,
"e": 26574,
"s": 26528,
"text": "Difference between Ref and Out keywords in C#"
}
] |
Convert from String to long in Java | To convert String to long, the following are the two methods.
The following is an example wherein we use parseLong() method.
Live Demo
public class Demo {
public static void main(String[] args) {
String myStr = "5";
Long myLong = Long.parseLong(myStr);
System.out.println("Long: "+myLong);
}
}
Long: 5
The following is an example wherein we have used valueOf() and longValue() method to convert String to long.
Live Demo
public class Demo {
public static void main(String[] args) {
String myStr = "20";
long res = Long.valueOf(myStr).longValue();
System.out.println("Long: "+res);
}
}
Long: 20 | [
{
"code": null,
"e": 1124,
"s": 1062,
"text": "To convert String to long, the following are the two methods."
},
{
"code": null,
"e": 1187,
"s": 1124,
"text": "The following is an example wherein we use parseLong() method."
},
{
"code": null,
"e": 1198,
"s": 1187,
"text": " Live Demo"
},
{
"code": null,
"e": 1381,
"s": 1198,
"text": "public class Demo {\n public static void main(String[] args) {\n String myStr = \"5\";\n Long myLong = Long.parseLong(myStr);\n System.out.println(\"Long: \"+myLong);\n }\n}"
},
{
"code": null,
"e": 1389,
"s": 1381,
"text": "Long: 5"
},
{
"code": null,
"e": 1498,
"s": 1389,
"text": "The following is an example wherein we have used valueOf() and longValue() method to convert String to long."
},
{
"code": null,
"e": 1509,
"s": 1498,
"text": " Live Demo"
},
{
"code": null,
"e": 1697,
"s": 1509,
"text": "public class Demo {\n public static void main(String[] args) {\n String myStr = \"20\";\n long res = Long.valueOf(myStr).longValue();\n System.out.println(\"Long: \"+res);\n }\n}"
},
{
"code": null,
"e": 1706,
"s": 1697,
"text": "Long: 20"
}
] |
Area Under the Curve and Beyond with Integrated Discrimination Improvement and Net Reclassification | by lambert leong | Towards Data Science | AUC is a good starting metric when comparing the performance of two models but it does not always tell the whole story
NRI looks at the new models ability to correctly reclassify cancers and benigns and should be used alongside AUC
IDI quantifies improvement of the slopes of the discrimination curves and plotting it can provide information AUC alone does not afford.
Published example of these concepts in medicine.
Code for the following example and useful AUC, NRI, IDI functions can be found at github.
In machine learning and diagnostic medicine the area under the receiver operating characteristic (ROC) curve or AUC is a common metric used to evaluate the predictive performance of a model or diagnostic test. New models are often bench marked against established models using AUC. Comparing AUCs of new and old models to evaluate improvement is a good place to start however, many end their analysis here and believe that simply reporting a higher AUC is sufficient. AUC can be misleading as it gives equal weight to the full range of sensitivity and specificity values even though a limited range, or specific threshold, may be of practical interest. In this article, we show how to fully interrogate new and improved model performance, beyond simple AUC comparisons, as to provide a more comprehensive understanding of improvements within the context of a given problem. We also present a coded example, in Python, to demonstrate the concepts we present.
Breast cancer is the leading cause of cancer death in women world wide. Early detection has helped to lower the mortality rate and the earlier a malignancy is identified, the more likely a patient is to survive. As such, great effort has been allocated to developing predictive models to better identify cancer. In this example we use extracted imaging features to build models to predict malignancy probability. We use data from the Diagnostic Wisconsin Breast Cancer Database [1] housed at the UCI Machine Learning Repository.
As mentioned previously, AUC gives equal weight to all thresholds but this may not be practical in the context of breast cancer diagnosis. The Breast Imaging Reporting and Data System or (BI-RADS) [2]. provides a course of action for a given probability of malignancy. In short, if the probability of malignancy is greater than 2%, a biopsy is recommended. Biopsies are invasive procedures and they can be physically and mentally detrimental to patients. A new and improved breast model would ideally be better at identifying cancers (sensitivity increase) and reducing false positives (specificity increase), preferably below 2% to avoid invasive and unnecessary biopsies.
We set up the example with the following code snippets.
# Import Modules #import osimport sysimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport seaborn as snsfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import train_test_splitfrom sklearn import metricsfrom sklearn.metrics import roc_auc_scorefrom sklearn.metrics import roc_auc_score
After we import the necessary modules, we load the breast cancer data set and split the data into a train and test set. Note, it is best practice to also create a validation set and we would normally do that but for the sake of this example we will stick with just a training and test set.
# Import data #data = load_breast_cancer()# Create DataFrame and Split Datadf = pd.DataFrame(data=data['data'],columns=data['feature_names'])df['label']=data['target']x_train, x_test, y_train, y_test = train_test_split(df.iloc[:,:-1], df.iloc[:,-1], test_size=0.40, random_state=123)
Also for the sake of this example, we will pretend that our reference/bench mark model was built on breast imaging features pertaining to texture, concave points, smoothness, fractal dimension, and compactness. We will also pretend that the new model uses additional imaging biomarkers/features which pertain to radius, perimeter, area, symmetry, and concavity. In total, the reference model is built using a total of 15 features while the new model is built using 30 features (15 features used by the original model and 15 new features). The following code snippet creates to two sets of features.
# create ref and new model feature sets #ref_feat, new_feat = [],[]for i in data['feature_names']: if 'fractal' in i or 'smoothness' in i or 'texture' in i ...or 'concave' in i or 'compactness' in i: ref_feat+=[i]
We create a reference or “ref model” with 15 features and the “new model” with all 30 features.
ref_model = RandomForestClassifier()new_model = RandomForestClassifier()# fit models to train dataref_model.fit(x_train[ref_feat], y_train)new_model.fit(x_train[new_feat], y_train)# make predictions on test datatest_ref_pred=ref_model.predict_proba(x_test[ref_feat])test_new_pred=new_model.predict_proba(x_test[new_feat])
We previously mentioned that comparing AUCs is a good starting point. We do that here to get an idea of how the new model performed with respect to our reference model. We use the following custom function to visualize ROC curves and confidence intervals (CI).
def bootstrap_results(y_truth, y_pred,num_bootstraps = 1000): n_bootstraps = num_bootstraps rng_seed = 42 # control reproducibility y_pred=y_pred y_true=y_truth rng = np.random.RandomState(rng_seed) tprs=[] fprs=[] aucs=[] threshs=[] base_thresh = np.linspace(0, 1, 101) for i in range(n_bootstraps): # bootstrap by sampling with replacement on the prediction indices indices = rng.randint(0, len(y_pred), len(y_pred)) if len(np.unique(y_true[indices])) < 2: # We need at least one positive and one negative sample for ROC AUC continue fpr, tpr, thresh = metrics.roc_curve(y_true[indices],y_pred[indices]) thresh=thresh[1:] thresh=np.append(thresh,[0.0]) thresh=thresh[::-1] fpr = np.interp(base_thresh, thresh, fpr[::-1]) tpr = np.interp(base_thresh, thresh, tpr[::-1]) tprs.append(tpr) fprs.append(fpr) threshs.append(thresh) tprs = np.array(tprs) mean_tprs = tprs.mean(axis=0) fprs = np.array(fprs) mean_fprs = fprs.mean(axis=0) return base_thresh, mean_tprs, mean_fprsdef get_auc_ci(y_truth, y_pred,num_bootstraps = 1000): n_bootstraps = num_bootstraps rng_seed = 42 # control reproducibility bootstrapped_scores = [] y_pred=y_pred y_true=y_truth rng = np.random.RandomState(rng_seed) tprs=[] aucs=[] base_fpr = np.linspace(0, 1, 101) for i in range(n_bootstraps): # bootstrap by sampling with replacement on the prediction indices indices = rng.randint(0, len(y_pred), len(y_pred)) if len(np.unique(y_true[indices])) < 2: # We need at least one positive and one negative sample for ROC AUC continue score = roc_auc_score(y_true[indices], y_pred[indices]) bootstrapped_scores.append(score) fpr, tpr, _ = metrics.roc_curve(y_true[indices],y_pred[indices]) roc_auc = metrics.auc(fpr, tpr) aucs.append(roc_auc) tpr = np.interp(base_fpr, fpr, tpr) tpr[0] = 0.0 tprs.append(tpr) tprs = np.array(tprs) mean_tprs = tprs.mean(axis=0) std = tprs.std(axis=0) mean_auc = metrics.auc(base_fpr, mean_tprs) std_auc = np.std(aucs) tprs_upper = np.minimum(mean_tprs + std*2, 1) tprs_lower = mean_tprs - std*2 return base_fpr, mean_tprs, tprs_lower, tprs_upper, mean_auc, std_aucdef plot_auc(truth, reference_model, new_model,n_bootstraps=1000, save=False): y_truth = truth ref_model = reference_model new_model = new_model ref_fpr, ref_tpr, ref_thresholds = metrics.roc_curve(y_truth, ref_model) new_fpr, new_tpr, new_thresholds = metrics.roc_curve(y_truth, new_model) ref_auc, new_auc = metrics.auc(ref_fpr, ref_tpr), metrics.auc(new_fpr, new_tpr) print('ref auc =',ref_auc, '\newn auc = ', new_auc) base_fpr_ref, mean_tprs_ref, tprs_lower_ref, tprs_upper_ref, mean_auc_ref, std_auc_ref=get_auc_ci(y_truth, ref_model,n_bootstraps) base_fpr_new, mean_tprs_new, tprs_lower_new, tprs_upper_new, mean_auc_new, std_auc_new=get_auc_ci(y_truth, new_model,n_bootstraps) plt.figure(figsize=(8, 8)) lw = 2 plt.plot(ref_fpr, ref_tpr, color='blue', lw=lw, label='Reference raw ROC (AUC = %0.2f)' % ref_auc, linestyle='--') plt.plot(base_fpr_ref, mean_tprs_ref, 'b', alpha = 0.8, label=r'Reference mean ROC (AUC=%0.2f, CI=%0.2f-%0.2f)' % (mean_auc_ref, (mean_auc_ref-2*std_auc_ref),(mean_auc_ref+2*std_auc_ref)),) plt.fill_between(base_fpr_ref, tprs_lower_ref, tprs_upper_ref, color = 'b', alpha = 0.2) plt.plot(new_fpr, new_tpr, color='darkorange', lw=lw, label='New raw ROC (AUC = %0.2f)' % new_auc, linestyle='--') plt.plot(base_fpr_new, mean_tprs_new, 'darkorange', alpha = 0.8, label=r'New mean ROC (AUC=%0.2f, CI=%0.2f-%0.2f)' % (mean_auc_new,(mean_auc_new-2*std_auc_new),(mean_auc_new+2*std_auc_new)),) plt.fill_between(base_fpr_new, tprs_lower_new, tprs_upper_new, color = 'darkorange', alpha = 0.2) plt.plot([0, 1], [0, 1], color='gray', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.0]) plt.xlabel('1 - Specificity', fontsize=18) plt.ylabel('Sensitivity', fontsize=18) plt.legend(loc="lower right", fontsize=13) plt.gca().set_aspect('equal', adjustable='box')
We run the following to generate AUC plots.
plot_auc(y_test.values,test_ref_pred[:,1],test_new_pred[:,1],n_bootstraps=100)
Figure 1: AUC curves with confidence intervals calculated using bootstrapping
Mean curves and the 95% confidence interval in Figure 1. were calculated via 100 rounds of bootstrapping, see code above. The reference (blue curve) and new model (orange curve) produce similar AUC at 0.99 and 0.99, respectively. The confidence interval is slightly narrower for the new model. Overall, it is difficult to draw any meaningful conclusion from the AUC curves alone and it would appear that the new model with additional features did little to nothing to improve malignancy predictions.
Our example in Figure 1. demonstrates how using only AUC can be limiting and suggest that analysis needs to go beyond simile AUC comparision. We present two additional metrics which are commonly used to asses the impact of new features or biomarkers on a model. These metrics include the net reclassification index (NRI) and the integrated discrimination improvement (IDI) [3]. These two metrics will help in understanding the actual differences in the two models that may not be obvious in Figure 1.
The NRI is derived by summing the number of NRI events and NRI nonevents. In our example, events are synonymous to patients with cancer or maligancies and NRI nonevents are synonymous to patient who do have benign findings. The NRI events is the net proportion of patients with events reassigned to a higher risk category and the NRI nonevents is the number of patients without events reassigned to a lower risk category [4]. We compute the NRI using the following Python functions.
def check_cat(prob,thresholds): cat=0 for i,v in enumerate(thresholds): if prob>v: cat=i return catdef make_cat_matrix(ref, new, indices, thresholds): num_cats=len(thresholds) mat=np.zeros((num_cats,num_cats)) for i in indices: row,col=check_cat(ref[i],thresholds),check_cat(new[i],thresholds) mat[row,col]+=1 return matdef nri(y_truth,y_ref, y_new,risk_thresholds): event_index = np.where(y_truth==1)[0] nonevent_index = np.where(y_truth==0)[0] event_mat=make_cat_matrix(y_ref,y_new,event_index,risk_thresholds) nonevent_mat=make_cat_matrix(y_ref,y_new,nonevent_index,risk_thresholds) events_up, events_down = event_mat[0,1:].sum()+event_mat[1,2:].sum()+event_mat[2,3:].sum(),event_mat[1,:1].sum()+event_mat[2,:2].sum()+event_mat[3,:3].sum() nonevents_up, nonevents_down = nonevent_mat[0,1:].sum()+nonevent_mat[1,2:].sum()+nonevent_mat[2,3:].sum(),nonevent_mat[1,:1].sum()+nonevent_mat[2,:2].sum()+nonevent_mat[3,:3].sum() nri_events = (events_up/len(event_index))-(events_down/len(event_index)) nri_nonevents = (nonevents_down/len(nonevent_index))-(nonevents_up/len(nonevent_index)) return nri_events, nri_nonevents, nri_events + nri_nonevents
We input both the reference and new models predictions into the NRI function to calculate the events, nonevents, and total NRI.
print(nri(y_test.values,test_ref_pred[:,1],test_new_pred[:,1],[0.02,0.1,0.5,0.95]))
The output from the code above is:
0.1642857142857143, 0.125, 0.2892857142857143
It is tempting to state that “the new model reclassified 29% of the patients when compared to the reference model” however, this would not be an accurate statement nor a proper interpretation of NRI. Since the NRI is the sum of the proportion of events and not events it is possible to have an NRI of 2 or 200%. Stating that the new model reclassified 200% more individuals is not possible because it implies that there are suddenly twice as many patients.A more correct interpretation would be to state that the new model correctly classified 16% more cancer cases and 13% more benigns when compared to the reference, totaling a overall NRI of 29%.
The NRI show us that adding more features to the new model reclassified both malignant and non-malignant patients. This information could not be concluded from AUC alone and may have incorrectly led people to think the models were the same. In a clinical setting, the new model would have found more cancers which could potentially save more lives. Also, the new model would have correctly identified more benigns which would translate to less stress for an individual and potentially sparing them from having and invasive procedure like a biopsy.
Category free or cfNRI is a newer metric and tracks overall movement of event and nonevents, irrespective of class. For our breast cancer example, the American College of Radiology (ACR) has distinct BI-RADS classes and therefore we do not find the need to calculate the cfNRI. We provide coded functions to calculate cfNRIs below in the instance that it may suit you problem.
def track_movement(ref,new, indices): up, down = 0,0 for i in indices: ref_val, new_val = ref[i],new[i] if ref_val<new_val: up+=1 elif ref_val>new_val: down+=1 return up, downdef category_free_nri(y_truth,y_ref, y_new): event_index = np.where(y_truth==1)[0] nonevent_index = np.where(y_truth==0)[0] events_up, events_down = track_movement(y_ref, y_new,event_index) nonevents_up, nonevents_down = track_movement(y_ref, y_new,nonevent_index) nri_events = (events_up/len(event_index))-(events_down/len(event_index)) nri_nonevents = (nonevents_down/len(nonevent_index))-(nonevents_up/len(nonevent_index)) #print(events_up, events_down, len(event_index), nonevents_up, nonevents_down, len(nonevent_index), nri_events, nri_nonevents, nri_events+nri_nonevents) return nri_events, nri_nonevents, nri_events + nri_nonevents
The IDI is a measure in the change of the discrimination slopes and shows the impact of new biomarkers on a binary predictive model. The IDI is the sum of the integrated sensitivity (IS) and integrated specificity (IP) and like NRI, it separates out events and nonevents or in this case cancers and benigns. We use the following code to calculate and plot the IDI curves [5].
def area_between_curves(y1,y2): diff = y1 - y2 # calculate difference posPart = np.maximum(diff, 0) negPart = -np.minimum(diff, 0) posArea = np.trapz(posPart) negArea = np.trapz(negPart) return posArea,negArea,posArea-negAreadef plot_idi(y_truth, ref_model, new_model, save=False): ref_fpr, ref_tpr, ref_thresholds = metrics.roc_curve(y_truth, ref_model) new_fpr, new_tpr, new_thresholds = metrics.roc_curve(y_truth, new_model) base, mean_tprs, mean_fprs=bootstrap_results( y_truth, new_model,100) base2, mean_tprs2, mean_fprs2=bootstrap_results( y_truth, ref_model,100) is_pos,is_neg, idi_event=area_between_curves(mean_tprs,mean_tprs2) ip_pos,ip_neg, idi_nonevent=area_between_curves(mean_fprs2,mean_fprs) print('IS positive', round(is_pos,2),'IS negative',round(is_neg,2),'IDI events',round(idi_event,2)) print('IP positive', round(ip_pos,2),'IP negative',round(ip_neg,2),'IDI nonevents',round(idi_nonevent,2)) print('IDI =',round(idi_event+idi_nonevent,2)) plt.figure(figsize=(10, 10)) ax=plt.axes() lw = 2 plt.plot(base, mean_tprs, 'black', alpha = 0.5, label='Events New (New)' ) plt.plot(base, mean_fprs, 'red', alpha = 0.5, label='Nonevents New (New)') plt.plot(base2, mean_tprs2, 'black', alpha = 0.7, linestyle='--',label='Events Reference (Ref)' ) plt.plot(base2, mean_fprs2, 'red', alpha = 0.7, linestyle='--', label='Nonevents Reference (Ref)') plt.fill_between(base, mean_tprs,mean_tprs2, color='black',alpha = 0.1, label='Integrated Sensitivity (area = %0.2f)'%idi_event) plt.fill_between(base, mean_fprs,mean_fprs2, color='red', alpha = 0.1, label='Integrated Specificity (area = %0.2f)'%idi_nonevent)#''' #TODO: comment out if not for breast birads ### BIRADS Thresholds ### plt.axvline(x=0.02,color='darkorange',linestyle='--',alpha=.5,label='BI-RADS 3/4a Border (2%)') plt.axvline(x=0.10,color='green',linestyle='--',alpha=.5,label='BI-RADS 4a/4b Border (10%)') plt.axvline(x=0.5,color='blue',linestyle='--',alpha=.5,label='BI-RADS 4b/4c Border (50%)') plt.axvline(x=0.95,color='purple',linestyle='--',alpha=.5,label='BI-RADS 4c/5 Border (95%)') def nri_annotation(plt, threshold): x_pos = base[threshold] x_offset=0.02 x_offset2=x_offset text_y_offset=0.01 text_y_offset2=text_y_offset if threshold==2: text_y_offset=0.04 text_y_offset2=0.04 x_offset2=0.05 print(x_pos+x_offset, (np.mean([mean_tprs2[threshold], mean_tprs[threshold]])+text_y_offset), x_pos, (np.mean([mean_tprs2[threshold], mean_tprs[threshold]]))) text_y_events=np.mean([mean_tprs2[threshold], mean_tprs[threshold]])+text_y_offset text_y_nonevents=np.mean([mean_fprs[threshold], mean_fprs2[threshold]])+text_y_offset2 plt.annotate('', xy=(x_pos+0.02, mean_tprs2[threshold+1]), xycoords='data', xytext=(x_pos+0.02, mean_tprs[threshold]), textcoords='data', arrowprops={'arrowstyle': '|-|'}) plt.annotate('NRI$_{events}$ = %0.2f'%(mean_tprs[threshold]-mean_tprs2[threshold]), xy=(x_pos+x_offset, text_y_events), xycoords='data', xytext=(x_pos+x_offset, text_y_events), textcoords='offset points', fontsize=15) plt.annotate('', xy=(x_pos+0.02, mean_fprs[threshold]), xycoords='data', xytext=(x_pos+0.02, mean_fprs2[threshold]), textcoords='data', arrowprops=dict(arrowstyle= '|-|',color='r')) plt.annotate('NRI$_{nonevents}$ = %0.2f'%(mean_fprs2[threshold]-mean_fprs[threshold]), xy=(x_pos+x_offset2, text_y_nonevents), xycoords='data', xytext=(x_pos+x_offset2, text_y_nonevents), textcoords='offset points', fontsize=15) print('Threshold =',round(x_pos,2),'NRI events =',round(mean_tprs[threshold]-mean_tprs2[threshold],4), 'NRI nonevents =',round(mean_fprs2[threshold]-mean_fprs[threshold],4),'Total =', round((mean_tprs[threshold]-mean_tprs2[threshold])+(mean_fprs2[threshold]-mean_fprs[threshold]),4)) nri_annotation(plt,2) nri_annotation(plt,10) nri_annotation(plt,50) nri_annotation(plt,95) #''' plt.xlim([0.0, 1.10]) plt.ylim([0.0, 1.10]) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) plt.xlabel('Calculated Risk', fontsize=18) plt.ylabel('Sensitivity (black), 1 - Specificity (red)', fontsize=18) plt.legend(loc="upper right", fontsize=11) plt.legend(loc=0, fontsize=11, bbox_to_anchor=(0,0,1.2,.9)) plt.gca().set_aspect('equal', adjustable='box') #if save: # plt.savefig('idi_curve.png',dpi=300, bbox_inches='tight') look=95 plt.show()
We run the following command to generate the graph in Figure 2.
plot_idi(y_test.values,test_ref_pred[:,1],test_new_pred[:,1])
Output:
IS positive 3.58 IS negative 0.16 IDI events 3.42IP positive 4.61 IP negative 0.04 IDI nonevents 4.57IDI = 7.980.04 1.04 0.02 1.0Threshold = 0.02 NRI events = 0.0 NRI nonevents = 0.2762 Total = 0.2762Threshold = 0.1 NRI events = -0.008 NRI nonevents = 0.1002 Total = 0.0922Threshold = 0.5 NRI events = 0.0215 NRI nonevents = 0.0317 Total = 0.0532Threshold = 0.95 NRI events = 0.1389 NRI nonevents = -0.0136 Total = 0.1252
Figure 2: IDI curve with calculated NRI at each class or BI-RADS border
The dashed and solid curves represent the reference and new model respectively. In the ideal case, the solid black line would be moved to the upper right indicating the most improvement to sensitivity and the red line would be lowered to the bottom right indicating the most improved specificity. The area between the black and red curves equate to the IS and IP and the total sum of the black and red area equates to the IDI. IDI provides more information that the AUC curves especially with respects to the orange dashed vertical line or the BI-RADS 3/4a border. At this border, the IP or red area is large which indicates that the new model was able to better predict benigns. This border is particularly interesting because it is recommended that all patients with BI-RADS 4 or greater receive biopsies [6]. The large area at the 3/4a border shows that adding new features to the new model increase specificity and potentially prevented 28% more people (NRI nonevents=0.28) from being unnecessarily biopsied.
AUC is a good metric but does not provide all the information needed for a comprehensive analysis of the impact of new biomarkers and models. The NRI and IDI should be used to complement AUC findings and interpretations. As a data scientist and cancer researcher who uses Python, it was difficult to find functions and code snippets that computed and plotted NRI and IDI as presented here. This was my motivation for posting this and I hope that my code can help other in their research, discoveries, and pursuit of better health care solutions.
[1] Dua, D. and Graff, C, (2019), Irvine, CA: University of California, School of Information and Computer Science, UCI Machine Learning Repository [http://archive.ics.uci.edu/ml].
[2] Understanding mammogram reports: Mammogram results. (n.d.). Retrieved May 06, 2021, from https://www.cancer.org/cancer/breast-cancer/screening-tests-and-early-detection/mammograms/understanding-your-mammogram-report.html
[3] Pencina, M. J., D’Agostino Sr, R. B., D’Agostino Jr, R. B., & Vasan, R. S., Evaluating the added predictive ability of a new marker: from area under the ROC curve to reclassification and beyond, (2008), Statistics in medicine, 27(2), 157–172.
[4] Pencina, M. J., D’Agostino Sr, R. B., & Steyerberg, E. W., Extensions of net reclassification improvement calculations to measure usefulness of new biomarkers, (2011), Statistics in medicine, 30(1), 11–21.
[5] Pickering, J. W., & Endre, Z. H., New metrics for assessing diagnostic potential of candidate biomarkers, (2012), Clinical Journal of the American Society of Nephrology, 7(8), 1355–1364.
[6] Leong, L., Malkov, S., Drukker, K., Niell, B., Sadowski, P., Wolfgruber, T., ... & Shepherd, J., Dual-energy three compartment breast imaging (3CB) for novel compositional biomarkers to improve detection of malignant lesions, (2021).
Originally published at https://www.lambertleong.com on May 1, 2021. | [
{
"code": null,
"e": 291,
"s": 172,
"text": "AUC is a good starting metric when comparing the performance of two models but it does not always tell the whole story"
},
{
"code": null,
"e": 404,
"s": 291,
"text": "NRI looks at the new models ability to correctly reclassify cancers and benigns and should be used alongside AUC"
},
{
"code": null,
"e": 541,
"s": 404,
"text": "IDI quantifies improvement of the slopes of the discrimination curves and plotting it can provide information AUC alone does not afford."
},
{
"code": null,
"e": 590,
"s": 541,
"text": "Published example of these concepts in medicine."
},
{
"code": null,
"e": 680,
"s": 590,
"text": "Code for the following example and useful AUC, NRI, IDI functions can be found at github."
},
{
"code": null,
"e": 1638,
"s": 680,
"text": "In machine learning and diagnostic medicine the area under the receiver operating characteristic (ROC) curve or AUC is a common metric used to evaluate the predictive performance of a model or diagnostic test. New models are often bench marked against established models using AUC. Comparing AUCs of new and old models to evaluate improvement is a good place to start however, many end their analysis here and believe that simply reporting a higher AUC is sufficient. AUC can be misleading as it gives equal weight to the full range of sensitivity and specificity values even though a limited range, or specific threshold, may be of practical interest. In this article, we show how to fully interrogate new and improved model performance, beyond simple AUC comparisons, as to provide a more comprehensive understanding of improvements within the context of a given problem. We also present a coded example, in Python, to demonstrate the concepts we present."
},
{
"code": null,
"e": 2167,
"s": 1638,
"text": "Breast cancer is the leading cause of cancer death in women world wide. Early detection has helped to lower the mortality rate and the earlier a malignancy is identified, the more likely a patient is to survive. As such, great effort has been allocated to developing predictive models to better identify cancer. In this example we use extracted imaging features to build models to predict malignancy probability. We use data from the Diagnostic Wisconsin Breast Cancer Database [1] housed at the UCI Machine Learning Repository."
},
{
"code": null,
"e": 2841,
"s": 2167,
"text": "As mentioned previously, AUC gives equal weight to all thresholds but this may not be practical in the context of breast cancer diagnosis. The Breast Imaging Reporting and Data System or (BI-RADS) [2]. provides a course of action for a given probability of malignancy. In short, if the probability of malignancy is greater than 2%, a biopsy is recommended. Biopsies are invasive procedures and they can be physically and mentally detrimental to patients. A new and improved breast model would ideally be better at identifying cancers (sensitivity increase) and reducing false positives (specificity increase), preferably below 2% to avoid invasive and unnecessary biopsies."
},
{
"code": null,
"e": 2897,
"s": 2841,
"text": "We set up the example with the following code snippets."
},
{
"code": null,
"e": 3321,
"s": 2897,
"text": "# Import Modules #import osimport sysimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport seaborn as snsfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import train_test_splitfrom sklearn import metricsfrom sklearn.metrics import roc_auc_scorefrom sklearn.metrics import roc_auc_score"
},
{
"code": null,
"e": 3611,
"s": 3321,
"text": "After we import the necessary modules, we load the breast cancer data set and split the data into a train and test set. Note, it is best practice to also create a validation set and we would normally do that but for the sake of this example we will stick with just a training and test set."
},
{
"code": null,
"e": 3895,
"s": 3611,
"text": "# Import data #data = load_breast_cancer()# Create DataFrame and Split Datadf = pd.DataFrame(data=data['data'],columns=data['feature_names'])df['label']=data['target']x_train, x_test, y_train, y_test = train_test_split(df.iloc[:,:-1], df.iloc[:,-1], test_size=0.40, random_state=123)"
},
{
"code": null,
"e": 4494,
"s": 3895,
"text": "Also for the sake of this example, we will pretend that our reference/bench mark model was built on breast imaging features pertaining to texture, concave points, smoothness, fractal dimension, and compactness. We will also pretend that the new model uses additional imaging biomarkers/features which pertain to radius, perimeter, area, symmetry, and concavity. In total, the reference model is built using a total of 15 features while the new model is built using 30 features (15 features used by the original model and 15 new features). The following code snippet creates to two sets of features."
},
{
"code": null,
"e": 4718,
"s": 4494,
"text": "# create ref and new model feature sets #ref_feat, new_feat = [],[]for i in data['feature_names']: if 'fractal' in i or 'smoothness' in i or 'texture' in i ...or 'concave' in i or 'compactness' in i: ref_feat+=[i]"
},
{
"code": null,
"e": 4814,
"s": 4718,
"text": "We create a reference or “ref model” with 15 features and the “new model” with all 30 features."
},
{
"code": null,
"e": 5136,
"s": 4814,
"text": "ref_model = RandomForestClassifier()new_model = RandomForestClassifier()# fit models to train dataref_model.fit(x_train[ref_feat], y_train)new_model.fit(x_train[new_feat], y_train)# make predictions on test datatest_ref_pred=ref_model.predict_proba(x_test[ref_feat])test_new_pred=new_model.predict_proba(x_test[new_feat])"
},
{
"code": null,
"e": 5397,
"s": 5136,
"text": "We previously mentioned that comparing AUCs is a good starting point. We do that here to get an idea of how the new model performed with respect to our reference model. We use the following custom function to visualize ROC curves and confidence intervals (CI)."
},
{
"code": null,
"e": 9665,
"s": 5397,
"text": "def bootstrap_results(y_truth, y_pred,num_bootstraps = 1000): n_bootstraps = num_bootstraps rng_seed = 42 # control reproducibility y_pred=y_pred y_true=y_truth rng = np.random.RandomState(rng_seed) tprs=[] fprs=[] aucs=[] threshs=[] base_thresh = np.linspace(0, 1, 101) for i in range(n_bootstraps): # bootstrap by sampling with replacement on the prediction indices indices = rng.randint(0, len(y_pred), len(y_pred)) if len(np.unique(y_true[indices])) < 2: # We need at least one positive and one negative sample for ROC AUC continue fpr, tpr, thresh = metrics.roc_curve(y_true[indices],y_pred[indices]) thresh=thresh[1:] thresh=np.append(thresh,[0.0]) thresh=thresh[::-1] fpr = np.interp(base_thresh, thresh, fpr[::-1]) tpr = np.interp(base_thresh, thresh, tpr[::-1]) tprs.append(tpr) fprs.append(fpr) threshs.append(thresh) tprs = np.array(tprs) mean_tprs = tprs.mean(axis=0) fprs = np.array(fprs) mean_fprs = fprs.mean(axis=0) return base_thresh, mean_tprs, mean_fprsdef get_auc_ci(y_truth, y_pred,num_bootstraps = 1000): n_bootstraps = num_bootstraps rng_seed = 42 # control reproducibility bootstrapped_scores = [] y_pred=y_pred y_true=y_truth rng = np.random.RandomState(rng_seed) tprs=[] aucs=[] base_fpr = np.linspace(0, 1, 101) for i in range(n_bootstraps): # bootstrap by sampling with replacement on the prediction indices indices = rng.randint(0, len(y_pred), len(y_pred)) if len(np.unique(y_true[indices])) < 2: # We need at least one positive and one negative sample for ROC AUC continue score = roc_auc_score(y_true[indices], y_pred[indices]) bootstrapped_scores.append(score) fpr, tpr, _ = metrics.roc_curve(y_true[indices],y_pred[indices]) roc_auc = metrics.auc(fpr, tpr) aucs.append(roc_auc) tpr = np.interp(base_fpr, fpr, tpr) tpr[0] = 0.0 tprs.append(tpr) tprs = np.array(tprs) mean_tprs = tprs.mean(axis=0) std = tprs.std(axis=0) mean_auc = metrics.auc(base_fpr, mean_tprs) std_auc = np.std(aucs) tprs_upper = np.minimum(mean_tprs + std*2, 1) tprs_lower = mean_tprs - std*2 return base_fpr, mean_tprs, tprs_lower, tprs_upper, mean_auc, std_aucdef plot_auc(truth, reference_model, new_model,n_bootstraps=1000, save=False): y_truth = truth ref_model = reference_model new_model = new_model ref_fpr, ref_tpr, ref_thresholds = metrics.roc_curve(y_truth, ref_model) new_fpr, new_tpr, new_thresholds = metrics.roc_curve(y_truth, new_model) ref_auc, new_auc = metrics.auc(ref_fpr, ref_tpr), metrics.auc(new_fpr, new_tpr) print('ref auc =',ref_auc, '\\newn auc = ', new_auc) base_fpr_ref, mean_tprs_ref, tprs_lower_ref, tprs_upper_ref, mean_auc_ref, std_auc_ref=get_auc_ci(y_truth, ref_model,n_bootstraps) base_fpr_new, mean_tprs_new, tprs_lower_new, tprs_upper_new, mean_auc_new, std_auc_new=get_auc_ci(y_truth, new_model,n_bootstraps) plt.figure(figsize=(8, 8)) lw = 2 plt.plot(ref_fpr, ref_tpr, color='blue', lw=lw, label='Reference raw ROC (AUC = %0.2f)' % ref_auc, linestyle='--') plt.plot(base_fpr_ref, mean_tprs_ref, 'b', alpha = 0.8, label=r'Reference mean ROC (AUC=%0.2f, CI=%0.2f-%0.2f)' % (mean_auc_ref, (mean_auc_ref-2*std_auc_ref),(mean_auc_ref+2*std_auc_ref)),) plt.fill_between(base_fpr_ref, tprs_lower_ref, tprs_upper_ref, color = 'b', alpha = 0.2) plt.plot(new_fpr, new_tpr, color='darkorange', lw=lw, label='New raw ROC (AUC = %0.2f)' % new_auc, linestyle='--') plt.plot(base_fpr_new, mean_tprs_new, 'darkorange', alpha = 0.8, label=r'New mean ROC (AUC=%0.2f, CI=%0.2f-%0.2f)' % (mean_auc_new,(mean_auc_new-2*std_auc_new),(mean_auc_new+2*std_auc_new)),) plt.fill_between(base_fpr_new, tprs_lower_new, tprs_upper_new, color = 'darkorange', alpha = 0.2) plt.plot([0, 1], [0, 1], color='gray', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.0]) plt.xlabel('1 - Specificity', fontsize=18) plt.ylabel('Sensitivity', fontsize=18) plt.legend(loc=\"lower right\", fontsize=13) plt.gca().set_aspect('equal', adjustable='box')"
},
{
"code": null,
"e": 9709,
"s": 9665,
"text": "We run the following to generate AUC plots."
},
{
"code": null,
"e": 9788,
"s": 9709,
"text": "plot_auc(y_test.values,test_ref_pred[:,1],test_new_pred[:,1],n_bootstraps=100)"
},
{
"code": null,
"e": 9866,
"s": 9788,
"text": "Figure 1: AUC curves with confidence intervals calculated using bootstrapping"
},
{
"code": null,
"e": 10366,
"s": 9866,
"text": "Mean curves and the 95% confidence interval in Figure 1. were calculated via 100 rounds of bootstrapping, see code above. The reference (blue curve) and new model (orange curve) produce similar AUC at 0.99 and 0.99, respectively. The confidence interval is slightly narrower for the new model. Overall, it is difficult to draw any meaningful conclusion from the AUC curves alone and it would appear that the new model with additional features did little to nothing to improve malignancy predictions."
},
{
"code": null,
"e": 10867,
"s": 10366,
"text": "Our example in Figure 1. demonstrates how using only AUC can be limiting and suggest that analysis needs to go beyond simile AUC comparision. We present two additional metrics which are commonly used to asses the impact of new features or biomarkers on a model. These metrics include the net reclassification index (NRI) and the integrated discrimination improvement (IDI) [3]. These two metrics will help in understanding the actual differences in the two models that may not be obvious in Figure 1."
},
{
"code": null,
"e": 11350,
"s": 10867,
"text": "The NRI is derived by summing the number of NRI events and NRI nonevents. In our example, events are synonymous to patients with cancer or maligancies and NRI nonevents are synonymous to patient who do have benign findings. The NRI events is the net proportion of patients with events reassigned to a higher risk category and the NRI nonevents is the number of patients without events reassigned to a lower risk category [4]. We compute the NRI using the following Python functions."
},
{
"code": null,
"e": 12576,
"s": 11350,
"text": "def check_cat(prob,thresholds): cat=0 for i,v in enumerate(thresholds): if prob>v: cat=i return catdef make_cat_matrix(ref, new, indices, thresholds): num_cats=len(thresholds) mat=np.zeros((num_cats,num_cats)) for i in indices: row,col=check_cat(ref[i],thresholds),check_cat(new[i],thresholds) mat[row,col]+=1 return matdef nri(y_truth,y_ref, y_new,risk_thresholds): event_index = np.where(y_truth==1)[0] nonevent_index = np.where(y_truth==0)[0] event_mat=make_cat_matrix(y_ref,y_new,event_index,risk_thresholds) nonevent_mat=make_cat_matrix(y_ref,y_new,nonevent_index,risk_thresholds) events_up, events_down = event_mat[0,1:].sum()+event_mat[1,2:].sum()+event_mat[2,3:].sum(),event_mat[1,:1].sum()+event_mat[2,:2].sum()+event_mat[3,:3].sum() nonevents_up, nonevents_down = nonevent_mat[0,1:].sum()+nonevent_mat[1,2:].sum()+nonevent_mat[2,3:].sum(),nonevent_mat[1,:1].sum()+nonevent_mat[2,:2].sum()+nonevent_mat[3,:3].sum() nri_events = (events_up/len(event_index))-(events_down/len(event_index)) nri_nonevents = (nonevents_down/len(nonevent_index))-(nonevents_up/len(nonevent_index)) return nri_events, nri_nonevents, nri_events + nri_nonevents"
},
{
"code": null,
"e": 12704,
"s": 12576,
"text": "We input both the reference and new models predictions into the NRI function to calculate the events, nonevents, and total NRI."
},
{
"code": null,
"e": 12788,
"s": 12704,
"text": "print(nri(y_test.values,test_ref_pred[:,1],test_new_pred[:,1],[0.02,0.1,0.5,0.95]))"
},
{
"code": null,
"e": 12823,
"s": 12788,
"text": "The output from the code above is:"
},
{
"code": null,
"e": 12869,
"s": 12823,
"text": "0.1642857142857143, 0.125, 0.2892857142857143"
},
{
"code": null,
"e": 13519,
"s": 12869,
"text": "It is tempting to state that “the new model reclassified 29% of the patients when compared to the reference model” however, this would not be an accurate statement nor a proper interpretation of NRI. Since the NRI is the sum of the proportion of events and not events it is possible to have an NRI of 2 or 200%. Stating that the new model reclassified 200% more individuals is not possible because it implies that there are suddenly twice as many patients.A more correct interpretation would be to state that the new model correctly classified 16% more cancer cases and 13% more benigns when compared to the reference, totaling a overall NRI of 29%."
},
{
"code": null,
"e": 14067,
"s": 13519,
"text": "The NRI show us that adding more features to the new model reclassified both malignant and non-malignant patients. This information could not be concluded from AUC alone and may have incorrectly led people to think the models were the same. In a clinical setting, the new model would have found more cancers which could potentially save more lives. Also, the new model would have correctly identified more benigns which would translate to less stress for an individual and potentially sparing them from having and invasive procedure like a biopsy."
},
{
"code": null,
"e": 14444,
"s": 14067,
"text": "Category free or cfNRI is a newer metric and tracks overall movement of event and nonevents, irrespective of class. For our breast cancer example, the American College of Radiology (ACR) has distinct BI-RADS classes and therefore we do not find the need to calculate the cfNRI. We provide coded functions to calculate cfNRIs below in the instance that it may suit you problem."
},
{
"code": null,
"e": 15335,
"s": 14444,
"text": "def track_movement(ref,new, indices): up, down = 0,0 for i in indices: ref_val, new_val = ref[i],new[i] if ref_val<new_val: up+=1 elif ref_val>new_val: down+=1 return up, downdef category_free_nri(y_truth,y_ref, y_new): event_index = np.where(y_truth==1)[0] nonevent_index = np.where(y_truth==0)[0] events_up, events_down = track_movement(y_ref, y_new,event_index) nonevents_up, nonevents_down = track_movement(y_ref, y_new,nonevent_index) nri_events = (events_up/len(event_index))-(events_down/len(event_index)) nri_nonevents = (nonevents_down/len(nonevent_index))-(nonevents_up/len(nonevent_index)) #print(events_up, events_down, len(event_index), nonevents_up, nonevents_down, len(nonevent_index), nri_events, nri_nonevents, nri_events+nri_nonevents) return nri_events, nri_nonevents, nri_events + nri_nonevents"
},
{
"code": null,
"e": 15711,
"s": 15335,
"text": "The IDI is a measure in the change of the discrimination slopes and shows the impact of new biomarkers on a binary predictive model. The IDI is the sum of the integrated sensitivity (IS) and integrated specificity (IP) and like NRI, it separates out events and nonevents or in this case cancers and benigns. We use the following code to calculate and plot the IDI curves [5]."
},
{
"code": null,
"e": 20473,
"s": 15711,
"text": "def area_between_curves(y1,y2): diff = y1 - y2 # calculate difference posPart = np.maximum(diff, 0) negPart = -np.minimum(diff, 0) posArea = np.trapz(posPart) negArea = np.trapz(negPart) return posArea,negArea,posArea-negAreadef plot_idi(y_truth, ref_model, new_model, save=False): ref_fpr, ref_tpr, ref_thresholds = metrics.roc_curve(y_truth, ref_model) new_fpr, new_tpr, new_thresholds = metrics.roc_curve(y_truth, new_model) base, mean_tprs, mean_fprs=bootstrap_results( y_truth, new_model,100) base2, mean_tprs2, mean_fprs2=bootstrap_results( y_truth, ref_model,100) is_pos,is_neg, idi_event=area_between_curves(mean_tprs,mean_tprs2) ip_pos,ip_neg, idi_nonevent=area_between_curves(mean_fprs2,mean_fprs) print('IS positive', round(is_pos,2),'IS negative',round(is_neg,2),'IDI events',round(idi_event,2)) print('IP positive', round(ip_pos,2),'IP negative',round(ip_neg,2),'IDI nonevents',round(idi_nonevent,2)) print('IDI =',round(idi_event+idi_nonevent,2)) plt.figure(figsize=(10, 10)) ax=plt.axes() lw = 2 plt.plot(base, mean_tprs, 'black', alpha = 0.5, label='Events New (New)' ) plt.plot(base, mean_fprs, 'red', alpha = 0.5, label='Nonevents New (New)') plt.plot(base2, mean_tprs2, 'black', alpha = 0.7, linestyle='--',label='Events Reference (Ref)' ) plt.plot(base2, mean_fprs2, 'red', alpha = 0.7, linestyle='--', label='Nonevents Reference (Ref)') plt.fill_between(base, mean_tprs,mean_tprs2, color='black',alpha = 0.1, label='Integrated Sensitivity (area = %0.2f)'%idi_event) plt.fill_between(base, mean_fprs,mean_fprs2, color='red', alpha = 0.1, label='Integrated Specificity (area = %0.2f)'%idi_nonevent)#''' #TODO: comment out if not for breast birads ### BIRADS Thresholds ### plt.axvline(x=0.02,color='darkorange',linestyle='--',alpha=.5,label='BI-RADS 3/4a Border (2%)') plt.axvline(x=0.10,color='green',linestyle='--',alpha=.5,label='BI-RADS 4a/4b Border (10%)') plt.axvline(x=0.5,color='blue',linestyle='--',alpha=.5,label='BI-RADS 4b/4c Border (50%)') plt.axvline(x=0.95,color='purple',linestyle='--',alpha=.5,label='BI-RADS 4c/5 Border (95%)') def nri_annotation(plt, threshold): x_pos = base[threshold] x_offset=0.02 x_offset2=x_offset text_y_offset=0.01 text_y_offset2=text_y_offset if threshold==2: text_y_offset=0.04 text_y_offset2=0.04 x_offset2=0.05 print(x_pos+x_offset, (np.mean([mean_tprs2[threshold], mean_tprs[threshold]])+text_y_offset), x_pos, (np.mean([mean_tprs2[threshold], mean_tprs[threshold]]))) text_y_events=np.mean([mean_tprs2[threshold], mean_tprs[threshold]])+text_y_offset text_y_nonevents=np.mean([mean_fprs[threshold], mean_fprs2[threshold]])+text_y_offset2 plt.annotate('', xy=(x_pos+0.02, mean_tprs2[threshold+1]), xycoords='data', xytext=(x_pos+0.02, mean_tprs[threshold]), textcoords='data', arrowprops={'arrowstyle': '|-|'}) plt.annotate('NRI$_{events}$ = %0.2f'%(mean_tprs[threshold]-mean_tprs2[threshold]), xy=(x_pos+x_offset, text_y_events), xycoords='data', xytext=(x_pos+x_offset, text_y_events), textcoords='offset points', fontsize=15) plt.annotate('', xy=(x_pos+0.02, mean_fprs[threshold]), xycoords='data', xytext=(x_pos+0.02, mean_fprs2[threshold]), textcoords='data', arrowprops=dict(arrowstyle= '|-|',color='r')) plt.annotate('NRI$_{nonevents}$ = %0.2f'%(mean_fprs2[threshold]-mean_fprs[threshold]), xy=(x_pos+x_offset2, text_y_nonevents), xycoords='data', xytext=(x_pos+x_offset2, text_y_nonevents), textcoords='offset points', fontsize=15) print('Threshold =',round(x_pos,2),'NRI events =',round(mean_tprs[threshold]-mean_tprs2[threshold],4), 'NRI nonevents =',round(mean_fprs2[threshold]-mean_fprs[threshold],4),'Total =', round((mean_tprs[threshold]-mean_tprs2[threshold])+(mean_fprs2[threshold]-mean_fprs[threshold]),4)) nri_annotation(plt,2) nri_annotation(plt,10) nri_annotation(plt,50) nri_annotation(plt,95) #''' plt.xlim([0.0, 1.10]) plt.ylim([0.0, 1.10]) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) plt.xlabel('Calculated Risk', fontsize=18) plt.ylabel('Sensitivity (black), 1 - Specificity (red)', fontsize=18) plt.legend(loc=\"upper right\", fontsize=11) plt.legend(loc=0, fontsize=11, bbox_to_anchor=(0,0,1.2,.9)) plt.gca().set_aspect('equal', adjustable='box') #if save: # plt.savefig('idi_curve.png',dpi=300, bbox_inches='tight') look=95 plt.show()"
},
{
"code": null,
"e": 20537,
"s": 20473,
"text": "We run the following command to generate the graph in Figure 2."
},
{
"code": null,
"e": 20599,
"s": 20537,
"text": "plot_idi(y_test.values,test_ref_pred[:,1],test_new_pred[:,1])"
},
{
"code": null,
"e": 20607,
"s": 20599,
"text": "Output:"
},
{
"code": null,
"e": 21029,
"s": 20607,
"text": "IS positive 3.58 IS negative 0.16 IDI events 3.42IP positive 4.61 IP negative 0.04 IDI nonevents 4.57IDI = 7.980.04 1.04 0.02 1.0Threshold = 0.02 NRI events = 0.0 NRI nonevents = 0.2762 Total = 0.2762Threshold = 0.1 NRI events = -0.008 NRI nonevents = 0.1002 Total = 0.0922Threshold = 0.5 NRI events = 0.0215 NRI nonevents = 0.0317 Total = 0.0532Threshold = 0.95 NRI events = 0.1389 NRI nonevents = -0.0136 Total = 0.1252"
},
{
"code": null,
"e": 21101,
"s": 21029,
"text": "Figure 2: IDI curve with calculated NRI at each class or BI-RADS border"
},
{
"code": null,
"e": 22114,
"s": 21101,
"text": "The dashed and solid curves represent the reference and new model respectively. In the ideal case, the solid black line would be moved to the upper right indicating the most improvement to sensitivity and the red line would be lowered to the bottom right indicating the most improved specificity. The area between the black and red curves equate to the IS and IP and the total sum of the black and red area equates to the IDI. IDI provides more information that the AUC curves especially with respects to the orange dashed vertical line or the BI-RADS 3/4a border. At this border, the IP or red area is large which indicates that the new model was able to better predict benigns. This border is particularly interesting because it is recommended that all patients with BI-RADS 4 or greater receive biopsies [6]. The large area at the 3/4a border shows that adding new features to the new model increase specificity and potentially prevented 28% more people (NRI nonevents=0.28) from being unnecessarily biopsied."
},
{
"code": null,
"e": 22660,
"s": 22114,
"text": "AUC is a good metric but does not provide all the information needed for a comprehensive analysis of the impact of new biomarkers and models. The NRI and IDI should be used to complement AUC findings and interpretations. As a data scientist and cancer researcher who uses Python, it was difficult to find functions and code snippets that computed and plotted NRI and IDI as presented here. This was my motivation for posting this and I hope that my code can help other in their research, discoveries, and pursuit of better health care solutions."
},
{
"code": null,
"e": 22841,
"s": 22660,
"text": "[1] Dua, D. and Graff, C, (2019), Irvine, CA: University of California, School of Information and Computer Science, UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]."
},
{
"code": null,
"e": 23066,
"s": 22841,
"text": "[2] Understanding mammogram reports: Mammogram results. (n.d.). Retrieved May 06, 2021, from https://www.cancer.org/cancer/breast-cancer/screening-tests-and-early-detection/mammograms/understanding-your-mammogram-report.html"
},
{
"code": null,
"e": 23313,
"s": 23066,
"text": "[3] Pencina, M. J., D’Agostino Sr, R. B., D’Agostino Jr, R. B., & Vasan, R. S., Evaluating the added predictive ability of a new marker: from area under the ROC curve to reclassification and beyond, (2008), Statistics in medicine, 27(2), 157–172."
},
{
"code": null,
"e": 23523,
"s": 23313,
"text": "[4] Pencina, M. J., D’Agostino Sr, R. B., & Steyerberg, E. W., Extensions of net reclassification improvement calculations to measure usefulness of new biomarkers, (2011), Statistics in medicine, 30(1), 11–21."
},
{
"code": null,
"e": 23714,
"s": 23523,
"text": "[5] Pickering, J. W., & Endre, Z. H., New metrics for assessing diagnostic potential of candidate biomarkers, (2012), Clinical Journal of the American Society of Nephrology, 7(8), 1355–1364."
},
{
"code": null,
"e": 23952,
"s": 23714,
"text": "[6] Leong, L., Malkov, S., Drukker, K., Niell, B., Sadowski, P., Wolfgruber, T., ... & Shepherd, J., Dual-energy three compartment breast imaging (3CB) for novel compositional biomarkers to improve detection of malignant lesions, (2021)."
}
] |
Using Classes for Machine Learning | by Sadrach Pierre, Ph.D. | Towards Data Science | Classes provide a useful way of combining data and functionality. The modularity of classes enables effective troubleshooting, code reuse, and problem-solving. For example, if your code breaks, you will be able to point to a specific class or class method without having to sift through much else code. Because of these factors, model development naturally lends itself to object-oriented programming practices.
In this post, we will discuss how we can use object-oriented programming for reading data, splitting data for training, fitting models, and making predictions. We will be using weather data which can be found here.
Before we get started let’s import pandas:
import pandas as pd
Now, let’s define a class called Model:
class Model: def __init__(self, datafile = "weatherHistory.csv"): self.df = pd.read_csv(datafile)
The class will have an ‘__init__’ function, also called a constructor, which allows us to initialize data upon the creation of a new instance of that class. We can define a new variable, ‘model_instance’, as an object (an instance of the Model class):
if __name__ == '__main__': model_instance = Model()
We should be able to access the data frame through the object, ‘model_instance.’ Let’s call the data frame and print the first five rows of the data:
if __name__ == '__main__': model_instance= Model() print(model_instance.df.head())
Looks good.
The next thing we can do is define a linear regression object in the initialization function. This is not to be confused with ‘model_instance’, which is an instance of our custom class ‘Model’:
class Model: def __init__(self, datafile = "weatherHistory.csv"): self.df = pd.read_csv(datafile) self.linear_reg = LinearRegression()
Again, it is worth noting that LinearRegression is a separate class from our custom ‘Model’ class and that in the line of code:
self.linear_reg = LinearRegression()
we are defining an instance of the LinearRegression class.
Now, let’s make sure we can access our linear regression object:
if __name__ == '__main__': model_instance = Model() print(model_instance.linear_reg)
The next thing we can do is define a method that lets us split our data for training and testing. The function will take a ‘test_size’ parameter which will let us specify the size of training and testing.
First, let’s import the ‘train_test_split’ method from ‘sklearn’ and let’s also import ‘NumPy’ :
from sklearn.model_selection import train_test_splitimport numpy as np
We will build a linear regression model which we will use to predict temperature. For simplicity, let’s use ‘Humidity’ and ‘Pressure (millibars)’ as our input and ‘Temperature’ as our output. We define our split method as follows:
def split(self, test_size): X = np.array(self.df[['Humidity', 'Pressure (millibars)']]) y = np.array(self.df['Temperature (C)']) self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, test_size = test_size, random_state = 42)
Next, let’s print ‘X_train’ and ‘y_train’ for inspection:
if __name__ == '__main__': model_instance = Model() model_instance.split(0.2) print(model_instance.X_train) print(model_instance.y_train)
We will now define a ‘fit’ function for our linear regression model:
def fit(self): self.model = self.linear_reg.fit(self.X_train, self.y_train)
We will also define a ‘predict’ function:
def predict(self): result = self.linear_reg.predict(self.X_test) return result
Now, let’s print our test predictions where the test size is 20% of the data:
if __name__ == '__main__': model_instance = Model() model_instance.split(0.2) model_instance.fit() print(model_instance.predict())
We can also print model performance:
if __name__ == '__main__': model_instance = Model() model_instance.split(0.2) model_instance.fit() print("Accuracy: ", model_instance.model.score(model_instance.X_test, model_instance.y_test))
We can also pass an ‘input_value’ parameter to our predict method, which will allow us to make out of sample predictions. If ‘None’ is passed then predictions will be made on the test input. Otherwise, predictions will be made on the ‘input_value’:
def predict(self, input_value): if input_value == None: result = self.linear_reg.predict(self.X_test) else: result = self.linear_reg.predict(np.array([input_value])) return result
Let’s call predict with some out of sample test input:
if __name__ == '__main__': model_instance = Model() model_instance.split(0.2) model_instance.fit() print(model_instance.predict([.9, 1000]))
We can also define a random forest regression model object as a Model field and run our script:
class Model: def __init__(self, datafile = "weatherHistory.csv"): self.df = pd.read_csv(datafile) self.linear_reg = LinearRegression() self.random_forest = RandomForestRegressor() def split(self, test_size): X = np.array(self.df[['Humidity', 'Pressure (millibars)']]) y = np.array(self.df['Temperature (C)']) self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, test_size = test_size, random_state = 42) def fit(self): self.model = self.random_forest.fit(self.X_train, self.y_train) def predict(self, input_value): if input_value == None: result = self.random_forest.fit(self.X_test) else: result = self.random_forest.fit(np.array([input_values])) return resultif __name__ == '__main__': model_instance = Model() model_instance.split(0.2) model_instance.fit() print("Accuracy: ", model_instance.model.score(model_instance.X_test, model_instance.y_test))
You can easily modify the code to build support vector regression models, ‘xgboost’ models, and much more. We can further generalize our class by passing a parameter to the constructor that, when specified, chooses from a list of possible models.
The logic could look something like:
class Model: def __init__(self, datafile = "weatherHistory.csv", model_type = None): self.df = pd.read_csv(datafile) if model_type == 'rf': self.user_defined_model = RandomForestRegressor() else: self.user_defined_model = LinearRegression()
And your ‘fit’ and ‘predict’ methods are modified:
def fit(self): self.model = self.user_defined_model.fit(self.X_train, self.y_train) def predict(self, input_value): if input_value == None: result = self.user_defined_model.fit(self.X_test) else: result = self.user_defined_model.fit(np.array([input_values])) return result
And we execute as follows:
if __name__ == '__main__': model_instance = Model(model_type = 'rf') model_instance.split(0.2) model_instance.fit() print("Accuracy: ", model_instance.model.score(model_instance.X_test, model_instance.y_test))
And if we pass ‘None’ we get:
if __name__ == '__main__': model_instance = Model(model_type = None) model_instance.split(0.2) model_instance.fit() print("Accuracy: ", model_instance.model.score(model_instance.X_test, model_instance.y_test))
I’ll stop here but I encourage you to add additional model objects. Some interesting examples you can try are support vector machines, ‘xgboost’ regression, and ‘lightgbm’ regression models. It may also be useful to add helper methods that generate summary statistics like mean and standard deviation for any of the numerical columns. You can also define methods that help you select features by calculating statistics like correlation.
To recap, in this post I discussed how to build machine learning models within the object-orientated programming framework. This framework is useful for troubleshooting, problem-solving, field collection, method collection, and much more. I hope you find a use for OOP in your own data science projects. The code from this post is available on GitHub. Thank you for reading and happy machine learning! | [
{
"code": null,
"e": 584,
"s": 172,
"text": "Classes provide a useful way of combining data and functionality. The modularity of classes enables effective troubleshooting, code reuse, and problem-solving. For example, if your code breaks, you will be able to point to a specific class or class method without having to sift through much else code. Because of these factors, model development naturally lends itself to object-oriented programming practices."
},
{
"code": null,
"e": 799,
"s": 584,
"text": "In this post, we will discuss how we can use object-oriented programming for reading data, splitting data for training, fitting models, and making predictions. We will be using weather data which can be found here."
},
{
"code": null,
"e": 842,
"s": 799,
"text": "Before we get started let’s import pandas:"
},
{
"code": null,
"e": 863,
"s": 842,
"text": "import pandas as pd "
},
{
"code": null,
"e": 903,
"s": 863,
"text": "Now, let’s define a class called Model:"
},
{
"code": null,
"e": 1011,
"s": 903,
"text": "class Model: def __init__(self, datafile = \"weatherHistory.csv\"): self.df = pd.read_csv(datafile)"
},
{
"code": null,
"e": 1263,
"s": 1011,
"text": "The class will have an ‘__init__’ function, also called a constructor, which allows us to initialize data upon the creation of a new instance of that class. We can define a new variable, ‘model_instance’, as an object (an instance of the Model class):"
},
{
"code": null,
"e": 1318,
"s": 1263,
"text": "if __name__ == '__main__': model_instance = Model()"
},
{
"code": null,
"e": 1468,
"s": 1318,
"text": "We should be able to access the data frame through the object, ‘model_instance.’ Let’s call the data frame and print the first five rows of the data:"
},
{
"code": null,
"e": 1557,
"s": 1468,
"text": "if __name__ == '__main__': model_instance= Model() print(model_instance.df.head())"
},
{
"code": null,
"e": 1569,
"s": 1557,
"text": "Looks good."
},
{
"code": null,
"e": 1763,
"s": 1569,
"text": "The next thing we can do is define a linear regression object in the initialization function. This is not to be confused with ‘model_instance’, which is an instance of our custom class ‘Model’:"
},
{
"code": null,
"e": 1915,
"s": 1763,
"text": "class Model: def __init__(self, datafile = \"weatherHistory.csv\"): self.df = pd.read_csv(datafile) self.linear_reg = LinearRegression()"
},
{
"code": null,
"e": 2043,
"s": 1915,
"text": "Again, it is worth noting that LinearRegression is a separate class from our custom ‘Model’ class and that in the line of code:"
},
{
"code": null,
"e": 2080,
"s": 2043,
"text": "self.linear_reg = LinearRegression()"
},
{
"code": null,
"e": 2139,
"s": 2080,
"text": "we are defining an instance of the LinearRegression class."
},
{
"code": null,
"e": 2204,
"s": 2139,
"text": "Now, let’s make sure we can access our linear regression object:"
},
{
"code": null,
"e": 2295,
"s": 2204,
"text": "if __name__ == '__main__': model_instance = Model() print(model_instance.linear_reg)"
},
{
"code": null,
"e": 2500,
"s": 2295,
"text": "The next thing we can do is define a method that lets us split our data for training and testing. The function will take a ‘test_size’ parameter which will let us specify the size of training and testing."
},
{
"code": null,
"e": 2597,
"s": 2500,
"text": "First, let’s import the ‘train_test_split’ method from ‘sklearn’ and let’s also import ‘NumPy’ :"
},
{
"code": null,
"e": 2668,
"s": 2597,
"text": "from sklearn.model_selection import train_test_splitimport numpy as np"
},
{
"code": null,
"e": 2899,
"s": 2668,
"text": "We will build a linear regression model which we will use to predict temperature. For simplicity, let’s use ‘Humidity’ and ‘Pressure (millibars)’ as our input and ‘Temperature’ as our output. We define our split method as follows:"
},
{
"code": null,
"e": 3169,
"s": 2899,
"text": "def split(self, test_size): X = np.array(self.df[['Humidity', 'Pressure (millibars)']]) y = np.array(self.df['Temperature (C)']) self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, test_size = test_size, random_state = 42)"
},
{
"code": null,
"e": 3227,
"s": 3169,
"text": "Next, let’s print ‘X_train’ and ‘y_train’ for inspection:"
},
{
"code": null,
"e": 3377,
"s": 3227,
"text": "if __name__ == '__main__': model_instance = Model() model_instance.split(0.2) print(model_instance.X_train) print(model_instance.y_train)"
},
{
"code": null,
"e": 3446,
"s": 3377,
"text": "We will now define a ‘fit’ function for our linear regression model:"
},
{
"code": null,
"e": 3529,
"s": 3446,
"text": "def fit(self): self.model = self.linear_reg.fit(self.X_train, self.y_train)"
},
{
"code": null,
"e": 3571,
"s": 3529,
"text": "We will also define a ‘predict’ function:"
},
{
"code": null,
"e": 3664,
"s": 3571,
"text": "def predict(self): result = self.linear_reg.predict(self.X_test) return result"
},
{
"code": null,
"e": 3742,
"s": 3664,
"text": "Now, let’s print our test predictions where the test size is 20% of the data:"
},
{
"code": null,
"e": 3896,
"s": 3742,
"text": "if __name__ == '__main__': model_instance = Model() model_instance.split(0.2) model_instance.fit() print(model_instance.predict())"
},
{
"code": null,
"e": 3933,
"s": 3896,
"text": "We can also print model performance:"
},
{
"code": null,
"e": 4146,
"s": 3933,
"text": "if __name__ == '__main__': model_instance = Model() model_instance.split(0.2) model_instance.fit() print(\"Accuracy: \", model_instance.model.score(model_instance.X_test, model_instance.y_test))"
},
{
"code": null,
"e": 4395,
"s": 4146,
"text": "We can also pass an ‘input_value’ parameter to our predict method, which will allow us to make out of sample predictions. If ‘None’ is passed then predictions will be made on the test input. Otherwise, predictions will be made on the ‘input_value’:"
},
{
"code": null,
"e": 4599,
"s": 4395,
"text": "def predict(self, input_value): if input_value == None: result = self.linear_reg.predict(self.X_test) else: result = self.linear_reg.predict(np.array([input_value])) return result"
},
{
"code": null,
"e": 4654,
"s": 4599,
"text": "Let’s call predict with some out of sample test input:"
},
{
"code": null,
"e": 4811,
"s": 4654,
"text": "if __name__ == '__main__': model_instance = Model() model_instance.split(0.2) model_instance.fit() print(model_instance.predict([.9, 1000]))"
},
{
"code": null,
"e": 4907,
"s": 4811,
"text": "We can also define a random forest regression model object as a Model field and run our script:"
},
{
"code": null,
"e": 5915,
"s": 4907,
"text": "class Model: def __init__(self, datafile = \"weatherHistory.csv\"): self.df = pd.read_csv(datafile) self.linear_reg = LinearRegression() self.random_forest = RandomForestRegressor() def split(self, test_size): X = np.array(self.df[['Humidity', 'Pressure (millibars)']]) y = np.array(self.df['Temperature (C)']) self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, test_size = test_size, random_state = 42) def fit(self): self.model = self.random_forest.fit(self.X_train, self.y_train) def predict(self, input_value): if input_value == None: result = self.random_forest.fit(self.X_test) else: result = self.random_forest.fit(np.array([input_values])) return resultif __name__ == '__main__': model_instance = Model() model_instance.split(0.2) model_instance.fit() print(\"Accuracy: \", model_instance.model.score(model_instance.X_test, model_instance.y_test))"
},
{
"code": null,
"e": 6162,
"s": 5915,
"text": "You can easily modify the code to build support vector regression models, ‘xgboost’ models, and much more. We can further generalize our class by passing a parameter to the constructor that, when specified, chooses from a list of possible models."
},
{
"code": null,
"e": 6199,
"s": 6162,
"text": "The logic could look something like:"
},
{
"code": null,
"e": 6484,
"s": 6199,
"text": "class Model: def __init__(self, datafile = \"weatherHistory.csv\", model_type = None): self.df = pd.read_csv(datafile) if model_type == 'rf': self.user_defined_model = RandomForestRegressor() else: self.user_defined_model = LinearRegression()"
},
{
"code": null,
"e": 6535,
"s": 6484,
"text": "And your ‘fit’ and ‘predict’ methods are modified:"
},
{
"code": null,
"e": 6874,
"s": 6535,
"text": " def fit(self): self.model = self.user_defined_model.fit(self.X_train, self.y_train) def predict(self, input_value): if input_value == None: result = self.user_defined_model.fit(self.X_test) else: result = self.user_defined_model.fit(np.array([input_values])) return result"
},
{
"code": null,
"e": 6901,
"s": 6874,
"text": "And we execute as follows:"
},
{
"code": null,
"e": 7127,
"s": 6901,
"text": "if __name__ == '__main__': model_instance = Model(model_type = 'rf') model_instance.split(0.2) model_instance.fit() print(\"Accuracy: \", model_instance.model.score(model_instance.X_test, model_instance.y_test))"
},
{
"code": null,
"e": 7157,
"s": 7127,
"text": "And if we pass ‘None’ we get:"
},
{
"code": null,
"e": 7383,
"s": 7157,
"text": "if __name__ == '__main__': model_instance = Model(model_type = None) model_instance.split(0.2) model_instance.fit() print(\"Accuracy: \", model_instance.model.score(model_instance.X_test, model_instance.y_test))"
},
{
"code": null,
"e": 7820,
"s": 7383,
"text": "I’ll stop here but I encourage you to add additional model objects. Some interesting examples you can try are support vector machines, ‘xgboost’ regression, and ‘lightgbm’ regression models. It may also be useful to add helper methods that generate summary statistics like mean and standard deviation for any of the numerical columns. You can also define methods that help you select features by calculating statistics like correlation."
}
] |
Implement Logistic Regression with L2 Regularization from scratch in Python | by Tulrose Deori | Towards Data Science | Table of contents:
IntroductionPre-requisitesMathematics behind the scenesRegularizationCodeResults and DemoFuture Works and ConclusionsReferences
Introduction
Pre-requisites
Mathematics behind the scenes
Regularization
Code
Results and Demo
Future Works and Conclusions
References
Logistic Regression is one of the most common machine learning algorithms used for classification. It a statistical model that uses a logistic function to model a binary dependent variable. In essence, it predicts the probability of an observation belonging to a certain class or label. For instance, is this a cat photo or a dog photo?
NB: Although Logistic Regression can be extended to multi-class classification, we will discuss only binary classification settings in this article.
The reader is expected to have an understanding of the following:
What is a dataset?
What is a feature?
What is multicollinearity?
What is a sigmoid function?
Assumptions: Logistic Regression makes certain key assumptions before starting its modeling process:
The labels are almost linearly separable.The observations have to be independent of each other.There is minimal or no multicollinearity among the independent variables.The independent variables are linearly related to the log odds.
The labels are almost linearly separable.
The observations have to be independent of each other.
There is minimal or no multicollinearity among the independent variables.
The independent variables are linearly related to the log odds.
Hypothesis: We want our model to predict the probability of an observation belonging to a certain class or label. As such, we want a hypothesis h that satisfies the following condition 0 <= h(x) <= 1 , where x is an observation.
We define h(x) = g(wT* x) , where g is a sigmoid function and w are the trainable parameters. As such, we have:
The cost for an observation: Now that we can predict the probability for an observation, we want the result to have the minimum error. If the class label is y, the cost (error) associated with an observation x is given by:
Cost Function: Thus, the total cost for all the m observations in a dataset is:
We can rewrite the cost function J as:
The objective of logistic regression is to find params w so that J is minimum. But, how do we do that?
Gradient Descent:
Gradient descent is an optimization algorithm used to minimize some function by iteratively moving in the direction of steepest descent as defined by the negative of the gradient.
We will update each of the params wi using the following template:
The above step will help us find a set of params wi, which will then help us to come up with h(x) to solve our binary classification task.
But there is also an undesirable outcome associated with the above gradient descent steps. In an attempt to find the best h(x), the following things happen:
CASE I: For class label = 0h(x) will try to produce results as close 0 as possibleAs such, wT.x will be as small as possible=> Wi will tend to -infinityCASE II: For class label = 1h(x) will try to produce results as close 1 as possibleAs such, wT.x will be as large as possible=> Wi will tend to +infinity
This leads to a problem called overfitting, which means, the model will not be able to generalize well, i.e. it won’t be able to correctly predict the class label for an unseen observation. So, to avoid this we need to control the growth of the params wi. But, how do we do that?
Regularization is a technique to solve the problem of overfitting in a machine learning algorithm by penalizing the cost function. It does so by using an additional penalty term in the cost function.There are two types of regularization techniques:
Lasso or L1 RegularizationRidge or L2 Regularization (we will discuss only this in this article)
Lasso or L1 Regularization
Ridge or L2 Regularization (we will discuss only this in this article)
So, how can L2 Regularization help to prevent overfitting? Let’s first look at our new cost function:
λ is called the regularization parameter. It controls the trade-off between two goals: fitting the training data well vs keeping the params small to avoid overfitting.
Hence, the gradient of J(w) becomes:
The regularization term will heavily penalize large wi. The effect will be less on smaller wi’s. As such, the growth of w is controlled. The h(x) we obtain with these controlled params w will be more generalizable.
NOTE: λ is a hyper-parameter value. We have to find it using cross-validation.
Larger value λ of will make wi shrink closer to 0, which might lead to underfitting.
λ = 0, will have no regulariztion effect.
When choosing λ, we have to take proper care of bias vs variance trade-off.
You can find more about Regularization here.
We are done with all the Mathematics. Let’s implement the code in Python.
NB: Although we defined the regularization param as λ above, we have used C = (1/λ) in our code so as to be similar with sklearn package.
Let’s fit the classifier on a dummy dataset and observe the results:
The decision boundary plot:
As we can see, our model is able to classify the observations very well. The boundary is the decision line.
Get a sandbox experience for the model here: LIVE PREVIEW.
There is scope to improve the Classifier performance by implementing other algorithms like Stochastic Average Gradient, Limited-memory BFGS, to solve the optimization problem.
We can also implement Lasso or L1 regularization.
And that’s all. Thank you for reading my blog. Please leave comments, feedback, and suggestions if you feel any.
Reach out to me through my Portfolio or find me on LinkedIn.
[1] https://www.coursera.org/learn/machine-learning
[2] https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html
[3] https://www.geeksforgeeks.org/understanding-logistic-regression
Go to top ^ | [
{
"code": null,
"e": 191,
"s": 172,
"text": "Table of contents:"
},
{
"code": null,
"e": 319,
"s": 191,
"text": "IntroductionPre-requisitesMathematics behind the scenesRegularizationCodeResults and DemoFuture Works and ConclusionsReferences"
},
{
"code": null,
"e": 332,
"s": 319,
"text": "Introduction"
},
{
"code": null,
"e": 347,
"s": 332,
"text": "Pre-requisites"
},
{
"code": null,
"e": 377,
"s": 347,
"text": "Mathematics behind the scenes"
},
{
"code": null,
"e": 392,
"s": 377,
"text": "Regularization"
},
{
"code": null,
"e": 397,
"s": 392,
"text": "Code"
},
{
"code": null,
"e": 414,
"s": 397,
"text": "Results and Demo"
},
{
"code": null,
"e": 443,
"s": 414,
"text": "Future Works and Conclusions"
},
{
"code": null,
"e": 454,
"s": 443,
"text": "References"
},
{
"code": null,
"e": 791,
"s": 454,
"text": "Logistic Regression is one of the most common machine learning algorithms used for classification. It a statistical model that uses a logistic function to model a binary dependent variable. In essence, it predicts the probability of an observation belonging to a certain class or label. For instance, is this a cat photo or a dog photo?"
},
{
"code": null,
"e": 940,
"s": 791,
"text": "NB: Although Logistic Regression can be extended to multi-class classification, we will discuss only binary classification settings in this article."
},
{
"code": null,
"e": 1006,
"s": 940,
"text": "The reader is expected to have an understanding of the following:"
},
{
"code": null,
"e": 1025,
"s": 1006,
"text": "What is a dataset?"
},
{
"code": null,
"e": 1044,
"s": 1025,
"text": "What is a feature?"
},
{
"code": null,
"e": 1071,
"s": 1044,
"text": "What is multicollinearity?"
},
{
"code": null,
"e": 1099,
"s": 1071,
"text": "What is a sigmoid function?"
},
{
"code": null,
"e": 1200,
"s": 1099,
"text": "Assumptions: Logistic Regression makes certain key assumptions before starting its modeling process:"
},
{
"code": null,
"e": 1432,
"s": 1200,
"text": "The labels are almost linearly separable.The observations have to be independent of each other.There is minimal or no multicollinearity among the independent variables.The independent variables are linearly related to the log odds."
},
{
"code": null,
"e": 1474,
"s": 1432,
"text": "The labels are almost linearly separable."
},
{
"code": null,
"e": 1529,
"s": 1474,
"text": "The observations have to be independent of each other."
},
{
"code": null,
"e": 1603,
"s": 1529,
"text": "There is minimal or no multicollinearity among the independent variables."
},
{
"code": null,
"e": 1667,
"s": 1603,
"text": "The independent variables are linearly related to the log odds."
},
{
"code": null,
"e": 1896,
"s": 1667,
"text": "Hypothesis: We want our model to predict the probability of an observation belonging to a certain class or label. As such, we want a hypothesis h that satisfies the following condition 0 <= h(x) <= 1 , where x is an observation."
},
{
"code": null,
"e": 2008,
"s": 1896,
"text": "We define h(x) = g(wT* x) , where g is a sigmoid function and w are the trainable parameters. As such, we have:"
},
{
"code": null,
"e": 2231,
"s": 2008,
"text": "The cost for an observation: Now that we can predict the probability for an observation, we want the result to have the minimum error. If the class label is y, the cost (error) associated with an observation x is given by:"
},
{
"code": null,
"e": 2311,
"s": 2231,
"text": "Cost Function: Thus, the total cost for all the m observations in a dataset is:"
},
{
"code": null,
"e": 2350,
"s": 2311,
"text": "We can rewrite the cost function J as:"
},
{
"code": null,
"e": 2453,
"s": 2350,
"text": "The objective of logistic regression is to find params w so that J is minimum. But, how do we do that?"
},
{
"code": null,
"e": 2471,
"s": 2453,
"text": "Gradient Descent:"
},
{
"code": null,
"e": 2651,
"s": 2471,
"text": "Gradient descent is an optimization algorithm used to minimize some function by iteratively moving in the direction of steepest descent as defined by the negative of the gradient."
},
{
"code": null,
"e": 2718,
"s": 2651,
"text": "We will update each of the params wi using the following template:"
},
{
"code": null,
"e": 2857,
"s": 2718,
"text": "The above step will help us find a set of params wi, which will then help us to come up with h(x) to solve our binary classification task."
},
{
"code": null,
"e": 3014,
"s": 2857,
"text": "But there is also an undesirable outcome associated with the above gradient descent steps. In an attempt to find the best h(x), the following things happen:"
},
{
"code": null,
"e": 3320,
"s": 3014,
"text": "CASE I: For class label = 0h(x) will try to produce results as close 0 as possibleAs such, wT.x will be as small as possible=> Wi will tend to -infinityCASE II: For class label = 1h(x) will try to produce results as close 1 as possibleAs such, wT.x will be as large as possible=> Wi will tend to +infinity"
},
{
"code": null,
"e": 3600,
"s": 3320,
"text": "This leads to a problem called overfitting, which means, the model will not be able to generalize well, i.e. it won’t be able to correctly predict the class label for an unseen observation. So, to avoid this we need to control the growth of the params wi. But, how do we do that?"
},
{
"code": null,
"e": 3849,
"s": 3600,
"text": "Regularization is a technique to solve the problem of overfitting in a machine learning algorithm by penalizing the cost function. It does so by using an additional penalty term in the cost function.There are two types of regularization techniques:"
},
{
"code": null,
"e": 3946,
"s": 3849,
"text": "Lasso or L1 RegularizationRidge or L2 Regularization (we will discuss only this in this article)"
},
{
"code": null,
"e": 3973,
"s": 3946,
"text": "Lasso or L1 Regularization"
},
{
"code": null,
"e": 4044,
"s": 3973,
"text": "Ridge or L2 Regularization (we will discuss only this in this article)"
},
{
"code": null,
"e": 4146,
"s": 4044,
"text": "So, how can L2 Regularization help to prevent overfitting? Let’s first look at our new cost function:"
},
{
"code": null,
"e": 4314,
"s": 4146,
"text": "λ is called the regularization parameter. It controls the trade-off between two goals: fitting the training data well vs keeping the params small to avoid overfitting."
},
{
"code": null,
"e": 4351,
"s": 4314,
"text": "Hence, the gradient of J(w) becomes:"
},
{
"code": null,
"e": 4566,
"s": 4351,
"text": "The regularization term will heavily penalize large wi. The effect will be less on smaller wi’s. As such, the growth of w is controlled. The h(x) we obtain with these controlled params w will be more generalizable."
},
{
"code": null,
"e": 4645,
"s": 4566,
"text": "NOTE: λ is a hyper-parameter value. We have to find it using cross-validation."
},
{
"code": null,
"e": 4730,
"s": 4645,
"text": "Larger value λ of will make wi shrink closer to 0, which might lead to underfitting."
},
{
"code": null,
"e": 4772,
"s": 4730,
"text": "λ = 0, will have no regulariztion effect."
},
{
"code": null,
"e": 4848,
"s": 4772,
"text": "When choosing λ, we have to take proper care of bias vs variance trade-off."
},
{
"code": null,
"e": 4893,
"s": 4848,
"text": "You can find more about Regularization here."
},
{
"code": null,
"e": 4967,
"s": 4893,
"text": "We are done with all the Mathematics. Let’s implement the code in Python."
},
{
"code": null,
"e": 5105,
"s": 4967,
"text": "NB: Although we defined the regularization param as λ above, we have used C = (1/λ) in our code so as to be similar with sklearn package."
},
{
"code": null,
"e": 5174,
"s": 5105,
"text": "Let’s fit the classifier on a dummy dataset and observe the results:"
},
{
"code": null,
"e": 5202,
"s": 5174,
"text": "The decision boundary plot:"
},
{
"code": null,
"e": 5310,
"s": 5202,
"text": "As we can see, our model is able to classify the observations very well. The boundary is the decision line."
},
{
"code": null,
"e": 5369,
"s": 5310,
"text": "Get a sandbox experience for the model here: LIVE PREVIEW."
},
{
"code": null,
"e": 5545,
"s": 5369,
"text": "There is scope to improve the Classifier performance by implementing other algorithms like Stochastic Average Gradient, Limited-memory BFGS, to solve the optimization problem."
},
{
"code": null,
"e": 5595,
"s": 5545,
"text": "We can also implement Lasso or L1 regularization."
},
{
"code": null,
"e": 5708,
"s": 5595,
"text": "And that’s all. Thank you for reading my blog. Please leave comments, feedback, and suggestions if you feel any."
},
{
"code": null,
"e": 5769,
"s": 5708,
"text": "Reach out to me through my Portfolio or find me on LinkedIn."
},
{
"code": null,
"e": 5821,
"s": 5769,
"text": "[1] https://www.coursera.org/learn/machine-learning"
},
{
"code": null,
"e": 5920,
"s": 5821,
"text": "[2] https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html"
},
{
"code": null,
"e": 5988,
"s": 5920,
"text": "[3] https://www.geeksforgeeks.org/understanding-logistic-regression"
}
] |
How to use equals () in Android textview? | This example demonstrate about How to use equals () in Android textview.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Enter name"
android:layout_height="wrap_content" />
<Button
android:id="@+id/click"
android:text="Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:textSize="25sp"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken name as Edit text, when user click on button it will take data and check that given string contains “point”.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
if (name.getText().toString().length() >= 0) {
text.setText(String.valueOf(name.getText().toString().equals("point")));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, enter the string as point and it returned true because it contained point string in given string. Now enter other string without point it gives the result as false as shown below −
Click here to download the project code | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "This example demonstrate about How to use equals () in Android textview."
},
{
"code": null,
"e": 1264,
"s": 1135,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1328,
"s": 1264,
"text": "Step − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2218,
"s": 1328,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter name\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/click\"\n android:text=\"Click\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/textview\"\n android:layout_width=\"wrap_content\"\n android:textSize=\"25sp\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2360,
"s": 2218,
"text": "In the above code, we have taken name as Edit text, when user click on button it will take data and check that given string contains “point”."
},
{
"code": null,
"e": 2417,
"s": 2360,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3492,
"s": 2417,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n Button button;\n TextView text;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n name = findViewById(R.id.name);\n button = findViewById(R.id.click);\n text = findViewById(R.id.textview);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n if (name.getText().toString().length() >= 0) {\n text.setText(String.valueOf(name.getText().toString().equals(\"point\")));\n }\n } else {\n name.setError(\"Plz enter name\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3839,
"s": 3492,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4041,
"s": 3839,
"text": "In the above result, enter the string as point and it returned true because it contained point string in given string. Now enter other string without point it gives the result as false as shown below −"
},
{
"code": null,
"e": 4081,
"s": 4041,
"text": "Click here to download the project code"
}
] |
Check if two people starting from different points ever meet - GeeksforGeeks | 05 Jul, 2021
There are two people that start from two different positions, let’s say x1 and x2. Both can jump v1 and v2 meters ahead respectively. We have to find if both will ever meet given that the number of jumps taken by both has to be same.Print ‘Yes’ if they will meet, print ‘No’ they will not.
Examples :
Input : x1 = 5, v1 = 8, x2 = 4, v2 = 7
Output : No
Explanation: The first person is starting ahead of the second one.
and his speed is also greater than the second one, so they will never meet.
Input : x1 = 6, v1 = 6, x2 = 4, v2 = 8
Output : Yes
Naive Approach: In this, we calculate the position of each person after each jump and checks if they have landed in the same spot or not. This one having complexity O(n).
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find if two people// starting from different positions// ever meet or not.#include <bits/stdc++.h>using namespace std; bool everMeet(int x1, int x2, int v1, int v2){ // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >=v2) return false; // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // Until one person crosses other while (x1 >= x2) { if (x1 == x2) return true; // first person taking one // jump in each iteration x1 = x1 + v1; // second person taking // one jump in each iteration x2 = x2 + v2; } return false; } // Driver codeint main(){ int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) printf("Yes"); else printf("No"); return 0;}
// Java program to find// if two people starting// from different positions// ever meet or not.import java.io.*; class GFG{ static void swap(int a, int b) { int t = a; a = b; b = t; } static boolean everMeet(int x1, int x2, int v1, int v2) { // If speed of a person // at a position before // other person is smaller, // then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >= v2) return false; // Making sure that // x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // Until one person // crosses other while (x1 >= x2) { if (x1 == x2) return true; // first person taking one // jump in each iteration x1 = x1 + v1; // second person taking // one jump in each iteration x2 = x2 + v2; } return false; } // Driver code public static void main (String[] args) { int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed// by akt_mit
# Python3 program to find if two# people starting from different# positions ever meet or not. def everMeet(x1, x2, v1, v2): # If speed of a person at # a position before other # person is smaller, then # return false. if (x1 < x2 and v1 <= v2): return False; if (x1 > x2 and v1 >= v2): return False; # Making sure that # x1 is greater if (x1 < x2): x1, x2 = x2,x1; v1, v2 = v2,v1; # Until one person # crosses other while (x1 >= x2): if (x1 == x2): return True; # first person taking one # jump in each iteration x1 = x1 + v1; # second person taking # one jump in each iteration x2 = x2 + v2; return False; # Driver codex1 = 5;v1 = 8;x2 = 4;v2 = 7;if (everMeet(x1, x2,v1, v2)): print("Yes");else: print("No"); # This code is contributed by mits
// C# program to find if two// people starting from different// positions ever meet or not.using System; class GFG{ static void swap(ref int a, ref int b) { int t = a; a = b; b = t; } static bool everMeet(int x1, int x2, int v1, int v2) { // If speed of a person at a // position before other person // is smaller, then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >= v2) return false; // Making sure that x1 is greater if (x1 < x2) { swap(ref x1, ref x2); swap(ref v1, ref v2); } // Until one person crosses other while (x1 >= x2) { if (x1 == x2) return true; // first person taking one // jump in each iteration x1 = x1 + v1; // second person taking // one jump in each iteration x2 = x2 + v2; } return false; } // Driver code static void Main() { int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by// Manish Shaw(manishshaw1)
<?php// PHP program to find if two// people starting from different// positions ever meet or not. function everMeet($x1, $x2, $v1, $v2){ // If speed of a person at // a position before other // person is smaller, then // return false. if ($x1 < $x2 && $v1 <=$v2) return false; if ($x1 > $x2 && $v1 >= $v2) return false; // Making sure that // x1 is greater if ($x1 < $x2) { list($x1, $x2) = array($x2, $x1); list($v1, $v2) = array($v2, $v1); } // Until one person // crosses other while ($x1 >= $x2) { if ($x1 == $x2) return true; // first person taking one // jump in each iteration $x1 = $x1 + $v1; // second person taking // one jump in each iteration $x2 = $x2 + $v2; } return false;} // Driver code$x1 = 5;$v1 = 8;$x2 = 4;$v2 = 7;if (everMeet($x1, $x2, $v1, $v2)) echo "Yes";else echo "No"; // This code is contributed by ajit?>
<script> // Javascript program to find // if two people starting // from different positions // ever meet or not. function swap(a, b) { let t = a; a = b; b = t; } function everMeet(x1, x2, v1, v2) { // If speed of a person // at a position before // other person is smaller, // then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >= v2) return false; // Making sure that // x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // Until one person // crosses other while (x1 >= x2) { if (x1 == x2) return true; // first person taking one // jump in each iteration x1 = x1 + v1; // second person taking // one jump in each iteration x2 = x2 + v2; } return false; } let x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) document.write("Yes"); else document.write("No"); </script>
No
Efficient approach: Other way is to use the concept of Relative Speed. If the X1 is D distance away from X2, then relative speed of X1 should be in factors of D so as both land on the same spot.Example: X1 = 10 X2 = 25 V1 = 10 V2 = 8 Since here D = 15 and relative speed = 2 which is not a factor of D they will never meet.The time complexity of this algorithm is O(1)
Implementation is given below:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find if two people// starting from different positions// ever meet or not.#include <bits/stdc++.h>using namespace std; bool everMeet(int x1, int x2, int v1, int v2){ // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >= v2) return false; // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // checking if relative speed is // a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0);} // Driver codeint main(){ int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) printf("Yes"); else printf("No"); return 0;}
// Java program to find if two people// starting from different positions// ever meet or not. public class GFG { static boolean everMeet(int x1, int x2, int v1, int v2) { // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) { return false; } if (x1 > x2 && v1 >= v2) { return false; } // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // checking if relative speed is // a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0); } static void swap(int a, int b) { int t = a; a = b; b = t; } public static void main(String[] args) { int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) { System.out.printf("Yes"); } else { System.out.printf("No"); } }} // This code is contributed by 29AjayKumar
# Python3 program to find if two people# starting from different positions# ever meet or not. def everMeet(x1, x2, v1, v2): # If speed of a person at a position before # other person is smaller, then return false. if (x1 < x2 and v1 <= v2): return False; if (x1 > x2 and v1 >= v2): return False; # Making sure that x1 is greater if (x1 < x2): swap(x1, x2) swap(v1, v2) # checking if relative speed is # a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0) def swap(a, b): t = a a = b b = t# Driver codedef main(): x1, v1, x2, v2 =5, 8, 4, 7 if (everMeet(x1, x2, v1, v2)): print("Yes") else: print("No") if __name__ == '__main__': main() # This code is contributed by 29AjayKumar
//C# program to find if two people// starting from different positions// ever meet or not.using System;public class GFG{ static bool everMeet(int x1, int x2, int v1, int v2) { // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) { return false; } if (x1 > x2 && v1 >= v2) { return false; } // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // checking if relative speed is // a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0); } static void swap(int a, int b) { int t = a; a = b; b = t; } public static void Main() { int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by 29AjayKumar
<?php// PHP program to find if two people// starting from different positions// ever meet or not. function everMeet($x1, $x2, $v1, $v2){ // If speed of a person at a position before // other person is smaller, then return false. if ($x1 < $x2 && $v1 <= $v2) return false; if ($x1 > $x2 && $v1 >= $v2) return false; // Making sure that x1 is greater if ($x1 < $x2) { list($x1, $x2) = array($x2, $x1); list($v2, $v1) = array($v1, $v2); } // checking if relative speed is // a factor of relative distance or not return (($x1 - $x2) % ($v1 - $v2) == 0);} // Driver code$x1 = 5; $v1 = 8;$x2 = 4; $v2 = 7;if (everMeet($x1, $x2, $v1, $v2)) print("Yes");else print("No"); // This code is contributed by mits?>
<script> // Javascript program to find if two people// starting from different positions// ever meet or not.function everMeet(x1, x2, v1, v2){ // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) { return false; } if (x1 > x2 && v1 >= v2) { return false; } // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // Checking if relative speed is // a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0);} function swap(a, b){ let t = a; a = b; b = t;} // Driver codelet x1 = 5, v1 = 8, x2 = 4, v2 = 7;if (everMeet(x1, x2, v1, v2)){ document.write("Yes");}else{ document.write("No");} // This code is contributed by mukesh07 </script>
No
manishshaw1
jit_t
Mithun Kumar
29AjayKumar
yepitsme
suresh07
mukesh07
surindertarika1234
Mathematical
School Programming
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
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects | [
{
"code": null,
"e": 26066,
"s": 26038,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 26356,
"s": 26066,
"text": "There are two people that start from two different positions, let’s say x1 and x2. Both can jump v1 and v2 meters ahead respectively. We have to find if both will ever meet given that the number of jumps taken by both has to be same.Print ‘Yes’ if they will meet, print ‘No’ they will not."
},
{
"code": null,
"e": 26367,
"s": 26356,
"text": "Examples :"
},
{
"code": null,
"e": 26616,
"s": 26367,
"text": "Input : x1 = 5, v1 = 8, x2 = 4, v2 = 7\nOutput : No\nExplanation: The first person is starting ahead of the second one.\nand his speed is also greater than the second one, so they will never meet.\n\nInput : x1 = 6, v1 = 6, x2 = 4, v2 = 8\nOutput : Yes"
},
{
"code": null,
"e": 26789,
"s": 26616,
"text": "Naive Approach: In this, we calculate the position of each person after each jump and checks if they have landed in the same spot or not. This one having complexity O(n). "
},
{
"code": null,
"e": 26793,
"s": 26789,
"text": "C++"
},
{
"code": null,
"e": 26798,
"s": 26793,
"text": "Java"
},
{
"code": null,
"e": 26806,
"s": 26798,
"text": "Python3"
},
{
"code": null,
"e": 26809,
"s": 26806,
"text": "C#"
},
{
"code": null,
"e": 26813,
"s": 26809,
"text": "PHP"
},
{
"code": null,
"e": 26824,
"s": 26813,
"text": "Javascript"
},
{
"code": "// C++ program to find if two people// starting from different positions// ever meet or not.#include <bits/stdc++.h>using namespace std; bool everMeet(int x1, int x2, int v1, int v2){ // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >=v2) return false; // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // Until one person crosses other while (x1 >= x2) { if (x1 == x2) return true; // first person taking one // jump in each iteration x1 = x1 + v1; // second person taking // one jump in each iteration x2 = x2 + v2; } return false; } // Driver codeint main(){ int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) printf(\"Yes\"); else printf(\"No\"); return 0;}",
"e": 27810,
"s": 26824,
"text": null
},
{
"code": "// Java program to find// if two people starting// from different positions// ever meet or not.import java.io.*; class GFG{ static void swap(int a, int b) { int t = a; a = b; b = t; } static boolean everMeet(int x1, int x2, int v1, int v2) { // If speed of a person // at a position before // other person is smaller, // then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >= v2) return false; // Making sure that // x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // Until one person // crosses other while (x1 >= x2) { if (x1 == x2) return true; // first person taking one // jump in each iteration x1 = x1 + v1; // second person taking // one jump in each iteration x2 = x2 + v2; } return false; } // Driver code public static void main (String[] args) { int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed// by akt_mit",
"e": 29200,
"s": 27810,
"text": null
},
{
"code": "# Python3 program to find if two# people starting from different# positions ever meet or not. def everMeet(x1, x2, v1, v2): # If speed of a person at # a position before other # person is smaller, then # return false. if (x1 < x2 and v1 <= v2): return False; if (x1 > x2 and v1 >= v2): return False; # Making sure that # x1 is greater if (x1 < x2): x1, x2 = x2,x1; v1, v2 = v2,v1; # Until one person # crosses other while (x1 >= x2): if (x1 == x2): return True; # first person taking one # jump in each iteration x1 = x1 + v1; # second person taking # one jump in each iteration x2 = x2 + v2; return False; # Driver codex1 = 5;v1 = 8;x2 = 4;v2 = 7;if (everMeet(x1, x2,v1, v2)): print(\"Yes\");else: print(\"No\"); # This code is contributed by mits",
"e": 30117,
"s": 29200,
"text": null
},
{
"code": "// C# program to find if two// people starting from different// positions ever meet or not.using System; class GFG{ static void swap(ref int a, ref int b) { int t = a; a = b; b = t; } static bool everMeet(int x1, int x2, int v1, int v2) { // If speed of a person at a // position before other person // is smaller, then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >= v2) return false; // Making sure that x1 is greater if (x1 < x2) { swap(ref x1, ref x2); swap(ref v1, ref v2); } // Until one person crosses other while (x1 >= x2) { if (x1 == x2) return true; // first person taking one // jump in each iteration x1 = x1 + v1; // second person taking // one jump in each iteration x2 = x2 + v2; } return false; } // Driver code static void Main() { int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 31493,
"s": 30117,
"text": null
},
{
"code": "<?php// PHP program to find if two// people starting from different// positions ever meet or not. function everMeet($x1, $x2, $v1, $v2){ // If speed of a person at // a position before other // person is smaller, then // return false. if ($x1 < $x2 && $v1 <=$v2) return false; if ($x1 > $x2 && $v1 >= $v2) return false; // Making sure that // x1 is greater if ($x1 < $x2) { list($x1, $x2) = array($x2, $x1); list($v1, $v2) = array($v2, $v1); } // Until one person // crosses other while ($x1 >= $x2) { if ($x1 == $x2) return true; // first person taking one // jump in each iteration $x1 = $x1 + $v1; // second person taking // one jump in each iteration $x2 = $x2 + $v2; } return false;} // Driver code$x1 = 5;$v1 = 8;$x2 = 4;$v2 = 7;if (everMeet($x1, $x2, $v1, $v2)) echo \"Yes\";else echo \"No\"; // This code is contributed by ajit?>",
"e": 32587,
"s": 31493,
"text": null
},
{
"code": "<script> // Javascript program to find // if two people starting // from different positions // ever meet or not. function swap(a, b) { let t = a; a = b; b = t; } function everMeet(x1, x2, v1, v2) { // If speed of a person // at a position before // other person is smaller, // then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >= v2) return false; // Making sure that // x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // Until one person // crosses other while (x1 >= x2) { if (x1 == x2) return true; // first person taking one // jump in each iteration x1 = x1 + v1; // second person taking // one jump in each iteration x2 = x2 + v2; } return false; } let x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 33814,
"s": 32587,
"text": null
},
{
"code": null,
"e": 33817,
"s": 33814,
"text": "No"
},
{
"code": null,
"e": 34189,
"s": 33819,
"text": "Efficient approach: Other way is to use the concept of Relative Speed. If the X1 is D distance away from X2, then relative speed of X1 should be in factors of D so as both land on the same spot.Example: X1 = 10 X2 = 25 V1 = 10 V2 = 8 Since here D = 15 and relative speed = 2 which is not a factor of D they will never meet.The time complexity of this algorithm is O(1) "
},
{
"code": null,
"e": 34222,
"s": 34189,
"text": "Implementation is given below: "
},
{
"code": null,
"e": 34226,
"s": 34222,
"text": "C++"
},
{
"code": null,
"e": 34231,
"s": 34226,
"text": "Java"
},
{
"code": null,
"e": 34239,
"s": 34231,
"text": "Python3"
},
{
"code": null,
"e": 34242,
"s": 34239,
"text": "C#"
},
{
"code": null,
"e": 34246,
"s": 34242,
"text": "PHP"
},
{
"code": null,
"e": 34257,
"s": 34246,
"text": "Javascript"
},
{
"code": "// C++ program to find if two people// starting from different positions// ever meet or not.#include <bits/stdc++.h>using namespace std; bool everMeet(int x1, int x2, int v1, int v2){ // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) return false; if (x1 > x2 && v1 >= v2) return false; // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // checking if relative speed is // a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0);} // Driver codeint main(){ int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) printf(\"Yes\"); else printf(\"No\"); return 0;}",
"e": 35033,
"s": 34257,
"text": null
},
{
"code": "// Java program to find if two people// starting from different positions// ever meet or not. public class GFG { static boolean everMeet(int x1, int x2, int v1, int v2) { // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) { return false; } if (x1 > x2 && v1 >= v2) { return false; } // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // checking if relative speed is // a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0); } static void swap(int a, int b) { int t = a; a = b; b = t; } public static void main(String[] args) { int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) { System.out.printf(\"Yes\"); } else { System.out.printf(\"No\"); } }} // This code is contributed by 29AjayKumar",
"e": 36073,
"s": 35033,
"text": null
},
{
"code": " # Python3 program to find if two people# starting from different positions# ever meet or not. def everMeet(x1, x2, v1, v2): # If speed of a person at a position before # other person is smaller, then return false. if (x1 < x2 and v1 <= v2): return False; if (x1 > x2 and v1 >= v2): return False; # Making sure that x1 is greater if (x1 < x2): swap(x1, x2) swap(v1, v2) # checking if relative speed is # a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0) def swap(a, b): t = a a = b b = t# Driver codedef main(): x1, v1, x2, v2 =5, 8, 4, 7 if (everMeet(x1, x2, v1, v2)): print(\"Yes\") else: print(\"No\") if __name__ == '__main__': main() # This code is contributed by 29AjayKumar",
"e": 37051,
"s": 36073,
"text": null
},
{
"code": "//C# program to find if two people// starting from different positions// ever meet or not.using System;public class GFG{ static bool everMeet(int x1, int x2, int v1, int v2) { // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) { return false; } if (x1 > x2 && v1 >= v2) { return false; } // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // checking if relative speed is // a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0); } static void swap(int a, int b) { int t = a; a = b; b = t; } public static void Main() { int x1 = 5, v1 = 8, x2 = 4, v2 = 7; if (everMeet(x1, x2, v1, v2)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by 29AjayKumar",
"e": 38085,
"s": 37051,
"text": null
},
{
"code": "<?php// PHP program to find if two people// starting from different positions// ever meet or not. function everMeet($x1, $x2, $v1, $v2){ // If speed of a person at a position before // other person is smaller, then return false. if ($x1 < $x2 && $v1 <= $v2) return false; if ($x1 > $x2 && $v1 >= $v2) return false; // Making sure that x1 is greater if ($x1 < $x2) { list($x1, $x2) = array($x2, $x1); list($v2, $v1) = array($v1, $v2); } // checking if relative speed is // a factor of relative distance or not return (($x1 - $x2) % ($v1 - $v2) == 0);} // Driver code$x1 = 5; $v1 = 8;$x2 = 4; $v2 = 7;if (everMeet($x1, $x2, $v1, $v2)) print(\"Yes\");else print(\"No\"); // This code is contributed by mits?>",
"e": 38857,
"s": 38085,
"text": null
},
{
"code": "<script> // Javascript program to find if two people// starting from different positions// ever meet or not.function everMeet(x1, x2, v1, v2){ // If speed of a person at a position before // other person is smaller, then return false. if (x1 < x2 && v1 <= v2) { return false; } if (x1 > x2 && v1 >= v2) { return false; } // Making sure that x1 is greater if (x1 < x2) { swap(x1, x2); swap(v1, v2); } // Checking if relative speed is // a factor of relative distance or not return ((x1 - x2) % (v1 - v2) == 0);} function swap(a, b){ let t = a; a = b; b = t;} // Driver codelet x1 = 5, v1 = 8, x2 = 4, v2 = 7;if (everMeet(x1, x2, v1, v2)){ document.write(\"Yes\");}else{ document.write(\"No\");} // This code is contributed by mukesh07 </script>",
"e": 39694,
"s": 38857,
"text": null
},
{
"code": null,
"e": 39697,
"s": 39694,
"text": "No"
},
{
"code": null,
"e": 39711,
"s": 39699,
"text": "manishshaw1"
},
{
"code": null,
"e": 39717,
"s": 39711,
"text": "jit_t"
},
{
"code": null,
"e": 39730,
"s": 39717,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 39742,
"s": 39730,
"text": "29AjayKumar"
},
{
"code": null,
"e": 39751,
"s": 39742,
"text": "yepitsme"
},
{
"code": null,
"e": 39760,
"s": 39751,
"text": "suresh07"
},
{
"code": null,
"e": 39769,
"s": 39760,
"text": "mukesh07"
},
{
"code": null,
"e": 39788,
"s": 39769,
"text": "surindertarika1234"
},
{
"code": null,
"e": 39801,
"s": 39788,
"text": "Mathematical"
},
{
"code": null,
"e": 39820,
"s": 39801,
"text": "School Programming"
},
{
"code": null,
"e": 39833,
"s": 39820,
"text": "Mathematical"
},
{
"code": null,
"e": 39931,
"s": 39833,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39955,
"s": 39931,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 39998,
"s": 39955,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 40012,
"s": 39998,
"text": "Prime Numbers"
},
{
"code": null,
"e": 40085,
"s": 40012,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 40106,
"s": 40085,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 40124,
"s": 40106,
"text": "Python Dictionary"
},
{
"code": null,
"e": 40140,
"s": 40124,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 40159,
"s": 40140,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 40184,
"s": 40159,
"text": "Reverse a string in Java"
}
] |
p5.js | pointLight() Function - GeeksforGeeks | 27 Apr, 2020
The pointLight() function in p5.js is used to create a point lights with the specified color and position in the scene. A scene can have a maximum of 5 active point lights at a time.
Syntax:
pointLight( v1, v2, v3, x, y, z )
OR
pointLight( v1, v2, v3, position )
OR
pointLight( color, x, y, z )
OR
pointLight( color, position )
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.
x: It is a number which determines the x axis position of the light.
y: It is a number which determines the y axis position of the light.
z: It is a number which determines the z axis position of the light.
position: It is p5.Vector which defines the position of the light.
color: It is a color string or p5.Color which defines the color of the point light.
Below example illustrates the pointLight() function in p5.js:
Example 1:
let newFont;let directionalLightEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 16); redSlider = createSlider(0, 255, 128, 1); redSlider.position(20, 50); greenSlider = createSlider(0, 255, 128, 1); greenSlider.position(20, 80); blueSlider = createSlider(0, 255, 128, 1); blueSlider.position(20, 110);} function draw() { background('green'); text("Move the sliders to change the point light's red, "+ "green and blue values", -285, -125); noStroke(); redValue = redSlider.value(); greenValue = greenSlider.value(); blueValue = blueSlider.value(); // Create a point light with the selected light color pointLight(redValue, greenValue, blueValue, 100, 0, 150); ambientMaterial(255); // Create the sphere on which the point light will work sphere(100);}
Output:
Example 2:
let newFont;let directionalLightEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 16); xPosSlider = createSlider(-150, 150, 100, 1); xPosSlider.position(20, 50); yPosSlider = createSlider(-300, 300, 0, 1); yPosSlider.position(20, 80); zPosSlider = createSlider(0, 250, 150, 1); zPosSlider.position(20, 110); } function draw() { background('green'); text("Change the sliders to move the point light position "+ "along x, y and z axis", -285, -125); noStroke(); xPositionValue = xPosSlider.value(); yPositionValue = yPosSlider.value(); zPositionValue = zPosSlider.value(); // Create a point light at the selected location pointLight(255, 0, 0, xPositionValue, yPositionValue, zPositionValue); // Create a sphere to show the demonstrate // of the point light location translate(xPositionValue, yPositionValue, zPositionValue); sphere(10); translate(-xPositionValue, -yPositionValue, -zPositionValue); specularMaterial(255); // Create the sphere on which the point light will work sphere(100);}
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/pointLight
JavaScript-p5.js
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 calculate the number of days between two dates in 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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 44937,
"s": 44909,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 45120,
"s": 44937,
"text": "The pointLight() function in p5.js is used to create a point lights with the specified color and position in the scene. A scene can have a maximum of 5 active point lights at a time."
},
{
"code": null,
"e": 45128,
"s": 45120,
"text": "Syntax:"
},
{
"code": null,
"e": 45162,
"s": 45128,
"text": "pointLight( v1, v2, v3, x, y, z )"
},
{
"code": null,
"e": 45165,
"s": 45162,
"text": "OR"
},
{
"code": null,
"e": 45200,
"s": 45165,
"text": "pointLight( v1, v2, v3, position )"
},
{
"code": null,
"e": 45203,
"s": 45200,
"text": "OR"
},
{
"code": null,
"e": 45232,
"s": 45203,
"text": "pointLight( color, x, y, z )"
},
{
"code": null,
"e": 45235,
"s": 45232,
"text": "OR"
},
{
"code": null,
"e": 45265,
"s": 45235,
"text": "pointLight( color, position )"
},
{
"code": null,
"e": 45355,
"s": 45265,
"text": "Parameters: This function accept eight parameters as mentioned above and described below:"
},
{
"code": null,
"e": 45449,
"s": 45355,
"text": "v1: It is a number which determines the red or hue value relative to the current color range."
},
{
"code": null,
"e": 45552,
"s": 45449,
"text": "v2: It is a number which determines the green or saturation value relative to the current color range."
},
{
"code": null,
"e": 45654,
"s": 45552,
"text": "v3: It is a number which determines the blue or brightness value relative to the current color range."
},
{
"code": null,
"e": 45723,
"s": 45654,
"text": "x: It is a number which determines the x axis position of the light."
},
{
"code": null,
"e": 45792,
"s": 45723,
"text": "y: It is a number which determines the y axis position of the light."
},
{
"code": null,
"e": 45861,
"s": 45792,
"text": "z: It is a number which determines the z axis position of the light."
},
{
"code": null,
"e": 45928,
"s": 45861,
"text": "position: It is p5.Vector which defines the position of the light."
},
{
"code": null,
"e": 46012,
"s": 45928,
"text": "color: It is a color string or p5.Color which defines the color of the point light."
},
{
"code": null,
"e": 46074,
"s": 46012,
"text": "Below example illustrates the pointLight() function in p5.js:"
},
{
"code": null,
"e": 46085,
"s": 46074,
"text": "Example 1:"
},
{
"code": "let newFont;let directionalLightEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 16); redSlider = createSlider(0, 255, 128, 1); redSlider.position(20, 50); greenSlider = createSlider(0, 255, 128, 1); greenSlider.position(20, 80); blueSlider = createSlider(0, 255, 128, 1); blueSlider.position(20, 110);} function draw() { background('green'); text(\"Move the sliders to change the point light's red, \"+ \"green and blue values\", -285, -125); noStroke(); redValue = redSlider.value(); greenValue = greenSlider.value(); blueValue = blueSlider.value(); // Create a point light with the selected light color pointLight(redValue, greenValue, blueValue, 100, 0, 150); ambientMaterial(255); // Create the sphere on which the point light will work sphere(100);}",
"e": 46998,
"s": 46085,
"text": null
},
{
"code": null,
"e": 47006,
"s": 46998,
"text": "Output:"
},
{
"code": null,
"e": 47017,
"s": 47006,
"text": "Example 2:"
},
{
"code": "let newFont;let directionalLightEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 16); xPosSlider = createSlider(-150, 150, 100, 1); xPosSlider.position(20, 50); yPosSlider = createSlider(-300, 300, 0, 1); yPosSlider.position(20, 80); zPosSlider = createSlider(0, 250, 150, 1); zPosSlider.position(20, 110); } function draw() { background('green'); text(\"Change the sliders to move the point light position \"+ \"along x, y and z axis\", -285, -125); noStroke(); xPositionValue = xPosSlider.value(); yPositionValue = yPosSlider.value(); zPositionValue = zPosSlider.value(); // Create a point light at the selected location pointLight(255, 0, 0, xPositionValue, yPositionValue, zPositionValue); // Create a sphere to show the demonstrate // of the point light location translate(xPositionValue, yPositionValue, zPositionValue); sphere(10); translate(-xPositionValue, -yPositionValue, -zPositionValue); specularMaterial(255); // Create the sphere on which the point light will work sphere(100);}",
"e": 48178,
"s": 47017,
"text": null
},
{
"code": null,
"e": 48186,
"s": 48178,
"text": "Output:"
},
{
"code": null,
"e": 48226,
"s": 48186,
"text": "Online editor: https://editor.p5js.org/"
},
{
"code": null,
"e": 48324,
"s": 48226,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 48378,
"s": 48324,
"text": "Reference: https://p5js.org/reference/#/p5/pointLight"
},
{
"code": null,
"e": 48395,
"s": 48378,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 48406,
"s": 48395,
"text": "JavaScript"
},
{
"code": null,
"e": 48423,
"s": 48406,
"text": "Web Technologies"
},
{
"code": null,
"e": 48521,
"s": 48423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48561,
"s": 48521,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 48606,
"s": 48561,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 48667,
"s": 48606,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 48739,
"s": 48667,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 48808,
"s": 48739,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 48848,
"s": 48808,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 48881,
"s": 48848,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 48926,
"s": 48881,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 48969,
"s": 48926,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to use Container Component in ReactJS? - GeeksforGeeks | 18 Jan, 2021
The container centers your content horizontally. It’s the most basic layout element. Material UI for React has this component available for us and it is very easy to integrate. We can the Container component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react'import Typography from '@material-ui/core/Typography';import Container from '@material-ui/core/Container'; const App = () => { return ( <Container maxWidth="sm"> <Typography component="div" style={{ backgroundColor: 'Orange', height: '100vh' }}> Greetings from GeeksforGeeks </Typography> </Container> );} export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
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?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components | [
{
"code": null,
"e": 26557,
"s": 26529,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 26806,
"s": 26557,
"text": "The container centers your content horizontally. It’s the most basic layout element. Material UI for React has this component available for us and it is very easy to integrate. We can the Container component in ReactJS using the following approach."
},
{
"code": null,
"e": 26856,
"s": 26806,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26920,
"s": 26856,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 26952,
"s": 26920,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27052,
"s": 26952,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27066,
"s": 27052,
"text": "cd foldername"
},
{
"code": null,
"e": 27175,
"s": 27066,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:"
},
{
"code": null,
"e": 27205,
"s": 27175,
"text": "npm install @material-ui/core"
},
{
"code": null,
"e": 27257,
"s": 27205,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27275,
"s": 27257,
"text": "Project Structure"
},
{
"code": null,
"e": 27404,
"s": 27275,
"text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 27415,
"s": 27404,
"text": "Javascript"
},
{
"code": "import React from 'react'import Typography from '@material-ui/core/Typography';import Container from '@material-ui/core/Container'; const App = () => { return ( <Container maxWidth=\"sm\"> <Typography component=\"div\" style={{ backgroundColor: 'Orange', height: '100vh' }}> Greetings from GeeksforGeeks </Typography> </Container> );} export default App",
"e": 27806,
"s": 27415,
"text": null
},
{
"code": null,
"e": 27919,
"s": 27806,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 27929,
"s": 27919,
"text": "npm start"
},
{
"code": null,
"e": 28028,
"s": 27929,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 28039,
"s": 28028,
"text": "JavaScript"
},
{
"code": null,
"e": 28047,
"s": 28039,
"text": "ReactJS"
},
{
"code": null,
"e": 28064,
"s": 28047,
"text": "Web Technologies"
},
{
"code": null,
"e": 28162,
"s": 28064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28202,
"s": 28162,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28263,
"s": 28202,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28304,
"s": 28263,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28326,
"s": 28304,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28380,
"s": 28326,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28423,
"s": 28380,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28468,
"s": 28423,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 28533,
"s": 28468,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 28601,
"s": 28533,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
How to add image before optgroup label using Bootstrap ? - GeeksforGeeks | 05 May, 2022
What is optgroup label?
It is an HTML tag that is used to group the options given in <select> tag. This combines the options in different groups having different labels.
Syntax:
HTML
<optgroup label="text"> <option value="One">One</option> <option value="Two">Two</option></optgroup>
If we need to add an image before optgroup label using bootstrap than we have to put “image” tag in label giving the source location of the image with the label name.
Example: The following example demonstrates the optgroup having image before label using Bootstrap.
HTML
<!DOCTYPE html><html lang="en"><head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"> </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"> </script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"> </script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-select.min.css"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.min.js"> </script> <style> .bootstrap-select img { width: 16px; } </style></head><body> <select class="selectpicker"> <optgroup label= "<img src='https://openmoji.org/data/color/svg/1F600.svg'> Numbers"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </optgroup> <optgroup label= "<img src='https://openmoji.org/data/color/svg/1F923.svg'> Digits"> <option value="Four">4</option> <option value="Five">5</option> <option value="Six">6</option> </optgroup> </select> <script> $('.selectpicker').on('shown.bs.select', function () { $('.bootstrap-select .dropdown-header').each(function () { if ((this.dataset.unescaped || '1') == '1') { let element = $(this); element.html(element.text()); element.attr('data-unescaped', '0'); } }) }) </script></body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
sahilintern
Bootstrap-4
Bootstrap-Misc
CSS-Misc
HTML-Misc
Bootstrap
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS? | [
{
"code": null,
"e": 29661,
"s": 29633,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 29685,
"s": 29661,
"text": "What is optgroup label?"
},
{
"code": null,
"e": 29831,
"s": 29685,
"text": "It is an HTML tag that is used to group the options given in <select> tag. This combines the options in different groups having different labels."
},
{
"code": null,
"e": 29840,
"s": 29831,
"text": "Syntax: "
},
{
"code": null,
"e": 29845,
"s": 29840,
"text": "HTML"
},
{
"code": "<optgroup label=\"text\"> <option value=\"One\">One</option> <option value=\"Two\">Two</option></optgroup>",
"e": 29952,
"s": 29845,
"text": null
},
{
"code": null,
"e": 30119,
"s": 29952,
"text": "If we need to add an image before optgroup label using bootstrap than we have to put “image” tag in label giving the source location of the image with the label name."
},
{
"code": null,
"e": 30219,
"s": 30119,
"text": "Example: The following example demonstrates the optgroup having image before label using Bootstrap."
},
{
"code": null,
"e": 30224,
"s": 30219,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\"> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-select.min.css\"> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.min.js\"> </script> <style> .bootstrap-select img { width: 16px; } </style></head><body> <select class=\"selectpicker\"> <optgroup label= \"<img src='https://openmoji.org/data/color/svg/1F600.svg'> Numbers\"> <option value=\"1\">One</option> <option value=\"2\">Two</option> <option value=\"3\">Three</option> </optgroup> <optgroup label= \"<img src='https://openmoji.org/data/color/svg/1F923.svg'> Digits\"> <option value=\"Four\">4</option> <option value=\"Five\">5</option> <option value=\"Six\">6</option> </optgroup> </select> <script> $('.selectpicker').on('shown.bs.select', function () { $('.bootstrap-select .dropdown-header').each(function () { if ((this.dataset.unescaped || '1') == '1') { let element = $(this); element.html(element.text()); element.attr('data-unescaped', '0'); } }) }) </script></body></html>",
"e": 32118,
"s": 30224,
"text": null
},
{
"code": null,
"e": 32126,
"s": 32118,
"text": "Output:"
},
{
"code": null,
"e": 32263,
"s": 32126,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 32275,
"s": 32263,
"text": "sahilintern"
},
{
"code": null,
"e": 32287,
"s": 32275,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 32302,
"s": 32287,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 32311,
"s": 32302,
"text": "CSS-Misc"
},
{
"code": null,
"e": 32321,
"s": 32311,
"text": "HTML-Misc"
},
{
"code": null,
"e": 32331,
"s": 32321,
"text": "Bootstrap"
},
{
"code": null,
"e": 32335,
"s": 32331,
"text": "CSS"
},
{
"code": null,
"e": 32340,
"s": 32335,
"text": "HTML"
},
{
"code": null,
"e": 32357,
"s": 32340,
"text": "Web Technologies"
},
{
"code": null,
"e": 32384,
"s": 32357,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 32389,
"s": 32384,
"text": "HTML"
},
{
"code": null,
"e": 32487,
"s": 32389,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32537,
"s": 32487,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 32566,
"s": 32537,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32607,
"s": 32566,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 32663,
"s": 32607,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 32704,
"s": 32663,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 32766,
"s": 32704,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32816,
"s": 32766,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 32864,
"s": 32816,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 32922,
"s": 32864,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
Difference between Public and Private in C++ with Example - GeeksforGeeks | 15 Oct, 2019
Public
All the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.
Example:
// C++ program to demonstrate public// access modifier #include <iostream>using namespace std; // class definitionclass Circle {public: double radius; double compute_area() { return 3.14 * radius * radius; }}; // main functionint main(){ Circle obj; // accessing public data member outside class obj.radius = 5.5; cout << "Radius is: " << obj.radius << "\n"; cout << "Area is: " << obj.compute_area(); return 0;}
Radius is: 5.5
Area is: 94.985
In the above program, the data member radius is public so we are allowed to access it outside the class.
Private
The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.Example:
// C++ program to demonstrate private// access modifier #include <iostream>using namespace std; class Circle { // private data memberprivate: double radius; // public member functionpublic: void compute_area(double r) { // member function can access private // data member radius radius = r; double area = 3.14 * radius * radius; cout << "Radius is: " << radius << endl; cout << "Area is: " << area; }}; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.compute_area(1.5); return 0;}
Radius is: 1.5
Area is: 7.065
Difference between Public and Private
C++ Programs
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6 | [
{
"code": null,
"e": 25797,
"s": 25769,
"text": "\n15 Oct, 2019"
},
{
"code": null,
"e": 25804,
"s": 25797,
"text": "Public"
},
{
"code": null,
"e": 26121,
"s": 25804,
"text": "All the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class."
},
{
"code": null,
"e": 26130,
"s": 26121,
"text": "Example:"
},
{
"code": "// C++ program to demonstrate public// access modifier #include <iostream>using namespace std; // class definitionclass Circle {public: double radius; double compute_area() { return 3.14 * radius * radius; }}; // main functionint main(){ Circle obj; // accessing public data member outside class obj.radius = 5.5; cout << \"Radius is: \" << obj.radius << \"\\n\"; cout << \"Area is: \" << obj.compute_area(); return 0;}",
"e": 26589,
"s": 26130,
"text": null
},
{
"code": null,
"e": 26621,
"s": 26589,
"text": "Radius is: 5.5\nArea is: 94.985\n"
},
{
"code": null,
"e": 26726,
"s": 26621,
"text": "In the above program, the data member radius is public so we are allowed to access it outside the class."
},
{
"code": null,
"e": 26734,
"s": 26726,
"text": "Private"
},
{
"code": null,
"e": 27035,
"s": 26734,
"text": "The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.Example:"
},
{
"code": "// C++ program to demonstrate private// access modifier #include <iostream>using namespace std; class Circle { // private data memberprivate: double radius; // public member functionpublic: void compute_area(double r) { // member function can access private // data member radius radius = r; double area = 3.14 * radius * radius; cout << \"Radius is: \" << radius << endl; cout << \"Area is: \" << area; }}; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.compute_area(1.5); return 0;}",
"e": 27706,
"s": 27035,
"text": null
},
{
"code": null,
"e": 27737,
"s": 27706,
"text": "Radius is: 1.5\nArea is: 7.065\n"
},
{
"code": null,
"e": 27775,
"s": 27737,
"text": "Difference between Public and Private"
},
{
"code": null,
"e": 27788,
"s": 27775,
"text": "C++ Programs"
},
{
"code": null,
"e": 27807,
"s": 27788,
"text": "Difference Between"
},
{
"code": null,
"e": 27905,
"s": 27807,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27946,
"s": 27905,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 28005,
"s": 27946,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 28026,
"s": 28005,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 28038,
"s": 28026,
"text": "cout in C++"
},
{
"code": null,
"e": 28059,
"s": 28038,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 28090,
"s": 28059,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 28130,
"s": 28090,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 28162,
"s": 28130,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 28223,
"s": 28162,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Print Function in C, C++, and Python - GeeksforGeeks | 08 Mar, 2021
In this article, the task is to observe the behavior of the print function in C, C++, and Python. Print function is used to display content on the screen.
Approach:
Some characters are stored in integer value inside printf function.
Printing the value as well as the count of the characters.
Illustrating the different use of printf().
Below is the C program printing the inside printf:
C
// C program printing inside printf() #include <stdio.h> // Driver Codeint main(){ // Stores no of characters printed by printf int val = printf("GeeksForGeeks\n"); // Print the count of characters printf("Int printf(\"GeeksForGeeks\\n \") = %d\n", val); return 0;}
GeeksForGeeks
Int printf("GeeksForGeeks\n ") = 14
Below is the C++ program printing inside cout:
C++
// C++ program printing inside cout #include <iostream>using namespace std; // Driver Codeint main(){ // Store no of characters printed by printf int value = printf("GeeksForGeeks\n"); // Prints the count of the characters cout << "Integer printf(\"GeeksForGeeks\\n\") = " << value << endl;}
GeeksForGeeks
Integer printf("GeeksForGeeks\n") = 14
Explanation:
In both the above code, printf returns the number of character it has printed successfully.
“GeeksForGeeks\n” have 14 characters hence it will print 14.
Below is the python program illustrating print():
Python3
# Python program illustrating print() # Storing valuevalue=print("GeeksForGeeks\n") # Printing valueprint(value)
GeeksForGeeks
None
Explanation: In python3, Print function never returns anything that’s why it is returning None.
C Language
C++
Python
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 25453,
"s": 25425,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 25608,
"s": 25453,
"text": "In this article, the task is to observe the behavior of the print function in C, C++, and Python. Print function is used to display content on the screen."
},
{
"code": null,
"e": 25619,
"s": 25608,
"text": "Approach: "
},
{
"code": null,
"e": 25687,
"s": 25619,
"text": "Some characters are stored in integer value inside printf function."
},
{
"code": null,
"e": 25746,
"s": 25687,
"text": "Printing the value as well as the count of the characters."
},
{
"code": null,
"e": 25790,
"s": 25746,
"text": "Illustrating the different use of printf()."
},
{
"code": null,
"e": 25841,
"s": 25790,
"text": "Below is the C program printing the inside printf:"
},
{
"code": null,
"e": 25843,
"s": 25841,
"text": "C"
},
{
"code": "// C program printing inside printf() #include <stdio.h> // Driver Codeint main(){ // Stores no of characters printed by printf int val = printf(\"GeeksForGeeks\\n\"); // Print the count of characters printf(\"Int printf(\\\"GeeksForGeeks\\\\n \\\") = %d\\n\", val); return 0;}",
"e": 26138,
"s": 25843,
"text": null
},
{
"code": null,
"e": 26188,
"s": 26138,
"text": "GeeksForGeeks\nInt printf(\"GeeksForGeeks\\n \") = 14"
},
{
"code": null,
"e": 26235,
"s": 26188,
"text": "Below is the C++ program printing inside cout:"
},
{
"code": null,
"e": 26239,
"s": 26235,
"text": "C++"
},
{
"code": "// C++ program printing inside cout #include <iostream>using namespace std; // Driver Codeint main(){ // Store no of characters printed by printf int value = printf(\"GeeksForGeeks\\n\"); // Prints the count of the characters cout << \"Integer printf(\\\"GeeksForGeeks\\\\n\\\") = \" << value << endl;}",
"e": 26561,
"s": 26239,
"text": null
},
{
"code": null,
"e": 26614,
"s": 26561,
"text": "GeeksForGeeks\nInteger printf(\"GeeksForGeeks\\n\") = 14"
},
{
"code": null,
"e": 26627,
"s": 26614,
"text": "Explanation:"
},
{
"code": null,
"e": 26719,
"s": 26627,
"text": "In both the above code, printf returns the number of character it has printed successfully."
},
{
"code": null,
"e": 26780,
"s": 26719,
"text": "“GeeksForGeeks\\n” have 14 characters hence it will print 14."
},
{
"code": null,
"e": 26830,
"s": 26780,
"text": "Below is the python program illustrating print():"
},
{
"code": null,
"e": 26838,
"s": 26830,
"text": "Python3"
},
{
"code": "# Python program illustrating print() # Storing valuevalue=print(\"GeeksForGeeks\\n\") # Printing valueprint(value)",
"e": 26953,
"s": 26838,
"text": null
},
{
"code": null,
"e": 26973,
"s": 26953,
"text": "GeeksForGeeks\n\nNone"
},
{
"code": null,
"e": 27069,
"s": 26973,
"text": "Explanation: In python3, Print function never returns anything that’s why it is returning None."
},
{
"code": null,
"e": 27080,
"s": 27069,
"text": "C Language"
},
{
"code": null,
"e": 27084,
"s": 27080,
"text": "C++"
},
{
"code": null,
"e": 27091,
"s": 27084,
"text": "Python"
},
{
"code": null,
"e": 27095,
"s": 27091,
"text": "CPP"
},
{
"code": null,
"e": 27193,
"s": 27095,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27231,
"s": 27193,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27257,
"s": 27231,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 27277,
"s": 27257,
"text": "Multithreading in C"
},
{
"code": null,
"e": 27299,
"s": 27277,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 27340,
"s": 27299,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27358,
"s": 27340,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27404,
"s": 27358,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27423,
"s": 27404,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27466,
"s": 27423,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
basic_istream::seekg() in C++ with Examples - GeeksforGeeks | 28 May, 2020
The basic_stream::seekg() method is used to set position of the next character to be extracted from the input stream. This function is present in the iostream header file. Below is the syntax for the same:
Header File:
#include<iostream>
Syntax:
basic_istream& seekg (pos_type pos);
Parameter:
pos: It represents the new position in the buffer .
Return Value: This function returns the basic_istream object.
Below is the program to illustrate std::basic_istream::seekg()
Program 1:
// C++ code for basic_istream::seekg() #include <bits/stdc++.h>using namespace std; // Driver codeint main(){ string str = "Geeks for Geeks"; istringstream gfg(str); string a, b; gfg >> a; gfg.seekg(0); // rewind gfg >> b; cout << "a = " << a << endl; cout << "b = " << b << endl;}
a = Geeks
b = Geeks
Program 2:
// C++ code for basic_istream::seekg() #include <bits/stdc++.h>using namespace std; // Driver codeint main(){ string str = "Geeks for Geeks"; istringstream gfg(str); string a, b; gfg >> a; gfg.seekg(6); // rewind gfg >> b; cout << "a = " << a << endl; cout << "b = " << b << endl;}
a = Geeks
b = for
Reference: http://www.cplusplus.com/reference/istream/basic_istream/seekg/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++ | [
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 25549,
"s": 25343,
"text": "The basic_stream::seekg() method is used to set position of the next character to be extracted from the input stream. This function is present in the iostream header file. Below is the syntax for the same:"
},
{
"code": null,
"e": 25562,
"s": 25549,
"text": "Header File:"
},
{
"code": null,
"e": 25582,
"s": 25562,
"text": "#include<iostream>\n"
},
{
"code": null,
"e": 25590,
"s": 25582,
"text": "Syntax:"
},
{
"code": null,
"e": 25628,
"s": 25590,
"text": "basic_istream& seekg (pos_type pos);\n"
},
{
"code": null,
"e": 25639,
"s": 25628,
"text": "Parameter:"
},
{
"code": null,
"e": 25691,
"s": 25639,
"text": "pos: It represents the new position in the buffer ."
},
{
"code": null,
"e": 25753,
"s": 25691,
"text": "Return Value: This function returns the basic_istream object."
},
{
"code": null,
"e": 25816,
"s": 25753,
"text": "Below is the program to illustrate std::basic_istream::seekg()"
},
{
"code": null,
"e": 25827,
"s": 25816,
"text": "Program 1:"
},
{
"code": "// C++ code for basic_istream::seekg() #include <bits/stdc++.h>using namespace std; // Driver codeint main(){ string str = \"Geeks for Geeks\"; istringstream gfg(str); string a, b; gfg >> a; gfg.seekg(0); // rewind gfg >> b; cout << \"a = \" << a << endl; cout << \"b = \" << b << endl;}",
"e": 26139,
"s": 25827,
"text": null
},
{
"code": null,
"e": 26160,
"s": 26139,
"text": "a = Geeks\nb = Geeks\n"
},
{
"code": null,
"e": 26171,
"s": 26160,
"text": "Program 2:"
},
{
"code": "// C++ code for basic_istream::seekg() #include <bits/stdc++.h>using namespace std; // Driver codeint main(){ string str = \"Geeks for Geeks\"; istringstream gfg(str); string a, b; gfg >> a; gfg.seekg(6); // rewind gfg >> b; cout << \"a = \" << a << endl; cout << \"b = \" << b << endl;}",
"e": 26483,
"s": 26171,
"text": null
},
{
"code": null,
"e": 26502,
"s": 26483,
"text": "a = Geeks\nb = for\n"
},
{
"code": null,
"e": 26577,
"s": 26502,
"text": "Reference: http://www.cplusplus.com/reference/istream/basic_istream/seekg/"
},
{
"code": null,
"e": 26591,
"s": 26577,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26595,
"s": 26591,
"text": "C++"
},
{
"code": null,
"e": 26599,
"s": 26595,
"text": "CPP"
},
{
"code": null,
"e": 26697,
"s": 26599,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26725,
"s": 26697,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26745,
"s": 26725,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26769,
"s": 26745,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26802,
"s": 26769,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26827,
"s": 26802,
"text": "std::string class in C++"
},
{
"code": null,
"e": 26871,
"s": 26827,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26916,
"s": 26871,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26940,
"s": 26916,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 26993,
"s": 26940,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
Python IMDbPY – Getting top 250 movies - GeeksforGeeks | 22 Apr, 2020
In this article we will see how we can retrieve the information of top 250 movies in IMDb database, IMDb sets ratings to all the movies.
In order to get the top 250 movies by IMDb we will use get_top250_movies method.
Syntax : imdb_object.get_top250_movies()
Argument : It takes no argument
Return : It returns list of 250 element and each element is idbm movie object
Below is the implementation
# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # getting top 250 moviessearch = ia.get_top250_movies() # printing only first 10 movies titlefor i in range(10): print(search[i]['title'])
Output :
The Shawshank Redemption
The Godfather
The Godfather: Part II
The Dark Knight
12 Angry Men
Schindler's List
The Lord of the Rings: The Return of the King
Pulp Fiction
The Good, the Bad and the Ugly
The Lord of the Rings: The Fellowship of the Ring
Python IMDbPY-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25853,
"s": 25825,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25990,
"s": 25853,
"text": "In this article we will see how we can retrieve the information of top 250 movies in IMDb database, IMDb sets ratings to all the movies."
},
{
"code": null,
"e": 26071,
"s": 25990,
"text": "In order to get the top 250 movies by IMDb we will use get_top250_movies method."
},
{
"code": null,
"e": 26112,
"s": 26071,
"text": "Syntax : imdb_object.get_top250_movies()"
},
{
"code": null,
"e": 26144,
"s": 26112,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 26222,
"s": 26144,
"text": "Return : It returns list of 250 element and each element is idbm movie object"
},
{
"code": null,
"e": 26250,
"s": 26222,
"text": "Below is the implementation"
},
{
"code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # getting top 250 moviessearch = ia.get_top250_movies() # printing only first 10 movies titlefor i in range(10): print(search[i]['title'])",
"e": 26475,
"s": 26250,
"text": null
},
{
"code": null,
"e": 26484,
"s": 26475,
"text": "Output :"
},
{
"code": null,
"e": 26733,
"s": 26484,
"text": "The Shawshank Redemption\nThe Godfather\nThe Godfather: Part II\nThe Dark Knight\n12 Angry Men\nSchindler's List\nThe Lord of the Rings: The Return of the King\nPulp Fiction\nThe Good, the Bad and the Ugly\nThe Lord of the Rings: The Fellowship of the Ring\n"
},
{
"code": null,
"e": 26754,
"s": 26733,
"text": "Python IMDbPY-module"
},
{
"code": null,
"e": 26761,
"s": 26754,
"text": "Python"
},
{
"code": null,
"e": 26859,
"s": 26761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26877,
"s": 26859,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26912,
"s": 26877,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26944,
"s": 26912,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26966,
"s": 26944,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27008,
"s": 26966,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27038,
"s": 27008,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27064,
"s": 27038,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27093,
"s": 27064,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27137,
"s": 27093,
"text": "Reading and Writing to text files in Python"
}
] |
Installing and Using Exiftool on Linux - GeeksforGeeks | 11 Feb, 2021
EXIF tool is a widely used meta-data information recorder built on Perl by Phil Harvey. It is one of a kind open-source tool which works on a variety of file types. EXIF stands for Exchangeable Image File Format, and it is mainly used for including metadata in various file types like txt, png, jpeg, pdf, HTML and many more. With EXIF tool we can also read, write and manipulate such meta-data information.
Exiftool is an open-source tool. The library is built with Platform Independent Perl library.
1. Clone the git repo onto your system.
git clone https://github.com/exiftool/exiftool.git
2. Test the tool with a test file present in the repository
cd exiftool
./exiftool t/images/ExifTool.jpg
Alternatively, on Ubuntu distribution you can use:
sudo apt install libimage-exiftool-perl
Or simply use the following command it will automatically capture the above command.
sudo apt install exiftool
For downloading directly from the Source, use the following commands. This will work for any Linux distro including CentOS.
wget https://sourceforge.net/projects/exiftool/files/Image-ExifTool-12.16.tar.gz
tar xvf Image-ExifTool-12.16.tar.gz
cd Image-ExifTool-12.16/
./exiftool t/images/ExifTool.jpg
To install it globally, make install the file.
Note: As it runs on Perl, you must have Perl installed on your Linux Distro.
perl Makefile.PL
make
make test
make install
You can now run ExifTool anywhere in your terminal by typing exiftool.
1. To extract the entire list of metadata from the file uses the following command.
exiftool <filename>
2. To extract the ids along with the Exif Tags in their Hexadecimal Format, run the above command with -H flag.
exiftool -H <filename>
3. ExifTool maintains the list of most common Exif Tags for a file, which could be viewed with the following flag.
exiftool --common <filename>
4. With ExifTool we can also extract the preview image or the thumbnail of an image file.
exiftool -PreviewImage [filename.jpg] > [Output.jpg]
exiftool -ThumbnailImage [filename.jpg] > [Output.jpg]
Example:
exiftool -b -PreviewImage CSM30803.CR2 > abc.jpg
-b to extract binary information and store the result in abc.jpg file
exiftool -b -ThumbnailImage CSM30803.CR2 > thumb.jpg
5. We can also generate extended information with verbose mode. This will display us the comprehensive data about the process that it is performing.
exiftool -v <filename>
To edit any meta-data we can use it’s corresponding Exif Tag to make the changes.
Note: We can only change the tags that are not write-protected.
exiftool -<Exif Tag>= “Geek Alert” <filename>
If we want to erase all the existing information within the meta tags of the file, we can use the following command . This command will remove all the Meta-Data from the file leaving all the basic or protected tag information.
exiftool -all= <filename>
We can save the output of the exiftool within another file (preferably a text file) to store the info for later use.
exiftool [filename] > [meta-data.txt]
cat <meta-data.txt>
We can combine the information from the metadata to solve variety of tasks. Suppose we have a lot of Images and we want to sort them into new folders and arrange them by year, month, or days, then we can use the following command:
The command copies the old images into directories based on their year and month.
exiftool -o '-Directory<CreateDate' -d ./newimage/%y/%y%m -r ./oldimage
-o make copies of all the images (hereafter referred to as old images) and make new images out of them
-Directory<CreateDate moves the images to their new destination folders using the Image Creation Date
./newimage/%y/%y%m is the relative path to the new directory, it follows the naming convention as year followed by subdirectory as year month.
-r is the recursively execute the command over the source folder
./oldimages is the source folder where original images are stored
Example:
To make a change in the current directory, move the image to directories.
exiftool '-Directory<CreateDate' -d %Y/%m-%d .
We can see the images are moved into a new folder with the year and then month-day subfolders.
Suppose you are working for a photography firm and you clicked photos for many events but the photos got mixed and now manually segregating each image will require a lot of wasted effort.
Here we will take advantage of the exiftool to segregate/ rename all the raw files present inside the current folder and it’s subfolder according to the exif tag of metadata Create Date and Time.
exiftool '-filename<CreateDate' -d %y%m%d-%H%M%S%%-03.c.%%e -r ./imagepath
-filename<CreateDate renames the raw images using image’s Creation Data & Time
-d sets the format for date/ time values
%y%m%d-%H%M%S%%-03.c.%%e is the format to rename the file.
For Example: This would rename a file taken on Feb 1, 2021, at 14:08 to 20210201-1408-000.xxx. The three zeros after the time are a copy number put there by %%-03.c in the date format.
While renaming files, copy number keeps on incremented until it finds a filename that does not exist yet.
.%%e keeps the original file name extension
Use .%%le (for renaming extension in lowercase) or .%%ue (for renaming in uppercase)
-r is the recursively execute the command over the source folder
./imagepath is the relative path to the directory with all your images to be renamed.
Example:
To make a change in current directory.
exiftool -d %Y-%m-%d_%H.%M.%S%%-c.%%e "-filename<CreateDate" .
ExifTool is a very powerful tool for manipulating file metadata. It got wide-ranging applications and with all those flags and options possibilities are endless.
Linux-Tools
Picked
Technical Scripter 2020
Linux-Unix
Technical Scripter
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": "\n11 Feb, 2021"
},
{
"code": null,
"e": 26059,
"s": 25651,
"text": "EXIF tool is a widely used meta-data information recorder built on Perl by Phil Harvey. It is one of a kind open-source tool which works on a variety of file types. EXIF stands for Exchangeable Image File Format, and it is mainly used for including metadata in various file types like txt, png, jpeg, pdf, HTML and many more. With EXIF tool we can also read, write and manipulate such meta-data information."
},
{
"code": null,
"e": 26154,
"s": 26059,
"text": "Exiftool is an open-source tool. The library is built with Platform Independent Perl library. "
},
{
"code": null,
"e": 26194,
"s": 26154,
"text": "1. Clone the git repo onto your system."
},
{
"code": null,
"e": 26245,
"s": 26194,
"text": "git clone https://github.com/exiftool/exiftool.git"
},
{
"code": null,
"e": 26305,
"s": 26245,
"text": "2. Test the tool with a test file present in the repository"
},
{
"code": null,
"e": 26350,
"s": 26305,
"text": "cd exiftool\n./exiftool t/images/ExifTool.jpg"
},
{
"code": null,
"e": 26401,
"s": 26350,
"text": "Alternatively, on Ubuntu distribution you can use:"
},
{
"code": null,
"e": 26441,
"s": 26401,
"text": "sudo apt install libimage-exiftool-perl"
},
{
"code": null,
"e": 26526,
"s": 26441,
"text": "Or simply use the following command it will automatically capture the above command."
},
{
"code": null,
"e": 26552,
"s": 26526,
"text": "sudo apt install exiftool"
},
{
"code": null,
"e": 26676,
"s": 26552,
"text": "For downloading directly from the Source, use the following commands. This will work for any Linux distro including CentOS."
},
{
"code": null,
"e": 26851,
"s": 26676,
"text": "wget https://sourceforge.net/projects/exiftool/files/Image-ExifTool-12.16.tar.gz\ntar xvf Image-ExifTool-12.16.tar.gz\ncd Image-ExifTool-12.16/\n./exiftool t/images/ExifTool.jpg"
},
{
"code": null,
"e": 26898,
"s": 26851,
"text": "To install it globally, make install the file."
},
{
"code": null,
"e": 26975,
"s": 26898,
"text": "Note: As it runs on Perl, you must have Perl installed on your Linux Distro."
},
{
"code": null,
"e": 27020,
"s": 26975,
"text": "perl Makefile.PL\nmake\nmake test\nmake install"
},
{
"code": null,
"e": 27091,
"s": 27020,
"text": "You can now run ExifTool anywhere in your terminal by typing exiftool."
},
{
"code": null,
"e": 27175,
"s": 27091,
"text": "1. To extract the entire list of metadata from the file uses the following command."
},
{
"code": null,
"e": 27196,
"s": 27175,
"text": "exiftool <filename>"
},
{
"code": null,
"e": 27308,
"s": 27196,
"text": "2. To extract the ids along with the Exif Tags in their Hexadecimal Format, run the above command with -H flag."
},
{
"code": null,
"e": 27331,
"s": 27308,
"text": "exiftool -H <filename>"
},
{
"code": null,
"e": 27446,
"s": 27331,
"text": "3. ExifTool maintains the list of most common Exif Tags for a file, which could be viewed with the following flag."
},
{
"code": null,
"e": 27475,
"s": 27446,
"text": "exiftool --common <filename>"
},
{
"code": null,
"e": 27565,
"s": 27475,
"text": "4. With ExifTool we can also extract the preview image or the thumbnail of an image file."
},
{
"code": null,
"e": 27673,
"s": 27565,
"text": "exiftool -PreviewImage [filename.jpg] > [Output.jpg]\nexiftool -ThumbnailImage [filename.jpg] > [Output.jpg]"
},
{
"code": null,
"e": 27682,
"s": 27673,
"text": "Example:"
},
{
"code": null,
"e": 27731,
"s": 27682,
"text": "exiftool -b -PreviewImage CSM30803.CR2 > abc.jpg"
},
{
"code": null,
"e": 27801,
"s": 27731,
"text": "-b to extract binary information and store the result in abc.jpg file"
},
{
"code": null,
"e": 27854,
"s": 27801,
"text": "exiftool -b -ThumbnailImage CSM30803.CR2 > thumb.jpg"
},
{
"code": null,
"e": 28003,
"s": 27854,
"text": "5. We can also generate extended information with verbose mode. This will display us the comprehensive data about the process that it is performing."
},
{
"code": null,
"e": 28026,
"s": 28003,
"text": "exiftool -v <filename>"
},
{
"code": null,
"e": 28108,
"s": 28026,
"text": "To edit any meta-data we can use it’s corresponding Exif Tag to make the changes."
},
{
"code": null,
"e": 28172,
"s": 28108,
"text": "Note: We can only change the tags that are not write-protected."
},
{
"code": null,
"e": 28220,
"s": 28172,
"text": "exiftool -<Exif Tag>= “Geek Alert” <filename>"
},
{
"code": null,
"e": 28447,
"s": 28220,
"text": "If we want to erase all the existing information within the meta tags of the file, we can use the following command . This command will remove all the Meta-Data from the file leaving all the basic or protected tag information."
},
{
"code": null,
"e": 28475,
"s": 28447,
"text": "exiftool -all= <filename>"
},
{
"code": null,
"e": 28592,
"s": 28475,
"text": "We can save the output of the exiftool within another file (preferably a text file) to store the info for later use."
},
{
"code": null,
"e": 28650,
"s": 28592,
"text": "exiftool [filename] > [meta-data.txt]\ncat <meta-data.txt>"
},
{
"code": null,
"e": 28881,
"s": 28650,
"text": "We can combine the information from the metadata to solve variety of tasks. Suppose we have a lot of Images and we want to sort them into new folders and arrange them by year, month, or days, then we can use the following command:"
},
{
"code": null,
"e": 28963,
"s": 28881,
"text": "The command copies the old images into directories based on their year and month."
},
{
"code": null,
"e": 29035,
"s": 28963,
"text": "exiftool -o '-Directory<CreateDate' -d ./newimage/%y/%y%m -r ./oldimage"
},
{
"code": null,
"e": 29138,
"s": 29035,
"text": "-o make copies of all the images (hereafter referred to as old images) and make new images out of them"
},
{
"code": null,
"e": 29240,
"s": 29138,
"text": "-Directory<CreateDate moves the images to their new destination folders using the Image Creation Date"
},
{
"code": null,
"e": 29383,
"s": 29240,
"text": "./newimage/%y/%y%m is the relative path to the new directory, it follows the naming convention as year followed by subdirectory as year month."
},
{
"code": null,
"e": 29448,
"s": 29383,
"text": "-r is the recursively execute the command over the source folder"
},
{
"code": null,
"e": 29514,
"s": 29448,
"text": "./oldimages is the source folder where original images are stored"
},
{
"code": null,
"e": 29523,
"s": 29514,
"text": "Example:"
},
{
"code": null,
"e": 29598,
"s": 29523,
"text": "To make a change in the current directory, move the image to directories. "
},
{
"code": null,
"e": 29645,
"s": 29598,
"text": "exiftool '-Directory<CreateDate' -d %Y/%m-%d ."
},
{
"code": null,
"e": 29741,
"s": 29645,
"text": " We can see the images are moved into a new folder with the year and then month-day subfolders."
},
{
"code": null,
"e": 29930,
"s": 29741,
"text": "Suppose you are working for a photography firm and you clicked photos for many events but the photos got mixed and now manually segregating each image will require a lot of wasted effort. "
},
{
"code": null,
"e": 30126,
"s": 29930,
"text": "Here we will take advantage of the exiftool to segregate/ rename all the raw files present inside the current folder and it’s subfolder according to the exif tag of metadata Create Date and Time."
},
{
"code": null,
"e": 30201,
"s": 30126,
"text": "exiftool '-filename<CreateDate' -d %y%m%d-%H%M%S%%-03.c.%%e -r ./imagepath"
},
{
"code": null,
"e": 30280,
"s": 30201,
"text": "-filename<CreateDate renames the raw images using image’s Creation Data & Time"
},
{
"code": null,
"e": 30321,
"s": 30280,
"text": "-d sets the format for date/ time values"
},
{
"code": null,
"e": 30380,
"s": 30321,
"text": "%y%m%d-%H%M%S%%-03.c.%%e is the format to rename the file."
},
{
"code": null,
"e": 30566,
"s": 30380,
"text": "For Example: This would rename a file taken on Feb 1, 2021, at 14:08 to 20210201-1408-000.xxx. The three zeros after the time are a copy number put there by %%-03.c in the date format. "
},
{
"code": null,
"e": 30672,
"s": 30566,
"text": "While renaming files, copy number keeps on incremented until it finds a filename that does not exist yet."
},
{
"code": null,
"e": 30716,
"s": 30672,
"text": ".%%e keeps the original file name extension"
},
{
"code": null,
"e": 30801,
"s": 30716,
"text": "Use .%%le (for renaming extension in lowercase) or .%%ue (for renaming in uppercase)"
},
{
"code": null,
"e": 30866,
"s": 30801,
"text": "-r is the recursively execute the command over the source folder"
},
{
"code": null,
"e": 30952,
"s": 30866,
"text": "./imagepath is the relative path to the directory with all your images to be renamed."
},
{
"code": null,
"e": 30961,
"s": 30952,
"text": "Example:"
},
{
"code": null,
"e": 31000,
"s": 30961,
"text": "To make a change in current directory."
},
{
"code": null,
"e": 31063,
"s": 31000,
"text": "exiftool -d %Y-%m-%d_%H.%M.%S%%-c.%%e \"-filename<CreateDate\" ."
},
{
"code": null,
"e": 31225,
"s": 31063,
"text": "ExifTool is a very powerful tool for manipulating file metadata. It got wide-ranging applications and with all those flags and options possibilities are endless."
},
{
"code": null,
"e": 31237,
"s": 31225,
"text": "Linux-Tools"
},
{
"code": null,
"e": 31244,
"s": 31237,
"text": "Picked"
},
{
"code": null,
"e": 31268,
"s": 31244,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31279,
"s": 31268,
"text": "Linux-Unix"
},
{
"code": null,
"e": 31298,
"s": 31279,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31396,
"s": 31298,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31431,
"s": 31396,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 31465,
"s": 31431,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 31491,
"s": 31465,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 31520,
"s": 31491,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 31557,
"s": 31520,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 31594,
"s": 31557,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 31636,
"s": 31594,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 31662,
"s": 31636,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 31698,
"s": 31662,
"text": "uniq Command in LINUX with examples"
}
] |
C# | Default Constructor - GeeksforGeeks | 23 Jan, 2019
If you don’t provide a constructor for your class, C# creates one by default that instantiates the object and sets member variables to the default values as listed in the Default Values Table. Constructor without any parameters is called a default constructor. In other words, this type of constructor does not take parameters. The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class to different values.
The default constructor initializes:
All numeric fields in the class to zero.
All string and object fields to null.
Example 1:
// C# Program to illustrate the use// of Default Constructorusing System; namespace GFG { class multiplication{ int a, b; // default Constructor public multiplication() { a = 10; b = 5; } // Main Methodpublic static void Main() { // an object is created, // constructor is called multiplication obj = new multiplication(); Console.WriteLine(obj.a); Console.WriteLine(obj.b); Console.WriteLine("The result of multiplication is: " +(obj.a * obj.b));} }}
Output:
10
5
The result of multiplication is: 50
Example 2: In this example, the class Person does not have any constructors, in which case, a default constructor is automatically provided and the fields are initialized to their default values.
// C# Program to illustrate the use// of Default Constructorusing System; public class Person{ public int age; public string name;} // Driver Classclass TestPerson { // Main Methodstatic void Main() { // object creation Person pers = new Person(); Console.WriteLine("Name: {0}, Age: {1}", pers.name, pers.age); }}
Output:
Name: , Age: 0
Note: The output is so because a string is assigned to null by default and integers to 0.
CSharp-Basics
CSharp-OOP
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Lambda Expressions in C# | [
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 26073,
"s": 25547,
"text": "If you don’t provide a constructor for your class, C# creates one by default that instantiates the object and sets member variables to the default values as listed in the Default Values Table. Constructor without any parameters is called a default constructor. In other words, this type of constructor does not take parameters. The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class to different values."
},
{
"code": null,
"e": 26110,
"s": 26073,
"text": "The default constructor initializes:"
},
{
"code": null,
"e": 26151,
"s": 26110,
"text": "All numeric fields in the class to zero."
},
{
"code": null,
"e": 26189,
"s": 26151,
"text": "All string and object fields to null."
},
{
"code": null,
"e": 26200,
"s": 26189,
"text": "Example 1:"
},
{
"code": "// C# Program to illustrate the use// of Default Constructorusing System; namespace GFG { class multiplication{ int a, b; // default Constructor public multiplication() { a = 10; b = 5; } // Main Methodpublic static void Main() { // an object is created, // constructor is called multiplication obj = new multiplication(); Console.WriteLine(obj.a); Console.WriteLine(obj.b); Console.WriteLine(\"The result of multiplication is: \" +(obj.a * obj.b));} }}",
"e": 26775,
"s": 26200,
"text": null
},
{
"code": null,
"e": 26783,
"s": 26775,
"text": "Output:"
},
{
"code": null,
"e": 26825,
"s": 26783,
"text": "10\n5\nThe result of multiplication is: 50\n"
},
{
"code": null,
"e": 27021,
"s": 26825,
"text": "Example 2: In this example, the class Person does not have any constructors, in which case, a default constructor is automatically provided and the fields are initialized to their default values."
},
{
"code": "// C# Program to illustrate the use// of Default Constructorusing System; public class Person{ public int age; public string name;} // Driver Classclass TestPerson { // Main Methodstatic void Main() { // object creation Person pers = new Person(); Console.WriteLine(\"Name: {0}, Age: {1}\", pers.name, pers.age); }} ",
"e": 27365,
"s": 27021,
"text": null
},
{
"code": null,
"e": 27373,
"s": 27365,
"text": "Output:"
},
{
"code": null,
"e": 27389,
"s": 27373,
"text": "Name: , Age: 0\n"
},
{
"code": null,
"e": 27479,
"s": 27389,
"text": "Note: The output is so because a string is assigned to null by default and integers to 0."
},
{
"code": null,
"e": 27493,
"s": 27479,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 27504,
"s": 27493,
"text": "CSharp-OOP"
},
{
"code": null,
"e": 27511,
"s": 27504,
"text": "Picked"
},
{
"code": null,
"e": 27514,
"s": 27511,
"text": "C#"
},
{
"code": null,
"e": 27612,
"s": 27514,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27635,
"s": 27612,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27663,
"s": 27635,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27680,
"s": 27663,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27702,
"s": 27680,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27731,
"s": 27702,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 27771,
"s": 27731,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27794,
"s": 27771,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 27834,
"s": 27794,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27877,
"s": 27834,
"text": "C# | How to insert an element in an Array?"
}
] |
Tumor Detection using classification - Machine Learning and Python - GeeksforGeeks | 15 Sep, 2021
In this article, we will be making a project through Python language which will be using some Machine Learning Algorithms too. It will be an exciting one as after this project you will understand the concepts of using AI & ML with a scripting language. The following libraries/packages will be used in this project:
numpy: It’s a Python library that is employed for scientific computing. It contains among other things – a strong array object, mathematical and statistical tools for integrating with other language’s code i.e. C/C++ and Fortran code.
pandas: It’s a Python package providing fast, flexible, and expressive data structures designed to form working with “relational” or “labeled” data both easy and intuitive.
matplotlib: Matplotlib may be a plotting library for the Python programming language which produces 2D plots to render visualization and helps in exploring the info sets. matplotlib.pyplot could be a collection of command style functions that make matplotlib work like MATLAB.
searborn:. Seaborn is an open-source Python library built on top of matplotlib. It’s used for data visualization and exploratory data analysis. Seaborn works easily with dataframes and also the Pandas library.
Python3
# Checking for any warningimport warningswarnings.filterwarnings('ignore')
After this step we will install some dependencies: Dependencies are all the software components required by your project in order for it to work as intended and avoid runtime errors. We will be needing the numpy, pandas, matplotlib & seaborn libraries / dependencies. As we will need a CSV file to do the operations, for this project we will be using a CSV file that contains data for Tumor (brain disease). So in this project at last we will be able to predict whether a subject (candidate) has a potent chance of suffering from a Tumor or not?
Step 1: Pre-processing the Data:
Python3
# Importing dependenciesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # Including & Reading the CSV file:df = pd.read_csv("https://raw.githubusercontent.com/ingledarshan/AIML-B2/main/data.csv")
Now we will check that the CSV file has been read successfully or not? So we will use the head method: head() method is used to return top n (5 by default) rows of a data frame or series.
Python3
df.head()
Python3
# Check the names of all columnsdf.columns
So this command will fetch the column’s header names. The output will be this:
Now in order to understand the data set briefly by getting a quick overview of the data-set, we will use info() method. This method very well handles the exploratory analysis of the data-sets.
Python3
df.info()
Output for above command:
In the CSV file, there may be some blanked fields that can harm the project (that is they will hamper the prediction).
Python3
df['Unnamed: 32']
Output:
Now as we have successfully found the vacant spaces in the data set, so now we will remove them.
Python3
df = df.drop("Unnamed: 32", axis=1) # to check whether those values are# deletd or not:df.head() # also check the columns after this# process:df.columns df.drop('id', axis=1, inplace=True)# we can do this also: df = df.drop('id', axis=1) # To see the change, again go through# the columnsdf.columns
Now we will check the class type of the columns with the help of type() method. It returns the class type of the argument(object) passed as a parameter.
Python3
type(df.columns)
Output:
pandas.core.indexes.base.Index
We will be needing to traverse and sort the data by their columns, so we will save the columns in a variable.
Python3
l = list(df.columns)print(l)
Now we will access the data with different start points. Say we will categorize the columns from 1 to 11 in a variable named features_mean and so on.
Python3
features_mean = l[1:11] features_se = l[11:21] features_worst = l[21:]
Python3
df.head (2)
In the ‘Diagnosis’ column of the CSV file, there are two options one is M = Malignant & B = Begin which basically tells the stage of the Tumor. But the same we will verify from the code.
Python3
# To check what value does the Diagnosis field havedf['diagnosis'].unique()# M stands for Malignant, B stands for Begin
Output:
array(['M', 'B'], dtype=object)
So it verifies that there are only two values in the Diagnosis field.
Now in order to get a fair idea of how many cases are having malignant tumor and who are in the beginning stage, we will use the countplot() method.
Python3
sns.countplot(df['diagnosis'], label="Count",);
If we don’t have to see the graph for the values, then I can use a function that will return the numerical values of the occurrences.
Now we will be able to be using the shape() method. Shape returns the form of an array. The form could be a tuple of integers. These numbers tell the lengths of the corresponding array dimension. In other words: The “shape” of an array may be a tuple with the number of elements per axis (dimension). For instance, the form is adequate to (6, 3), i.e. we’ve got 6 lines and three columns.
Python3
df.shape
Output:
(539, 31)
which means that in the data set there are 539 lines and 31 columns.
As of now, we are ready with the to-be-processed dataset, so we will be able to be using describe( ) method which is employed to look at some basic statistical details like percentile, mean, std etc. of a knowledge frame or a series of numeric values.
Python3
# Summary of all numeric valuesdf.decsbibe()
After all, this stuff, we will be using the corr( ) method to find the correlation between different fields. Corr( ) is used to find the pairwise correlation of all columns in the data frame. Any nan values are automatically excluded. For any non-numeric data type columns in the data-frame, it is ignored.
Python3
# Correlation Plotcorr = df.corr()corr
This command will provide 30 rows * 30 columns table which will be having rows like radius_mean, texture_se and so on.
The command corr.shape( ) will return (30, 30). The next step is plotting the statistics via heatmap. A heatmap could even be a two-dimensional graphical representation of information where the individual values that are contained during a matrix are represented as colors. The seaborn package allows the creation of annotated heatmaps which can be changed a little by using Matplotlib tools as per the creator’s requirement.
Python3
# making a heatmapplt.figure(figsize=(14, 14))sns.heatmap(corr)
Again we will be checking the CSV data set in order to ensure that the columns are just fine and haven’t been affected by the operations.
Python3
df.head()
This will return a table through which one can be assured that the data set is well sorted or not. In the few next commands, we will be segregating the data.
Python3
df['diagnosis'] = df['diagnosis'].map({'M': 1, 'B': 0})df.head() df['diagnosis'].unique() X = df.drop('diagnosis', axis=1)X.head() y = df['diagnosis']y.head()
Note: As we have prepared a prediction model which can be used with any of the machine-learning model, so now we will use one by one show you the output of the prediction model with each of the machine learning algorithms.
Step 2: Test Checking or Training The Data set
Using Logistic Regression Model:
Python3
# divide the dataset into train and test setfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) df.shape# o/p: (569, 31) X_train.shape# o/p: (398, 30) X_test.shape# o/p: (171, 30) y_train.shape# o/p: (398,) y_test.shape# o/p: (171,) X_train.head(1)# will return the top 5 rows (if exists) ss = StandardScaler()X_train = ss.fit_transform(X_train)X_test = ss.transform(X_test) X_train
Output:
After doing the basic training of the model we can test this by using one of the Machine Learning Models. So we will be testing this by using Logistic Regression, Decision Tree Classifier, Random Forest Classifier and SVM.
Python3
# apply Logistic Regression from sklearn.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X_train, y_train) # implemented our model through logistic regressiony_pred = lr.predict(X_test)y_pred # array containing the actual outputy_test
Output:
To mathematically check to what extent the model has predicted the correct value:
Python3
from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_test, y_pred))
Output:
0.9883040935672515
Now let’s frame the results in the form of a table.
Python3
tempResults = pd.DataFrame({'Algorithm':['Logistic Regression Method'], 'Accuracy':[lr_acc]})results = pd.concat( [results, tempResults] )results = results[['Algorithm','Accuracy']]results
Output:
Using Decision Tree Model:
Python3
# apply Decision Tree Classifierfrom sklearn.metrics import accuracy_scorefrom sklearn.tree import DecisionTreeClassifierdtc = DecisionTreeClassifier()dtc.fit(X_train, y_train) y_pred = dtc.predict(X_test)y_pred print(accuracy_score(y_test, y_pred)) # Tabulating the resultstempResults = pd.DataFrame({'Algorithm': ['Decision tree Classifier Method'], 'Accuracy': [dtc_acc]})results = pd.concat([results, tempResults])results = results[['Algorithm', 'Accuracy']]results
Output:
Using Random Forest Model:
Python3
# apply Random Forest Classifierfrom sklearn.metrics import accuracy_scorefrom sklearn.ensemble import RandomForestClassifierrfc = RandomForestClassifier()rfc.fit(X_train, y_train) y_pred = rfc.predict(X_test)y_pred print(accuracy_score(y_test, y_pred)) # tabulating the resultstempResults = pd.DataFrame({'Algorithm': ['Random Forest Classifier Method'], 'Accuracy': [rfc_acc]}) results = pd.concat([results, tempResults])results = results[['Algorithm', 'Accuracy']]results
Output:
Using SVM:
Python3
# apply Support Vector Machinefrom sklearn import svmsvc = svm.SVC()svc.fit(X_train,y_train y_pred = svc.predict(X_test)y_pred from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_test, y_pred))
Output:
So now we can check that which model effectively produced a higher number of correct predictions through this table:
Python3
# Tabulating the resultstempResults = pd.DataFrame({'Algorithm': ['Support Vector Classifier Method'], 'Accuracy': [svc_acc]})results = pd.concat([results, tempResults])results = results[['Algorithm', 'Accuracy']]results
Output:
After going through the accuracy of the above-used machine learning algorithms, I can conclude that these algorithms will give the same output every time if the same data set is fed. I can also say that these algorithms majorly provide the same output of prediction accuracy even if the data set is changed.
From the above table, we can conclude that through SVM Model and Logistic Regression Model were the best-suited models for my project.
kapoorsagar226
gabaa406
Python-projects
Technical Scripter 2020
Machine Learning
Project
Python
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
SDE SHEET - A Complete Guide for SDE Preparation
Working with zip files in Python
XML parsing in Python
Python | Simple GUI calculator using Tkinter
Implementing Web Scraping in Python with BeautifulSoup | [
{
"code": null,
"e": 25613,
"s": 25585,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 25930,
"s": 25613,
"text": "In this article, we will be making a project through Python language which will be using some Machine Learning Algorithms too. It will be an exciting one as after this project you will understand the concepts of using AI & ML with a scripting language. The following libraries/packages will be used in this project:"
},
{
"code": null,
"e": 26165,
"s": 25930,
"text": "numpy: It’s a Python library that is employed for scientific computing. It contains among other things – a strong array object, mathematical and statistical tools for integrating with other language’s code i.e. C/C++ and Fortran code."
},
{
"code": null,
"e": 26338,
"s": 26165,
"text": "pandas: It’s a Python package providing fast, flexible, and expressive data structures designed to form working with “relational” or “labeled” data both easy and intuitive."
},
{
"code": null,
"e": 26615,
"s": 26338,
"text": "matplotlib: Matplotlib may be a plotting library for the Python programming language which produces 2D plots to render visualization and helps in exploring the info sets. matplotlib.pyplot could be a collection of command style functions that make matplotlib work like MATLAB."
},
{
"code": null,
"e": 26825,
"s": 26615,
"text": "searborn:. Seaborn is an open-source Python library built on top of matplotlib. It’s used for data visualization and exploratory data analysis. Seaborn works easily with dataframes and also the Pandas library."
},
{
"code": null,
"e": 26833,
"s": 26825,
"text": "Python3"
},
{
"code": "# Checking for any warningimport warningswarnings.filterwarnings('ignore')",
"e": 26908,
"s": 26833,
"text": null
},
{
"code": null,
"e": 27454,
"s": 26908,
"text": "After this step we will install some dependencies: Dependencies are all the software components required by your project in order for it to work as intended and avoid runtime errors. We will be needing the numpy, pandas, matplotlib & seaborn libraries / dependencies. As we will need a CSV file to do the operations, for this project we will be using a CSV file that contains data for Tumor (brain disease). So in this project at last we will be able to predict whether a subject (candidate) has a potent chance of suffering from a Tumor or not?"
},
{
"code": null,
"e": 27487,
"s": 27454,
"text": "Step 1: Pre-processing the Data:"
},
{
"code": null,
"e": 27495,
"s": 27487,
"text": "Python3"
},
{
"code": "# Importing dependenciesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # Including & Reading the CSV file:df = pd.read_csv(\"https://raw.githubusercontent.com/ingledarshan/AIML-B2/main/data.csv\")",
"e": 27733,
"s": 27495,
"text": null
},
{
"code": null,
"e": 27922,
"s": 27733,
"text": "Now we will check that the CSV file has been read successfully or not? So we will use the head method: head() method is used to return top n (5 by default) rows of a data frame or series. "
},
{
"code": null,
"e": 27930,
"s": 27922,
"text": "Python3"
},
{
"code": "df.head()",
"e": 27940,
"s": 27930,
"text": null
},
{
"code": null,
"e": 27953,
"s": 27945,
"text": "Python3"
},
{
"code": "# Check the names of all columnsdf.columns",
"e": 27996,
"s": 27953,
"text": null
},
{
"code": null,
"e": 28075,
"s": 27996,
"text": "So this command will fetch the column’s header names. The output will be this:"
},
{
"code": null,
"e": 28268,
"s": 28075,
"text": "Now in order to understand the data set briefly by getting a quick overview of the data-set, we will use info() method. This method very well handles the exploratory analysis of the data-sets."
},
{
"code": null,
"e": 28276,
"s": 28268,
"text": "Python3"
},
{
"code": "df.info()",
"e": 28286,
"s": 28276,
"text": null
},
{
"code": null,
"e": 28315,
"s": 28289,
"text": "Output for above command:"
},
{
"code": null,
"e": 28439,
"s": 28319,
"text": "In the CSV file, there may be some blanked fields that can harm the project (that is they will hamper the prediction). "
},
{
"code": null,
"e": 28449,
"s": 28441,
"text": "Python3"
},
{
"code": "df['Unnamed: 32']",
"e": 28467,
"s": 28449,
"text": null
},
{
"code": null,
"e": 28479,
"s": 28470,
"text": "Output: "
},
{
"code": null,
"e": 28580,
"s": 28483,
"text": "Now as we have successfully found the vacant spaces in the data set, so now we will remove them."
},
{
"code": null,
"e": 28590,
"s": 28582,
"text": "Python3"
},
{
"code": "df = df.drop(\"Unnamed: 32\", axis=1) # to check whether those values are# deletd or not:df.head() # also check the columns after this# process:df.columns df.drop('id', axis=1, inplace=True)# we can do this also: df = df.drop('id', axis=1) # To see the change, again go through# the columnsdf.columns",
"e": 28889,
"s": 28590,
"text": null
},
{
"code": null,
"e": 29043,
"s": 28889,
"text": "Now we will check the class type of the columns with the help of type() method. It returns the class type of the argument(object) passed as a parameter. "
},
{
"code": null,
"e": 29051,
"s": 29043,
"text": "Python3"
},
{
"code": "type(df.columns)",
"e": 29068,
"s": 29051,
"text": null
},
{
"code": null,
"e": 29079,
"s": 29071,
"text": "Output:"
},
{
"code": null,
"e": 29112,
"s": 29081,
"text": "pandas.core.indexes.base.Index"
},
{
"code": null,
"e": 29225,
"s": 29114,
"text": "We will be needing to traverse and sort the data by their columns, so we will save the columns in a variable. "
},
{
"code": null,
"e": 29235,
"s": 29227,
"text": "Python3"
},
{
"code": "l = list(df.columns)print(l)",
"e": 29264,
"s": 29235,
"text": null
},
{
"code": null,
"e": 29418,
"s": 29267,
"text": "Now we will access the data with different start points. Say we will categorize the columns from 1 to 11 in a variable named features_mean and so on. "
},
{
"code": null,
"e": 29428,
"s": 29420,
"text": "Python3"
},
{
"code": "features_mean = l[1:11] features_se = l[11:21] features_worst = l[21:]",
"e": 29499,
"s": 29428,
"text": null
},
{
"code": null,
"e": 29512,
"s": 29504,
"text": "Python3"
},
{
"code": "df.head (2)",
"e": 29524,
"s": 29512,
"text": null
},
{
"code": null,
"e": 29717,
"s": 29529,
"text": "In the ‘Diagnosis’ column of the CSV file, there are two options one is M = Malignant & B = Begin which basically tells the stage of the Tumor. But the same we will verify from the code. "
},
{
"code": null,
"e": 29727,
"s": 29719,
"text": "Python3"
},
{
"code": "# To check what value does the Diagnosis field havedf['diagnosis'].unique()# M stands for Malignant, B stands for Begin",
"e": 29847,
"s": 29727,
"text": null
},
{
"code": null,
"e": 29856,
"s": 29847,
"text": "Output: "
},
{
"code": null,
"e": 29888,
"s": 29856,
"text": "array(['M', 'B'], dtype=object)"
},
{
"code": null,
"e": 29958,
"s": 29888,
"text": "So it verifies that there are only two values in the Diagnosis field."
},
{
"code": null,
"e": 30108,
"s": 29958,
"text": "Now in order to get a fair idea of how many cases are having malignant tumor and who are in the beginning stage, we will use the countplot() method. "
},
{
"code": null,
"e": 30116,
"s": 30108,
"text": "Python3"
},
{
"code": "sns.countplot(df['diagnosis'], label=\"Count\",);",
"e": 30164,
"s": 30116,
"text": null
},
{
"code": null,
"e": 30304,
"s": 30169,
"text": "If we don’t have to see the graph for the values, then I can use a function that will return the numerical values of the occurrences. "
},
{
"code": null,
"e": 30697,
"s": 30308,
"text": "Now we will be able to be using the shape() method. Shape returns the form of an array. The form could be a tuple of integers. These numbers tell the lengths of the corresponding array dimension. In other words: The “shape” of an array may be a tuple with the number of elements per axis (dimension). For instance, the form is adequate to (6, 3), i.e. we’ve got 6 lines and three columns."
},
{
"code": null,
"e": 30707,
"s": 30699,
"text": "Python3"
},
{
"code": "df.shape",
"e": 30716,
"s": 30707,
"text": null
},
{
"code": null,
"e": 30728,
"s": 30719,
"text": "Output: "
},
{
"code": null,
"e": 30740,
"s": 30730,
"text": "(539, 31)"
},
{
"code": null,
"e": 30811,
"s": 30742,
"text": "which means that in the data set there are 539 lines and 31 columns."
},
{
"code": null,
"e": 31065,
"s": 30813,
"text": "As of now, we are ready with the to-be-processed dataset, so we will be able to be using describe( ) method which is employed to look at some basic statistical details like percentile, mean, std etc. of a knowledge frame or a series of numeric values."
},
{
"code": null,
"e": 31075,
"s": 31067,
"text": "Python3"
},
{
"code": "# Summary of all numeric valuesdf.decsbibe()",
"e": 31120,
"s": 31075,
"text": null
},
{
"code": null,
"e": 31429,
"s": 31120,
"text": "After all, this stuff, we will be using the corr( ) method to find the correlation between different fields. Corr( ) is used to find the pairwise correlation of all columns in the data frame. Any nan values are automatically excluded. For any non-numeric data type columns in the data-frame, it is ignored. "
},
{
"code": null,
"e": 31437,
"s": 31429,
"text": "Python3"
},
{
"code": "# Correlation Plotcorr = df.corr()corr",
"e": 31476,
"s": 31437,
"text": null
},
{
"code": null,
"e": 31598,
"s": 31479,
"text": "This command will provide 30 rows * 30 columns table which will be having rows like radius_mean, texture_se and so on."
},
{
"code": null,
"e": 32026,
"s": 31600,
"text": "The command corr.shape( ) will return (30, 30). The next step is plotting the statistics via heatmap. A heatmap could even be a two-dimensional graphical representation of information where the individual values that are contained during a matrix are represented as colors. The seaborn package allows the creation of annotated heatmaps which can be changed a little by using Matplotlib tools as per the creator’s requirement."
},
{
"code": null,
"e": 32036,
"s": 32028,
"text": "Python3"
},
{
"code": "# making a heatmapplt.figure(figsize=(14, 14))sns.heatmap(corr)",
"e": 32100,
"s": 32036,
"text": null
},
{
"code": null,
"e": 32238,
"s": 32100,
"text": "Again we will be checking the CSV data set in order to ensure that the columns are just fine and haven’t been affected by the operations."
},
{
"code": null,
"e": 32246,
"s": 32238,
"text": "Python3"
},
{
"code": "df.head()",
"e": 32256,
"s": 32246,
"text": null
},
{
"code": null,
"e": 32418,
"s": 32259,
"text": "This will return a table through which one can be assured that the data set is well sorted or not. In the few next commands, we will be segregating the data. "
},
{
"code": null,
"e": 32428,
"s": 32420,
"text": "Python3"
},
{
"code": "df['diagnosis'] = df['diagnosis'].map({'M': 1, 'B': 0})df.head() df['diagnosis'].unique() X = df.drop('diagnosis', axis=1)X.head() y = df['diagnosis']y.head()",
"e": 32587,
"s": 32428,
"text": null
},
{
"code": null,
"e": 32811,
"s": 32587,
"text": "Note: As we have prepared a prediction model which can be used with any of the machine-learning model, so now we will use one by one show you the output of the prediction model with each of the machine learning algorithms. "
},
{
"code": null,
"e": 32858,
"s": 32811,
"text": "Step 2: Test Checking or Training The Data set"
},
{
"code": null,
"e": 32891,
"s": 32858,
"text": "Using Logistic Regression Model:"
},
{
"code": null,
"e": 32899,
"s": 32891,
"text": "Python3"
},
{
"code": "# divide the dataset into train and test setfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) df.shape# o/p: (569, 31) X_train.shape# o/p: (398, 30) X_test.shape# o/p: (171, 30) y_train.shape# o/p: (398,) y_test.shape# o/p: (171,) X_train.head(1)# will return the top 5 rows (if exists) ss = StandardScaler()X_train = ss.fit_transform(X_train)X_test = ss.transform(X_test) X_train",
"e": 33403,
"s": 32899,
"text": null
},
{
"code": null,
"e": 33412,
"s": 33403,
"text": "Output: "
},
{
"code": null,
"e": 33635,
"s": 33412,
"text": "After doing the basic training of the model we can test this by using one of the Machine Learning Models. So we will be testing this by using Logistic Regression, Decision Tree Classifier, Random Forest Classifier and SVM."
},
{
"code": null,
"e": 33643,
"s": 33635,
"text": "Python3"
},
{
"code": "# apply Logistic Regression from sklearn.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X_train, y_train) # implemented our model through logistic regressiony_pred = lr.predict(X_test)y_pred # array containing the actual outputy_test",
"e": 33900,
"s": 33643,
"text": null
},
{
"code": null,
"e": 33908,
"s": 33900,
"text": "Output:"
},
{
"code": null,
"e": 33990,
"s": 33908,
"text": "To mathematically check to what extent the model has predicted the correct value:"
},
{
"code": null,
"e": 33998,
"s": 33990,
"text": "Python3"
},
{
"code": "from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_test, y_pred))",
"e": 34078,
"s": 33998,
"text": null
},
{
"code": null,
"e": 34090,
"s": 34081,
"text": "Output: "
},
{
"code": null,
"e": 34111,
"s": 34092,
"text": "0.9883040935672515"
},
{
"code": null,
"e": 34166,
"s": 34113,
"text": "Now let’s frame the results in the form of a table. "
},
{
"code": null,
"e": 34176,
"s": 34168,
"text": "Python3"
},
{
"code": "tempResults = pd.DataFrame({'Algorithm':['Logistic Regression Method'], 'Accuracy':[lr_acc]})results = pd.concat( [results, tempResults] )results = results[['Algorithm','Accuracy']]results",
"e": 34365,
"s": 34176,
"text": null
},
{
"code": null,
"e": 34376,
"s": 34368,
"text": "Output:"
},
{
"code": null,
"e": 34405,
"s": 34378,
"text": "Using Decision Tree Model:"
},
{
"code": null,
"e": 34415,
"s": 34407,
"text": "Python3"
},
{
"code": "# apply Decision Tree Classifierfrom sklearn.metrics import accuracy_scorefrom sklearn.tree import DecisionTreeClassifierdtc = DecisionTreeClassifier()dtc.fit(X_train, y_train) y_pred = dtc.predict(X_test)y_pred print(accuracy_score(y_test, y_pred)) # Tabulating the resultstempResults = pd.DataFrame({'Algorithm': ['Decision tree Classifier Method'], 'Accuracy': [dtc_acc]})results = pd.concat([results, tempResults])results = results[['Algorithm', 'Accuracy']]results",
"e": 34912,
"s": 34415,
"text": null
},
{
"code": null,
"e": 34920,
"s": 34912,
"text": "Output:"
},
{
"code": null,
"e": 34947,
"s": 34920,
"text": "Using Random Forest Model:"
},
{
"code": null,
"e": 34955,
"s": 34947,
"text": "Python3"
},
{
"code": "# apply Random Forest Classifierfrom sklearn.metrics import accuracy_scorefrom sklearn.ensemble import RandomForestClassifierrfc = RandomForestClassifier()rfc.fit(X_train, y_train) y_pred = rfc.predict(X_test)y_pred print(accuracy_score(y_test, y_pred)) # tabulating the resultstempResults = pd.DataFrame({'Algorithm': ['Random Forest Classifier Method'], 'Accuracy': [rfc_acc]}) results = pd.concat([results, tempResults])results = results[['Algorithm', 'Accuracy']]results",
"e": 35457,
"s": 34955,
"text": null
},
{
"code": null,
"e": 35465,
"s": 35457,
"text": "Output:"
},
{
"code": null,
"e": 35476,
"s": 35465,
"text": "Using SVM:"
},
{
"code": null,
"e": 35484,
"s": 35476,
"text": "Python3"
},
{
"code": "# apply Support Vector Machinefrom sklearn import svmsvc = svm.SVC()svc.fit(X_train,y_train y_pred = svc.predict(X_test)y_pred from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_test, y_pred))",
"e": 35707,
"s": 35484,
"text": null
},
{
"code": null,
"e": 35718,
"s": 35710,
"text": "Output:"
},
{
"code": null,
"e": 35839,
"s": 35722,
"text": "So now we can check that which model effectively produced a higher number of correct predictions through this table:"
},
{
"code": null,
"e": 35849,
"s": 35841,
"text": "Python3"
},
{
"code": "# Tabulating the resultstempResults = pd.DataFrame({'Algorithm': ['Support Vector Classifier Method'], 'Accuracy': [svc_acc]})results = pd.concat([results, tempResults])results = results[['Algorithm', 'Accuracy']]results",
"e": 36097,
"s": 35849,
"text": null
},
{
"code": null,
"e": 36105,
"s": 36097,
"text": "Output:"
},
{
"code": null,
"e": 36413,
"s": 36105,
"text": "After going through the accuracy of the above-used machine learning algorithms, I can conclude that these algorithms will give the same output every time if the same data set is fed. I can also say that these algorithms majorly provide the same output of prediction accuracy even if the data set is changed."
},
{
"code": null,
"e": 36548,
"s": 36413,
"text": "From the above table, we can conclude that through SVM Model and Logistic Regression Model were the best-suited models for my project."
},
{
"code": null,
"e": 36563,
"s": 36548,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 36572,
"s": 36563,
"text": "gabaa406"
},
{
"code": null,
"e": 36588,
"s": 36572,
"text": "Python-projects"
},
{
"code": null,
"e": 36612,
"s": 36588,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 36629,
"s": 36612,
"text": "Machine Learning"
},
{
"code": null,
"e": 36637,
"s": 36629,
"text": "Project"
},
{
"code": null,
"e": 36644,
"s": 36637,
"text": "Python"
},
{
"code": null,
"e": 36663,
"s": 36644,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36680,
"s": 36663,
"text": "Machine Learning"
},
{
"code": null,
"e": 36778,
"s": 36680,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36819,
"s": 36778,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 36852,
"s": 36819,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 36880,
"s": 36852,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 36916,
"s": 36880,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 36971,
"s": 36916,
"text": "Convolutional Neural Network (CNN) in Machine Learning"
},
{
"code": null,
"e": 37020,
"s": 36971,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 37053,
"s": 37020,
"text": "Working with zip files in Python"
},
{
"code": null,
"e": 37075,
"s": 37053,
"text": "XML parsing in Python"
},
{
"code": null,
"e": 37120,
"s": 37075,
"text": "Python | Simple GUI calculator using Tkinter"
}
] |
Compressing and Decompressing files in Java - GeeksforGeeks | 10 Dec, 2016
DeflaterOutputStream and InflaterInputStream classes are provided in Java to compress and decompress the file contents. These classes provide useful methods that can be used for compressing the file content.
Compressing a File using DeflaterOutputStream
This class implements an output stream filter for compressing data in the “deflate” compression format. It is also used as the basis for other types of compression filters, such as GZIPOutputStream.
Important Methods:
void close() : Writes remaining compressed data to the output stream and closes the underlying stream.
protected void deflate() : Writes next block of compressed data to the output stream.
void finish() : Finishes writing compressed data to the output stream without closing the underlying stream.
void flush() : Flushes the compressed output stream.
void write(byte[] b, int off, int len) : Writes an array of bytes to the compressed output stream where off is the start offset of data and len is total number of bytes.
void write(int b) : Writes a byte to the compressed output stream.
Steps to compress a file(file 1)
Take an input file ‘file 1’ to FileInputStream for reading data.
Take the output file ‘file 2’ and assign it to FileOutputStream . This will help to write data into ‘file2’.
Assign FileOutputStream to DeflaterOutputStream for Compressing the data.
Now, read data from FileInputStream and write it into DeflaterOutputStream. It will compress the data and send it to FileOutputStream which stores the compressed data into the output file.
import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.Deflater;import java.util.zip.DeflaterOutputStream; class zip{ public static void main(String[] args) throws IOException { //Assign the original file : file to //FileInputStream for reading data FileInputStream fis=new FileInputStream("file1"); //Assign compressed file:file2 to FileOutputStream FileOutputStream fos=new FileOutputStream("file2"); //Assign FileOutputStream to DeflaterOutputStream DeflaterOutputStream dos=new DeflaterOutputStream(fos); //read data from FileInputStream and write it into DeflaterOutputStream int data; while ((data=fis.read())!=-1) { dos.write(data); } //close the file fis.close(); dos.close(); }}
Decompressing a File using InflaterInputStream
This class implements a stream filter for uncompressing data in the “deflate” compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream.
Important methods:
int available() : Returns 0 after EOF has been reached, otherwise always return 1.
void close() : Closes the input stream and releases any system resources associated with the stream.
protected void fill() : Fills input buffer with more data to decompress.
void mark(int readlimit) : Marks the current position in the input stream.
boolean markSupported() : Tests if the input stream supports the mark and reset methods.
int read() : Reads a byte of uncompressed data.
int read(byte[] b, int off, int len) : Reads decompressed data into an array of bytes to the compressed output stream where off is the start offset of data and len is total number of bytes.
void reset() : Re-positions this stream to the position at the time the mark method was last called on this input stream.
Steps to decompress a file
File with the name ‘file2’ now contains compressed data and we need to obtain original decompressed data from this file.
Assign the compressed file ‘file2’ to FileInputStream. This helps to read data from ‘file2’.
Assign the output file ‘file3’ to FileOutputStream. This will help to write uncompressed data into ‘file3’.
Now, read uncompressed data from InflaterInputStream and write it into FileOutputStream. This will write the uncompressed data to ‘file3’.
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.InflaterInputStream; //Uncompressing a file using an InflaterInputStreamclass unzip{ public static void main(String[] args) throws IOException { //assign Input File : file2 to FileInputStream for reading data FileInputStream fis=new FileInputStream("file2"); //assign output file: file3 to FileOutputStream for reading the data FileOutputStream fos=new FileOutputStream("file3"); //assign inflaterInputStream to FileInputStream for uncompressing the data InflaterInputStream iis=new InflaterInputStream(fis); //read data from inflaterInputStream and write it into FileOutputStream int data; while((data=iis.read())!=-1) { fos.write(data); } //close the files fos.close(); iis.close(); }}
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Multithreading in Java
Collections in Java
Initializing a List in Java | [
{
"code": null,
"e": 25619,
"s": 25591,
"text": "\n10 Dec, 2016"
},
{
"code": null,
"e": 25829,
"s": 25619,
"text": "DeflaterOutputStream and InflaterInputStream classes are provided in Java to compress and decompress the file contents. These classes provide useful methods that can be used for compressing the file content."
},
{
"code": null,
"e": 25875,
"s": 25829,
"text": "Compressing a File using DeflaterOutputStream"
},
{
"code": null,
"e": 26074,
"s": 25875,
"text": "This class implements an output stream filter for compressing data in the “deflate” compression format. It is also used as the basis for other types of compression filters, such as GZIPOutputStream."
},
{
"code": null,
"e": 26093,
"s": 26074,
"text": "Important Methods:"
},
{
"code": null,
"e": 26196,
"s": 26093,
"text": "void close() : Writes remaining compressed data to the output stream and closes the underlying stream."
},
{
"code": null,
"e": 26282,
"s": 26196,
"text": "protected void deflate() : Writes next block of compressed data to the output stream."
},
{
"code": null,
"e": 26391,
"s": 26282,
"text": "void finish() : Finishes writing compressed data to the output stream without closing the underlying stream."
},
{
"code": null,
"e": 26444,
"s": 26391,
"text": "void flush() : Flushes the compressed output stream."
},
{
"code": null,
"e": 26614,
"s": 26444,
"text": "void write(byte[] b, int off, int len) : Writes an array of bytes to the compressed output stream where off is the start offset of data and len is total number of bytes."
},
{
"code": null,
"e": 26681,
"s": 26614,
"text": "void write(int b) : Writes a byte to the compressed output stream."
},
{
"code": null,
"e": 26714,
"s": 26681,
"text": "Steps to compress a file(file 1)"
},
{
"code": null,
"e": 26779,
"s": 26714,
"text": "Take an input file ‘file 1’ to FileInputStream for reading data."
},
{
"code": null,
"e": 26888,
"s": 26779,
"text": "Take the output file ‘file 2’ and assign it to FileOutputStream . This will help to write data into ‘file2’."
},
{
"code": null,
"e": 26962,
"s": 26888,
"text": "Assign FileOutputStream to DeflaterOutputStream for Compressing the data."
},
{
"code": null,
"e": 27151,
"s": 26962,
"text": "Now, read data from FileInputStream and write it into DeflaterOutputStream. It will compress the data and send it to FileOutputStream which stores the compressed data into the output file."
},
{
"code": "import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.Deflater;import java.util.zip.DeflaterOutputStream; class zip{ public static void main(String[] args) throws IOException { //Assign the original file : file to //FileInputStream for reading data FileInputStream fis=new FileInputStream(\"file1\"); //Assign compressed file:file2 to FileOutputStream FileOutputStream fos=new FileOutputStream(\"file2\"); //Assign FileOutputStream to DeflaterOutputStream DeflaterOutputStream dos=new DeflaterOutputStream(fos); //read data from FileInputStream and write it into DeflaterOutputStream int data; while ((data=fis.read())!=-1) { dos.write(data); } //close the file fis.close(); dos.close(); }}",
"e": 28063,
"s": 27151,
"text": null
},
{
"code": null,
"e": 28110,
"s": 28063,
"text": "Decompressing a File using InflaterInputStream"
},
{
"code": null,
"e": 28295,
"s": 28110,
"text": "This class implements a stream filter for uncompressing data in the “deflate” compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream."
},
{
"code": null,
"e": 28314,
"s": 28295,
"text": "Important methods:"
},
{
"code": null,
"e": 28397,
"s": 28314,
"text": "int available() : Returns 0 after EOF has been reached, otherwise always return 1."
},
{
"code": null,
"e": 28498,
"s": 28397,
"text": "void close() : Closes the input stream and releases any system resources associated with the stream."
},
{
"code": null,
"e": 28571,
"s": 28498,
"text": "protected void fill() : Fills input buffer with more data to decompress."
},
{
"code": null,
"e": 28646,
"s": 28571,
"text": "void mark(int readlimit) : Marks the current position in the input stream."
},
{
"code": null,
"e": 28735,
"s": 28646,
"text": "boolean markSupported() : Tests if the input stream supports the mark and reset methods."
},
{
"code": null,
"e": 28783,
"s": 28735,
"text": "int read() : Reads a byte of uncompressed data."
},
{
"code": null,
"e": 28973,
"s": 28783,
"text": "int read(byte[] b, int off, int len) : Reads decompressed data into an array of bytes to the compressed output stream where off is the start offset of data and len is total number of bytes."
},
{
"code": null,
"e": 29095,
"s": 28973,
"text": "void reset() : Re-positions this stream to the position at the time the mark method was last called on this input stream."
},
{
"code": null,
"e": 29122,
"s": 29095,
"text": "Steps to decompress a file"
},
{
"code": null,
"e": 29243,
"s": 29122,
"text": "File with the name ‘file2’ now contains compressed data and we need to obtain original decompressed data from this file."
},
{
"code": null,
"e": 29336,
"s": 29243,
"text": "Assign the compressed file ‘file2’ to FileInputStream. This helps to read data from ‘file2’."
},
{
"code": null,
"e": 29444,
"s": 29336,
"text": "Assign the output file ‘file3’ to FileOutputStream. This will help to write uncompressed data into ‘file3’."
},
{
"code": null,
"e": 29583,
"s": 29444,
"text": "Now, read uncompressed data from InflaterInputStream and write it into FileOutputStream. This will write the uncompressed data to ‘file3’."
},
{
"code": "import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.InflaterInputStream; //Uncompressing a file using an InflaterInputStreamclass unzip{ public static void main(String[] args) throws IOException { //assign Input File : file2 to FileInputStream for reading data FileInputStream fis=new FileInputStream(\"file2\"); //assign output file: file3 to FileOutputStream for reading the data FileOutputStream fos=new FileOutputStream(\"file3\"); //assign inflaterInputStream to FileInputStream for uncompressing the data InflaterInputStream iis=new InflaterInputStream(fis); //read data from inflaterInputStream and write it into FileOutputStream int data; while((data=iis.read())!=-1) { fos.write(data); } //close the files fos.close(); iis.close(); }}",
"e": 30541,
"s": 29583,
"text": null
},
{
"code": null,
"e": 30845,
"s": 30543,
"text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30970,
"s": 30845,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30975,
"s": 30970,
"text": "Java"
},
{
"code": null,
"e": 30980,
"s": 30975,
"text": "Java"
},
{
"code": null,
"e": 31078,
"s": 30980,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31093,
"s": 31078,
"text": "Stream In Java"
},
{
"code": null,
"e": 31112,
"s": 31093,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31130,
"s": 31112,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31162,
"s": 31130,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31182,
"s": 31162,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31206,
"s": 31182,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 31238,
"s": 31206,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31261,
"s": 31238,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 31281,
"s": 31261,
"text": "Collections in Java"
}
] |
Parallel Coordinates Plot using Plotly in Python - 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.
Parallel coordinates plot is a common way of visualizing and analyzing high-dimensional datasets. A point in n-dimensional space is represented as a polyline with vertices on the parallel axes and the position of the vertex corresponds to the coordinate of the point.
Syntax: parallel_coordinates(data_frame=None, dimensions=None, labels={}, range_color=None)
Parameters:
data_frame: This argument needs to be passed for column names (and not keyword names) to be used.
dimensions: Either names of columns in data_frame, or pandas Series, or array_like objects Values from these columns are used for multidimensional visualization.
labels: By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed.
range_color: If provided, overrides auto-scaling on the continuous color scale.
Example 1:
Python3
import plotly.express as px df = px.data.tips()fig = px.parallel_coordinates( df, dimensions=['tip', 'total_bill', 'day','time'],) fig.show()
Output:
Example 2: Showing Parallel Coordinates Chart with go.Parcoords()
Python3
import plotly.graph_objects as go fig = go.Figure(data=go.Parcoords( line_color='green', dimensions=list([ dict(range=[4, 9], label='A', values=[5, 8]), dict(range=[2, 7], label='B', values=[3, 6]), ]))) fig.show()
Output:
Example 3:
Python3
import plotly.graph_objects as goimport plotly.express as px df = px.data.tips() fig = go.Figure(data=go.Parcoords( dimensions=list([ dict(range=[0, 8], constraintrange=[4, 8], label='Sepal Length', values=df['tip']), dict(range=[0, 8], label='Sepal Width', values=df['total_bill']), ]))) fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25841,
"s": 25537,
"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": 26109,
"s": 25841,
"text": "Parallel coordinates plot is a common way of visualizing and analyzing high-dimensional datasets. A point in n-dimensional space is represented as a polyline with vertices on the parallel axes and the position of the vertex corresponds to the coordinate of the point."
},
{
"code": null,
"e": 26202,
"s": 26109,
"text": " Syntax: parallel_coordinates(data_frame=None, dimensions=None, labels={}, range_color=None)"
},
{
"code": null,
"e": 26214,
"s": 26202,
"text": "Parameters:"
},
{
"code": null,
"e": 26313,
"s": 26214,
"text": "data_frame: This argument needs to be passed for column names (and not keyword names) to be used. "
},
{
"code": null,
"e": 26475,
"s": 26313,
"text": "dimensions: Either names of columns in data_frame, or pandas Series, or array_like objects Values from these columns are used for multidimensional visualization."
},
{
"code": null,
"e": 26748,
"s": 26475,
"text": "labels: By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed."
},
{
"code": null,
"e": 26828,
"s": 26748,
"text": "range_color: If provided, overrides auto-scaling on the continuous color scale."
},
{
"code": null,
"e": 26839,
"s": 26828,
"text": "Example 1:"
},
{
"code": null,
"e": 26847,
"s": 26839,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips()fig = px.parallel_coordinates( df, dimensions=['tip', 'total_bill', 'day','time'],) fig.show()",
"e": 26996,
"s": 26847,
"text": null
},
{
"code": null,
"e": 27004,
"s": 26996,
"text": "Output:"
},
{
"code": null,
"e": 27070,
"s": 27004,
"text": "Example 2: Showing Parallel Coordinates Chart with go.Parcoords()"
},
{
"code": null,
"e": 27078,
"s": 27070,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go fig = go.Figure(data=go.Parcoords( line_color='green', dimensions=list([ dict(range=[4, 9], label='A', values=[5, 8]), dict(range=[2, 7], label='B', values=[3, 6]), ]))) fig.show()",
"e": 27342,
"s": 27078,
"text": null
},
{
"code": null,
"e": 27350,
"s": 27342,
"text": "Output:"
},
{
"code": null,
"e": 27361,
"s": 27350,
"text": "Example 3:"
},
{
"code": null,
"e": 27369,
"s": 27361,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as goimport plotly.express as px df = px.data.tips() fig = go.Figure(data=go.Parcoords( dimensions=list([ dict(range=[0, 8], constraintrange=[4, 8], label='Sepal Length', values=df['tip']), dict(range=[0, 8], label='Sepal Width', values=df['total_bill']), ]))) fig.show()",
"e": 27730,
"s": 27369,
"text": null
},
{
"code": null,
"e": 27738,
"s": 27730,
"text": "Output:"
},
{
"code": null,
"e": 27752,
"s": 27738,
"text": "Python-Plotly"
},
{
"code": null,
"e": 27759,
"s": 27752,
"text": "Python"
},
{
"code": null,
"e": 27857,
"s": 27759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27889,
"s": 27857,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27931,
"s": 27889,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27973,
"s": 27931,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28000,
"s": 27973,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28056,
"s": 28000,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28078,
"s": 28056,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28117,
"s": 28078,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28148,
"s": 28117,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28177,
"s": 28148,
"text": "Create a directory in Python"
}
] |
HTTP headers | Content-Encoding - GeeksforGeeks | 23 Oct, 2019
The HTTP headers Content-encoding is used to compress the media type. It informers the server which encoding the user will supported. It sends the information to the Accept-encoding. The server selects any one of the proposals, uses it and informs the client of its choice with the Content-Encoding response header.Syntax:
Content-Encoding: gzip | compress | deflate | br| identity
Note: Multiple algorithms can also be applied.
Directives:
gzip: It uses Lempel-Ziv coding (LZ77), with a 32-bit CRC format. It is the original format of UNIX gzip program.
compress: It uses Lempel-Ziv-Welch (LZW) algorithm. Due to patent issue, many modern browsers don’t support this type of content-encoding.
deflate: This format uses zlib structure with deflate compression algorithm.
br: It is a compression format using the Brotli algorithm.
identity: It is used to indicate that there is no compression.
You can check how good your Accept-Encoding and Content-Encoding is working on this site.
Example:
Single Compression:Content-Encoding: gzip
Content-Encoding: compress
Content-Encoding: gzip
Content-Encoding: compress
Multiple Compression:Content-Encoding: gzip, compress
To check the Content-Encoding in action go to Inspect Element -> Network check the request header for Content-Encoding like below, Content-Encoding is highlighted you can see.Supported Browsers: The browsers compatible with HTTP headers Content-Encoding are listed below:Google ChromeInternet ExplorerFirefoxSafariOperaMy Personal Notes
arrow_drop_upSave
Content-Encoding: gzip, compress
To check the Content-Encoding in action go to Inspect Element -> Network check the request header for Content-Encoding like below, Content-Encoding is highlighted you can see.Supported Browsers: The browsers compatible with HTTP headers Content-Encoding are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
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
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method
How to apply style to parent if it has child with CSS?
How to Open URL in New Tab using JavaScript ?
How to execute PHP code using command line ? | [
{
"code": null,
"e": 25927,
"s": 25899,
"text": "\n23 Oct, 2019"
},
{
"code": null,
"e": 26250,
"s": 25927,
"text": "The HTTP headers Content-encoding is used to compress the media type. It informers the server which encoding the user will supported. It sends the information to the Accept-encoding. The server selects any one of the proposals, uses it and informs the client of its choice with the Content-Encoding response header.Syntax:"
},
{
"code": null,
"e": 26310,
"s": 26250,
"text": "Content-Encoding: gzip | compress | deflate | br| identity\n"
},
{
"code": null,
"e": 26357,
"s": 26310,
"text": "Note: Multiple algorithms can also be applied."
},
{
"code": null,
"e": 26369,
"s": 26357,
"text": "Directives:"
},
{
"code": null,
"e": 26483,
"s": 26369,
"text": "gzip: It uses Lempel-Ziv coding (LZ77), with a 32-bit CRC format. It is the original format of UNIX gzip program."
},
{
"code": null,
"e": 26622,
"s": 26483,
"text": "compress: It uses Lempel-Ziv-Welch (LZW) algorithm. Due to patent issue, many modern browsers don’t support this type of content-encoding."
},
{
"code": null,
"e": 26699,
"s": 26622,
"text": "deflate: This format uses zlib structure with deflate compression algorithm."
},
{
"code": null,
"e": 26758,
"s": 26699,
"text": "br: It is a compression format using the Brotli algorithm."
},
{
"code": null,
"e": 26821,
"s": 26758,
"text": "identity: It is used to indicate that there is no compression."
},
{
"code": null,
"e": 26911,
"s": 26821,
"text": "You can check how good your Accept-Encoding and Content-Encoding is working on this site."
},
{
"code": null,
"e": 26920,
"s": 26911,
"text": "Example:"
},
{
"code": null,
"e": 26990,
"s": 26920,
"text": "Single Compression:Content-Encoding: gzip\nContent-Encoding: compress\n"
},
{
"code": null,
"e": 27041,
"s": 26990,
"text": "Content-Encoding: gzip\nContent-Encoding: compress\n"
},
{
"code": null,
"e": 27450,
"s": 27041,
"text": "Multiple Compression:Content-Encoding: gzip, compress\nTo check the Content-Encoding in action go to Inspect Element -> Network check the request header for Content-Encoding like below, Content-Encoding is highlighted you can see.Supported Browsers: The browsers compatible with HTTP headers Content-Encoding are listed below:Google ChromeInternet ExplorerFirefoxSafariOperaMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 27484,
"s": 27450,
"text": "Content-Encoding: gzip, compress\n"
},
{
"code": null,
"e": 27756,
"s": 27484,
"text": "To check the Content-Encoding in action go to Inspect Element -> Network check the request header for Content-Encoding like below, Content-Encoding is highlighted you can see.Supported Browsers: The browsers compatible with HTTP headers Content-Encoding are listed below:"
},
{
"code": null,
"e": 27770,
"s": 27756,
"text": "Google Chrome"
},
{
"code": null,
"e": 27788,
"s": 27770,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27796,
"s": 27788,
"text": "Firefox"
},
{
"code": null,
"e": 27803,
"s": 27796,
"text": "Safari"
},
{
"code": null,
"e": 27809,
"s": 27803,
"text": "Opera"
},
{
"code": null,
"e": 27822,
"s": 27809,
"text": "HTTP-headers"
},
{
"code": null,
"e": 27829,
"s": 27822,
"text": "Picked"
},
{
"code": null,
"e": 27846,
"s": 27829,
"text": "Web Technologies"
},
{
"code": null,
"e": 27944,
"s": 27846,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27984,
"s": 27944,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28029,
"s": 27984,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28072,
"s": 28029,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28133,
"s": 28072,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28191,
"s": 28133,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28263,
"s": 28191,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28296,
"s": 28263,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 28351,
"s": 28296,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 28397,
"s": 28351,
"text": "How to Open URL in New Tab using JavaScript ?"
}
] |
SQUARE() Function in SQL Server - GeeksforGeeks | 28 Dec, 2020
SQUARE() function :This function in SQL Server is used to return the square of a specified number. For example, if the specified number is 9, this function will return 81 as output.
Features :
This function is used to square a given number.
This function accepts both that is positive and negative numbers.
This function also accepts fraction numbers.
This function always returns positive number.
This function use the formula “(a)2 = Returned value”, where a is the specified number.
Syntax :
SQUARE(number)
Parameter :This method accepts a parameter as given below as follows.
number –Specified number whose square is going to be returned.
Returns :It returns the square of a specified number.
Example-1 :Getting the result 16.0 which is the square of the specified number 4.
SELECT SQUARE(4);
Output :
16.0
Example-2 :Getting the result 4.0 which is the square of the specified negative number -2.
SELECT SQUARE(-2);
Output :
4.0
Example-3 :Getting the result 0.0 which is the square of the specified number zero (0).
SELECT SQUARE(0);
Output :
0.0
Example-4 :Getting the result 1.0 which is the square of the specified number 1.
SELECT SQUARE(1);
Output :
1.0
Example-5 :Getting the result 1.4399999999999999 which is the square of the specified number 1.2.
SELECT SQUARE(1.2);
Output :
1.4399999999999999
Application :This function is used to return the square of a specified number.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 25695,
"s": 25513,
"text": "SQUARE() function :This function in SQL Server is used to return the square of a specified number. For example, if the specified number is 9, this function will return 81 as output."
},
{
"code": null,
"e": 25706,
"s": 25695,
"text": "Features :"
},
{
"code": null,
"e": 25754,
"s": 25706,
"text": "This function is used to square a given number."
},
{
"code": null,
"e": 25820,
"s": 25754,
"text": "This function accepts both that is positive and negative numbers."
},
{
"code": null,
"e": 25865,
"s": 25820,
"text": "This function also accepts fraction numbers."
},
{
"code": null,
"e": 25911,
"s": 25865,
"text": "This function always returns positive number."
},
{
"code": null,
"e": 25999,
"s": 25911,
"text": "This function use the formula “(a)2 = Returned value”, where a is the specified number."
},
{
"code": null,
"e": 26008,
"s": 25999,
"text": "Syntax :"
},
{
"code": null,
"e": 26023,
"s": 26008,
"text": "SQUARE(number)"
},
{
"code": null,
"e": 26093,
"s": 26023,
"text": "Parameter :This method accepts a parameter as given below as follows."
},
{
"code": null,
"e": 26156,
"s": 26093,
"text": "number –Specified number whose square is going to be returned."
},
{
"code": null,
"e": 26210,
"s": 26156,
"text": "Returns :It returns the square of a specified number."
},
{
"code": null,
"e": 26292,
"s": 26210,
"text": "Example-1 :Getting the result 16.0 which is the square of the specified number 4."
},
{
"code": null,
"e": 26310,
"s": 26292,
"text": "SELECT SQUARE(4);"
},
{
"code": null,
"e": 26319,
"s": 26310,
"text": "Output :"
},
{
"code": null,
"e": 26324,
"s": 26319,
"text": "16.0"
},
{
"code": null,
"e": 26415,
"s": 26324,
"text": "Example-2 :Getting the result 4.0 which is the square of the specified negative number -2."
},
{
"code": null,
"e": 26434,
"s": 26415,
"text": "SELECT SQUARE(-2);"
},
{
"code": null,
"e": 26443,
"s": 26434,
"text": "Output :"
},
{
"code": null,
"e": 26447,
"s": 26443,
"text": "4.0"
},
{
"code": null,
"e": 26535,
"s": 26447,
"text": "Example-3 :Getting the result 0.0 which is the square of the specified number zero (0)."
},
{
"code": null,
"e": 26553,
"s": 26535,
"text": "SELECT SQUARE(0);"
},
{
"code": null,
"e": 26562,
"s": 26553,
"text": "Output :"
},
{
"code": null,
"e": 26566,
"s": 26562,
"text": "0.0"
},
{
"code": null,
"e": 26647,
"s": 26566,
"text": "Example-4 :Getting the result 1.0 which is the square of the specified number 1."
},
{
"code": null,
"e": 26665,
"s": 26647,
"text": "SELECT SQUARE(1);"
},
{
"code": null,
"e": 26674,
"s": 26665,
"text": "Output :"
},
{
"code": null,
"e": 26678,
"s": 26674,
"text": "1.0"
},
{
"code": null,
"e": 26776,
"s": 26678,
"text": "Example-5 :Getting the result 1.4399999999999999 which is the square of the specified number 1.2."
},
{
"code": null,
"e": 26796,
"s": 26776,
"text": "SELECT SQUARE(1.2);"
},
{
"code": null,
"e": 26805,
"s": 26796,
"text": "Output :"
},
{
"code": null,
"e": 26824,
"s": 26805,
"text": "1.4399999999999999"
},
{
"code": null,
"e": 26903,
"s": 26824,
"text": "Application :This function is used to return the square of a specified number."
},
{
"code": null,
"e": 26912,
"s": 26903,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26923,
"s": 26912,
"text": "SQL-Server"
},
{
"code": null,
"e": 26927,
"s": 26923,
"text": "SQL"
},
{
"code": null,
"e": 26931,
"s": 26927,
"text": "SQL"
},
{
"code": null,
"e": 27029,
"s": 26931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27095,
"s": 27029,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27110,
"s": 27095,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27167,
"s": 27110,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27199,
"s": 27167,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27277,
"s": 27199,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27313,
"s": 27277,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27330,
"s": 27313,
"text": "SQL using Python"
},
{
"code": null,
"e": 27396,
"s": 27330,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 27458,
"s": 27396,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
MATLAB Syntax - GeeksforGeeks | 05 Oct, 2021
Writing code in the MATLAB environment is quite simple. We do not need to include any libraries/header files, we can directly start writing commands in the command window of the Editor. Usually, we write small and easily executable programs in the Command Window and larger programs with multiple lines and functions in the Editor.
Now, we will see the syntax of a MATLAB program. Let us begin with the very basic code to display ‘Hello World’ as the output in the command window:
Example:
Matlab
% A MATLAB program illustrate% disp functiondisp("Hello World")
Here, disp() is a function used to display the desired value as the output.
Output:
Likewise, we can perform any basic operation in the command window. Let’s have a look at a few of them.
Example :
Matlab
% Adding two numbers in the% MATLAB Command Window15 + 25
Output :
In the above output, ‘ans’ is a default variable in MATLAB that stores the value of the most recent output. This variable is only created when output is generated without any specific argument to it.
Example:
Matlab
% MATLAB code for multiplying two numbers% in MATLAB Command Window20 * 5
Output :
Thus, we can perform various mathematical operations in the MATLAB command window. The following table summarizes the various operations along with their syntax that can be performed in MATLAB:
Declaring Variables in MATLAB is fairly simple. We just need to write a valid name for the variable followed by an equal sign (‘=’). The naming of variables is discussed further in this article. In MATLAB, we need not explicitly mention the type of variable while declaring it,
a=7 %declares an integer variable and assigns it the value 7
b=9.81 %declares a float (decimal) variable and assigns it the value 9.81
c = [1,2,3] %declares an array and assigns it the values 1, 2 and 3
d=a = [1,2,3;4,5,6;7,8,9] %declares a 2-D array and assigns it the values 1,2,3,4,5,6,7,8 and9
The rules for naming a variable in MATLAB are as follows:
A variable name must begin with a letter which may be followed by letters, digits, or underscores (no other special character allowed).
MATLAB is case-sensitive which means that upper and lower case letters are considered different. (‘GeeksForGeeks’ and ‘geeksforgeeks’ are considered separate variable names)
Avoid giving variables the same name as that of existing MATLAB functions.
Unlike many programming languages, every statement/expression in MATLAB need not necessarily end with a semicolon. However, in MATLAB, a semicolon is used at the end of a statement to restrict the result of the statement from being displayed in the output.
Let us understand this with a few examples:
Example:
Matlab
% MATLAB code to assign values% to two variables and display% their sum (without the use of% any semicolon)a=2b=3c=a+b
Output:
In the above code, although we didn’t write any explicit statement to print the value stored in the variable a, b and c, yet the values of a, b and c is displayed as the output by default.
Example:
Matlab
% MATLAB code to assign values% to two variables and display% their sum (with the use of% semicolon)a = 2;b = 3;c = a+b
Output:
We can observe that this time the output of the statements ending with a semicolon (a=2; and b=3;) are not displayed as the output. Hence, a semicolon can be used in MATLAB to restrict the result of the statement from being displayed in the output.
Note: A semicolon does not restrict the output from being displayed when put at the end of a statement that is specifically meant to print output.
Example:
Matlab
% MATLAB code to disp function %% (with the use of semicolon) % disp('Learning with Geeks for Geeks');
Output:
Adding comments to code is always considered a good practice. Comments are statements or annotations written within the source code to make the code easier for humans to understand. Comments are simply ignored at the time of compilation/execution.
MATLAB provides two types of comments:
Single-Line Comments
Multi-Line Comments
Single-Line Comments: They are denoted by ‘%’ (percentage sign). It implies that the comment is applied to a single line only which means that everything following ‘%’ in a line is a comment and thus not executed.
Multi-Line Comments: They are denoted by ‘%{‘ (percentage sign and opening curly bracket) and ‘%}’ (percentage sign and closing curly bracket). Everything is written between ‘%{‘ and ‘%}’ is a comment and thus not executed.
In order to save a MATLAB script, go to the editor tab and click ‘save as’, and then provide your script with an appropriate name. The scripts written in MATLAB are stored with the ‘.m’ extension.
abhishek0719kadiyan
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Forward and Inverse Fourier Transform of an Image in MATLAB
Boundary Extraction of image using MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Classes and Object in MATLAB
Double Integral in MATLAB
Adaptive Histogram Equalization in Image Processing Using MATLAB
What are different types of denoising filters in MATLAB? | [
{
"code": null,
"e": 25885,
"s": 25857,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 26217,
"s": 25885,
"text": "Writing code in the MATLAB environment is quite simple. We do not need to include any libraries/header files, we can directly start writing commands in the command window of the Editor. Usually, we write small and easily executable programs in the Command Window and larger programs with multiple lines and functions in the Editor."
},
{
"code": null,
"e": 26366,
"s": 26217,
"text": "Now, we will see the syntax of a MATLAB program. Let us begin with the very basic code to display ‘Hello World’ as the output in the command window:"
},
{
"code": null,
"e": 26375,
"s": 26366,
"text": "Example:"
},
{
"code": null,
"e": 26382,
"s": 26375,
"text": "Matlab"
},
{
"code": "% A MATLAB program illustrate% disp functiondisp(\"Hello World\")",
"e": 26446,
"s": 26382,
"text": null
},
{
"code": null,
"e": 26523,
"s": 26446,
"text": " Here, disp() is a function used to display the desired value as the output."
},
{
"code": null,
"e": 26532,
"s": 26523,
"text": "Output: "
},
{
"code": null,
"e": 26637,
"s": 26532,
"text": "Likewise, we can perform any basic operation in the command window. Let’s have a look at a few of them. "
},
{
"code": null,
"e": 26647,
"s": 26637,
"text": "Example :"
},
{
"code": null,
"e": 26654,
"s": 26647,
"text": "Matlab"
},
{
"code": "% Adding two numbers in the% MATLAB Command Window15 + 25",
"e": 26712,
"s": 26654,
"text": null
},
{
"code": null,
"e": 26723,
"s": 26712,
"text": " Output : "
},
{
"code": null,
"e": 26924,
"s": 26723,
"text": "In the above output, ‘ans’ is a default variable in MATLAB that stores the value of the most recent output. This variable is only created when output is generated without any specific argument to it. "
},
{
"code": null,
"e": 26934,
"s": 26924,
"text": "Example: "
},
{
"code": null,
"e": 26941,
"s": 26934,
"text": "Matlab"
},
{
"code": "% MATLAB code for multiplying two numbers% in MATLAB Command Window20 * 5",
"e": 27015,
"s": 26941,
"text": null
},
{
"code": null,
"e": 27026,
"s": 27015,
"text": " Output : "
},
{
"code": null,
"e": 27221,
"s": 27026,
"text": "Thus, we can perform various mathematical operations in the MATLAB command window. The following table summarizes the various operations along with their syntax that can be performed in MATLAB:"
},
{
"code": null,
"e": 27499,
"s": 27221,
"text": "Declaring Variables in MATLAB is fairly simple. We just need to write a valid name for the variable followed by an equal sign (‘=’). The naming of variables is discussed further in this article. In MATLAB, we need not explicitly mention the type of variable while declaring it,"
},
{
"code": null,
"e": 27591,
"s": 27499,
"text": "a=7 %declares an integer variable and assigns it the value 7"
},
{
"code": null,
"e": 27692,
"s": 27591,
"text": "b=9.81 %declares a float (decimal) variable and assigns it the value 9.81"
},
{
"code": null,
"e": 27782,
"s": 27692,
"text": "c = [1,2,3] %declares an array and assigns it the values 1, 2 and 3"
},
{
"code": null,
"e": 27878,
"s": 27782,
"text": "d=a = [1,2,3;4,5,6;7,8,9] %declares a 2-D array and assigns it the values 1,2,3,4,5,6,7,8 and9"
},
{
"code": null,
"e": 27936,
"s": 27878,
"text": "The rules for naming a variable in MATLAB are as follows:"
},
{
"code": null,
"e": 28072,
"s": 27936,
"text": "A variable name must begin with a letter which may be followed by letters, digits, or underscores (no other special character allowed)."
},
{
"code": null,
"e": 28246,
"s": 28072,
"text": "MATLAB is case-sensitive which means that upper and lower case letters are considered different. (‘GeeksForGeeks’ and ‘geeksforgeeks’ are considered separate variable names)"
},
{
"code": null,
"e": 28321,
"s": 28246,
"text": "Avoid giving variables the same name as that of existing MATLAB functions."
},
{
"code": null,
"e": 28578,
"s": 28321,
"text": "Unlike many programming languages, every statement/expression in MATLAB need not necessarily end with a semicolon. However, in MATLAB, a semicolon is used at the end of a statement to restrict the result of the statement from being displayed in the output."
},
{
"code": null,
"e": 28622,
"s": 28578,
"text": "Let us understand this with a few examples:"
},
{
"code": null,
"e": 28633,
"s": 28622,
"text": "Example: "
},
{
"code": null,
"e": 28640,
"s": 28633,
"text": "Matlab"
},
{
"code": "% MATLAB code to assign values% to two variables and display% their sum (without the use of% any semicolon)a=2b=3c=a+b",
"e": 28759,
"s": 28640,
"text": null
},
{
"code": null,
"e": 28767,
"s": 28759,
"text": "Output:"
},
{
"code": null,
"e": 28956,
"s": 28767,
"text": "In the above code, although we didn’t write any explicit statement to print the value stored in the variable a, b and c, yet the values of a, b and c is displayed as the output by default."
},
{
"code": null,
"e": 28966,
"s": 28956,
"text": "Example: "
},
{
"code": null,
"e": 28973,
"s": 28966,
"text": "Matlab"
},
{
"code": "% MATLAB code to assign values% to two variables and display% their sum (with the use of% semicolon)a = 2;b = 3;c = a+b",
"e": 29093,
"s": 28973,
"text": null
},
{
"code": null,
"e": 29103,
"s": 29093,
"text": " Output: "
},
{
"code": null,
"e": 29352,
"s": 29103,
"text": "We can observe that this time the output of the statements ending with a semicolon (a=2; and b=3;) are not displayed as the output. Hence, a semicolon can be used in MATLAB to restrict the result of the statement from being displayed in the output."
},
{
"code": null,
"e": 29499,
"s": 29352,
"text": "Note: A semicolon does not restrict the output from being displayed when put at the end of a statement that is specifically meant to print output."
},
{
"code": null,
"e": 29509,
"s": 29499,
"text": "Example: "
},
{
"code": null,
"e": 29516,
"s": 29509,
"text": "Matlab"
},
{
"code": "% MATLAB code to disp function %% (with the use of semicolon) % disp('Learning with Geeks for Geeks');",
"e": 29619,
"s": 29516,
"text": null
},
{
"code": null,
"e": 29629,
"s": 29619,
"text": " Output: "
},
{
"code": null,
"e": 29877,
"s": 29629,
"text": "Adding comments to code is always considered a good practice. Comments are statements or annotations written within the source code to make the code easier for humans to understand. Comments are simply ignored at the time of compilation/execution."
},
{
"code": null,
"e": 29917,
"s": 29877,
"text": "MATLAB provides two types of comments: "
},
{
"code": null,
"e": 29940,
"s": 29917,
"text": "Single-Line Comments "
},
{
"code": null,
"e": 29960,
"s": 29940,
"text": "Multi-Line Comments"
},
{
"code": null,
"e": 30174,
"s": 29960,
"text": "Single-Line Comments: They are denoted by ‘%’ (percentage sign). It implies that the comment is applied to a single line only which means that everything following ‘%’ in a line is a comment and thus not executed."
},
{
"code": null,
"e": 30398,
"s": 30174,
"text": "Multi-Line Comments: They are denoted by ‘%{‘ (percentage sign and opening curly bracket) and ‘%}’ (percentage sign and closing curly bracket). Everything is written between ‘%{‘ and ‘%}’ is a comment and thus not executed."
},
{
"code": null,
"e": 30596,
"s": 30398,
"text": "In order to save a MATLAB script, go to the editor tab and click ‘save as’, and then provide your script with an appropriate name. The scripts written in MATLAB are stored with the ‘.m’ extension. "
},
{
"code": null,
"e": 30618,
"s": 30598,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 30625,
"s": 30618,
"text": "Picked"
},
{
"code": null,
"e": 30632,
"s": 30625,
"text": "MATLAB"
},
{
"code": null,
"e": 30730,
"s": 30632,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30790,
"s": 30730,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 30832,
"s": 30790,
"text": "Boundary Extraction of image using MATLAB"
},
{
"code": null,
"e": 30905,
"s": 30832,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 30970,
"s": 30905,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 31010,
"s": 30970,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 31071,
"s": 31010,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
},
{
"code": null,
"e": 31100,
"s": 31071,
"text": "Classes and Object in MATLAB"
},
{
"code": null,
"e": 31126,
"s": 31100,
"text": "Double Integral in MATLAB"
},
{
"code": null,
"e": 31191,
"s": 31126,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
}
] |
Insert multiple rows in a single MySQL query | Let us first create a table −
mysql> create table DemoTable1384
-> (
-> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentName varchar(20),
-> StudentAge int
-> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command. Here, we are inserting multiple rows in a single query −
mysql> insert into DemoTable1384(StudentName,StudentAge) values('Chris Brown',21),('David Miller',22),
-> ('Carol Taylor',19),('Adam Smith',23);
Query OK, 4 rows affected (0.11 sec)
Records: 4 Duplicates: 0 Warnings: 0
Display all records from the table using select statement −
mysql> select * from DemoTable1384;
This will produce the following output −
+-----------+--------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+--------------+------------+
| 1 | Chris Brown | 21 |
| 2 | David Miller | 22 |
| 3 | Carol Taylor | 19 |
| 4 | Adam Smith | 23 |
+-----------+--------------+------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1289,
"s": 1092,
"text": "mysql> create table DemoTable1384\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentName varchar(20),\n -> StudentAge int\n -> );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1401,
"s": 1289,
"text": "Insert some records in the table using insert command. Here, we are inserting multiple rows in a single query −"
},
{
"code": null,
"e": 1622,
"s": 1401,
"text": "mysql> insert into DemoTable1384(StudentName,StudentAge) values('Chris Brown',21),('David Miller',22),\n-> ('Carol Taylor',19),('Adam Smith',23);\nQuery OK, 4 rows affected (0.11 sec)\nRecords: 4 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 1682,
"s": 1622,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1718,
"s": 1682,
"text": "mysql> select * from DemoTable1384;"
},
{
"code": null,
"e": 1759,
"s": 1718,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2120,
"s": 1759,
"text": "+-----------+--------------+------------+\n| StudentId | StudentName | StudentAge |\n+-----------+--------------+------------+\n| 1 | Chris Brown | 21 |\n| 2 | David Miller | 22 |\n| 3 | Carol Taylor | 19 |\n| 4 | Adam Smith | 23 |\n+-----------+--------------+------------+\n4 rows in set (0.00 sec)"
}
] |
Decomposing Signal Using Empirical Mode Decomposition — Algorithm Explanation for Dummy | by Muhammad Ryan | Towards Data Science | What kind of ‘beast’ is Empirical Mode Decomposition (EMD) is? It’s an algorithm to decompose signals. And when I say signal, what I mean is a time-series data. We inputting a signal to the EMD and we will get some decomposed signal a.k.a ‘basic ingredient’ of our signal input. It’s similar to the Fast Fourier Transform (FFT). FFT assumes our signal is periodic and it’s ‘basic ingredient’ is various simple sine waves. In FFT, our signal is changed from the time spectrum to the frequency spectrum.
The different with EMD is the output remains in the time spectrum and EMD does not assume our signal is periodic and it’s not based on simple sine wave instead, it’s Intrinsic Mode Function (IMF). EMD is really based on the dataset, doesn’t have an assumption about the data (That why it’s called Empirical). IMF is a wave that obeying 2 properties:
The difference number of maxima and minima at most by 1. Maxima is a peak of wave and minima is a valley.
The difference number of maxima and minima at most by 1. Maxima is a peak of wave and minima is a valley.
Assume our dataset has been standardized using
Then maxima not always above zero and minima not always below zero. Maxima is the value of the signal where when the trend in the signal continues to go up then suddenly go down, the value right before the value goes down is maxima. On the other hand, Minima is when the trend in the signal continues to go down then suddenly go up, the value right before goes up is minima.
2. The Mean of the wave of IMF is zero.
A simple sine wave is an IMF (The difference between minima and maxima is at most by 1 ✓, The mean of the dataset is zero ✓).
>>> import numpy as np>>> frequency = 1>>> total_time = 1>>> res = 0.01>>> time = np.arange(0, total_time, res)>>> amplitude = np.sin(2 * np.pi * frequency * total_time * (time/time[-1]))>>> np.mean(amplitude)-2.6319088627735572e-17 #this value literally equal 0
But an IMF can have more than 1 frequency and more complex.
To make it more easy for us to understand the algorithm, here I present a toy test signal.
This signal (1 Hz sine wave)
and this (4 Hz sine wave)
are combined become this
Voila, we will try to decompose this signal trough this step by step algorithm explanation.
Here the algorithm of EMD.
Step 1, Find the Minima and Maxima.
Step 2, create an envelope of minima and maxima from the array of minima and maxima. Interpolate the value of minima and maxima to create an envelope of minima and maxima using a cubic spline.
Step 4, from the envelope of minima and maxima, get the middle value.
Step 5, decrease the value of the real toy test signal by the middle value of the envelope.
If you look closely, this is our 4 Hz sine wave successfully extracted. But looks like there is some error like a sudden leap on both sides of the wave. This has come from the error of the interpolation of the cubic spline. The interpolation of the cubic spline becomes so bad at the beginning and the end of the signal. The solution is we must define a boundary condition. What I mean about boundary condition is we must define the envelope of minima and maxima at the beginning and the end of the signal before doing the cubic spline. In this article, the envelope of minima and maxima of the beginning and the end of the signal is the same as with the nearest maxima and minima from them. Let’s restart it from step 1 to step 5 but this time, we define the boundary condition.
Ouch, this time the error is affected the entire extracted signal. But the sudden leap has vanished.
Step 6, Check if this extracted signal is an IMF.
#here is the ouput of python scriptmean: -0.002681745482482584 Total minima 20 Total maxima 21
The mean is nearly zero, I think we can ignore it and round it to zero. The number of Minima and Maxima also fulfill the requirement, we get an IMF. If you are not satisfied with the mean of the extracted signal, you can process it 1 more time following step 2 — step 6. But this time, instead of inputting a real toy test signal, we use that extracted signal. This the route of the algorithm when in the first or second or so on triest, the extracted signal not satisfied IMF condition. To make it more simple, let’s just admit the signal is an IMF.
Step 7, decrease the original toy test signal with this IMF.
Woah, we get our 1 Hz signal (but as we thought, the beginning and the end is wrong). It looks like we success to decompose our fused signal. But, the condition to stop in the algorithm of EMD is when our residuum signal is just a constant, monotonic, or just have 1 extremum (just have 1 minima or maxima). Our signal which we have reduced by the IMF before is called residuum. Let’s continue the process.
mean: -0.002681745482482584 Total minima 6 Total maxima 6
It looks like the requirement of the residuum not yet fulfilled. Let’s processed it again.
mean: -0.002681745482482584 Total minima 2 Total maxima 2
And at last, we find the residuum (monotonic). The last extracted looks like just noise because of the accumulative error of boundary. This is can be prevented by raising the threshold of the mean of the signal. When the mean of the signal is not fulfilling the threshold (the extracted signal is not an IMF), it will try again following step 2–6 until the extracted signal fulfill the threshold. The more convergence the threshold to zero, the more likely this noise vanishes. So that this article is not too long, in the EMD algorithm demonstration earlier, the threshold we used was not too strict. Because in the end what we want to achieve here is that readers understand step by step the EMD algorithm easily.
For the first time, I am trying using google colab, so all the code and explanation to build all graph above can be accessed through this link (ps: some code must be run in the order to make it work properly).
See you.
references:
https://medium.com/@rrfd/standardize-or-normalize-examples-in-python-e3f174b65dfc, accessed on 2 October 2019
Zeiler, A., Faltermeier, R., Keck, I. R., Tomé, A. M., Puntonet, C. G., & Lang, E. W. (2010, July). Empirical mode decomposition-an introduction. In The 2010 International Joint Conference on Neural Networks (IJCNN) (pp. 1–8). IEEE. | [
{
"code": null,
"e": 673,
"s": 171,
"text": "What kind of ‘beast’ is Empirical Mode Decomposition (EMD) is? It’s an algorithm to decompose signals. And when I say signal, what I mean is a time-series data. We inputting a signal to the EMD and we will get some decomposed signal a.k.a ‘basic ingredient’ of our signal input. It’s similar to the Fast Fourier Transform (FFT). FFT assumes our signal is periodic and it’s ‘basic ingredient’ is various simple sine waves. In FFT, our signal is changed from the time spectrum to the frequency spectrum."
},
{
"code": null,
"e": 1023,
"s": 673,
"text": "The different with EMD is the output remains in the time spectrum and EMD does not assume our signal is periodic and it’s not based on simple sine wave instead, it’s Intrinsic Mode Function (IMF). EMD is really based on the dataset, doesn’t have an assumption about the data (That why it’s called Empirical). IMF is a wave that obeying 2 properties:"
},
{
"code": null,
"e": 1129,
"s": 1023,
"text": "The difference number of maxima and minima at most by 1. Maxima is a peak of wave and minima is a valley."
},
{
"code": null,
"e": 1235,
"s": 1129,
"text": "The difference number of maxima and minima at most by 1. Maxima is a peak of wave and minima is a valley."
},
{
"code": null,
"e": 1282,
"s": 1235,
"text": "Assume our dataset has been standardized using"
},
{
"code": null,
"e": 1657,
"s": 1282,
"text": "Then maxima not always above zero and minima not always below zero. Maxima is the value of the signal where when the trend in the signal continues to go up then suddenly go down, the value right before the value goes down is maxima. On the other hand, Minima is when the trend in the signal continues to go down then suddenly go up, the value right before goes up is minima."
},
{
"code": null,
"e": 1697,
"s": 1657,
"text": "2. The Mean of the wave of IMF is zero."
},
{
"code": null,
"e": 1823,
"s": 1697,
"text": "A simple sine wave is an IMF (The difference between minima and maxima is at most by 1 ✓, The mean of the dataset is zero ✓)."
},
{
"code": null,
"e": 2086,
"s": 1823,
"text": ">>> import numpy as np>>> frequency = 1>>> total_time = 1>>> res = 0.01>>> time = np.arange(0, total_time, res)>>> amplitude = np.sin(2 * np.pi * frequency * total_time * (time/time[-1]))>>> np.mean(amplitude)-2.6319088627735572e-17 #this value literally equal 0"
},
{
"code": null,
"e": 2146,
"s": 2086,
"text": "But an IMF can have more than 1 frequency and more complex."
},
{
"code": null,
"e": 2237,
"s": 2146,
"text": "To make it more easy for us to understand the algorithm, here I present a toy test signal."
},
{
"code": null,
"e": 2266,
"s": 2237,
"text": "This signal (1 Hz sine wave)"
},
{
"code": null,
"e": 2292,
"s": 2266,
"text": "and this (4 Hz sine wave)"
},
{
"code": null,
"e": 2317,
"s": 2292,
"text": "are combined become this"
},
{
"code": null,
"e": 2409,
"s": 2317,
"text": "Voila, we will try to decompose this signal trough this step by step algorithm explanation."
},
{
"code": null,
"e": 2436,
"s": 2409,
"text": "Here the algorithm of EMD."
},
{
"code": null,
"e": 2472,
"s": 2436,
"text": "Step 1, Find the Minima and Maxima."
},
{
"code": null,
"e": 2665,
"s": 2472,
"text": "Step 2, create an envelope of minima and maxima from the array of minima and maxima. Interpolate the value of minima and maxima to create an envelope of minima and maxima using a cubic spline."
},
{
"code": null,
"e": 2735,
"s": 2665,
"text": "Step 4, from the envelope of minima and maxima, get the middle value."
},
{
"code": null,
"e": 2827,
"s": 2735,
"text": "Step 5, decrease the value of the real toy test signal by the middle value of the envelope."
},
{
"code": null,
"e": 3607,
"s": 2827,
"text": "If you look closely, this is our 4 Hz sine wave successfully extracted. But looks like there is some error like a sudden leap on both sides of the wave. This has come from the error of the interpolation of the cubic spline. The interpolation of the cubic spline becomes so bad at the beginning and the end of the signal. The solution is we must define a boundary condition. What I mean about boundary condition is we must define the envelope of minima and maxima at the beginning and the end of the signal before doing the cubic spline. In this article, the envelope of minima and maxima of the beginning and the end of the signal is the same as with the nearest maxima and minima from them. Let’s restart it from step 1 to step 5 but this time, we define the boundary condition."
},
{
"code": null,
"e": 3708,
"s": 3607,
"text": "Ouch, this time the error is affected the entire extracted signal. But the sudden leap has vanished."
},
{
"code": null,
"e": 3758,
"s": 3708,
"text": "Step 6, Check if this extracted signal is an IMF."
},
{
"code": null,
"e": 3853,
"s": 3758,
"text": "#here is the ouput of python scriptmean: -0.002681745482482584 Total minima 20 Total maxima 21"
},
{
"code": null,
"e": 4404,
"s": 3853,
"text": "The mean is nearly zero, I think we can ignore it and round it to zero. The number of Minima and Maxima also fulfill the requirement, we get an IMF. If you are not satisfied with the mean of the extracted signal, you can process it 1 more time following step 2 — step 6. But this time, instead of inputting a real toy test signal, we use that extracted signal. This the route of the algorithm when in the first or second or so on triest, the extracted signal not satisfied IMF condition. To make it more simple, let’s just admit the signal is an IMF."
},
{
"code": null,
"e": 4465,
"s": 4404,
"text": "Step 7, decrease the original toy test signal with this IMF."
},
{
"code": null,
"e": 4872,
"s": 4465,
"text": "Woah, we get our 1 Hz signal (but as we thought, the beginning and the end is wrong). It looks like we success to decompose our fused signal. But, the condition to stop in the algorithm of EMD is when our residuum signal is just a constant, monotonic, or just have 1 extremum (just have 1 minima or maxima). Our signal which we have reduced by the IMF before is called residuum. Let’s continue the process."
},
{
"code": null,
"e": 4930,
"s": 4872,
"text": "mean: -0.002681745482482584 Total minima 6 Total maxima 6"
},
{
"code": null,
"e": 5021,
"s": 4930,
"text": "It looks like the requirement of the residuum not yet fulfilled. Let’s processed it again."
},
{
"code": null,
"e": 5079,
"s": 5021,
"text": "mean: -0.002681745482482584 Total minima 2 Total maxima 2"
},
{
"code": null,
"e": 5795,
"s": 5079,
"text": "And at last, we find the residuum (monotonic). The last extracted looks like just noise because of the accumulative error of boundary. This is can be prevented by raising the threshold of the mean of the signal. When the mean of the signal is not fulfilling the threshold (the extracted signal is not an IMF), it will try again following step 2–6 until the extracted signal fulfill the threshold. The more convergence the threshold to zero, the more likely this noise vanishes. So that this article is not too long, in the EMD algorithm demonstration earlier, the threshold we used was not too strict. Because in the end what we want to achieve here is that readers understand step by step the EMD algorithm easily."
},
{
"code": null,
"e": 6005,
"s": 5795,
"text": "For the first time, I am trying using google colab, so all the code and explanation to build all graph above can be accessed through this link (ps: some code must be run in the order to make it work properly)."
},
{
"code": null,
"e": 6014,
"s": 6005,
"text": "See you."
},
{
"code": null,
"e": 6026,
"s": 6014,
"text": "references:"
},
{
"code": null,
"e": 6136,
"s": 6026,
"text": "https://medium.com/@rrfd/standardize-or-normalize-examples-in-python-e3f174b65dfc, accessed on 2 October 2019"
}
] |
Event-Driven Programming | Event-driven programming focuses on events. Eventually, the flow of program depends upon events. Until now, we were dealing with either sequential or parallel execution model but the model having the concept of event-driven programming is called asynchronous model. Event-driven programming depends upon an event loop that is always listening for the new incoming events. The working of event-driven programming is dependent upon events. Once an event loops, then events decide what to execute and in what order. Following flowchart will help you understand how this works −
Asyncio module was added in Python 3.4 and it provides infrastructure for writing single-threaded concurrent code using co-routines. Following are the different concepts used by the Asyncio module −
Event-loop is a functionality to handle all the events in a computational code. It acts round the way during the execution of whole program and keeps track of the incoming and execution of events. The Asyncio module allows a single event loop per process. Followings are some methods provided by Asyncio module to manage an event loop −
loop = get_event_loop() − This method will provide the event loop for the current context.
loop = get_event_loop() − This method will provide the event loop for the current context.
loop.call_later(time_delay,callback,argument) − This method arranges for the callback that is to be called after the given time_delay seconds.
loop.call_later(time_delay,callback,argument) − This method arranges for the callback that is to be called after the given time_delay seconds.
loop.call_soon(callback,argument) − This method arranges for a callback that is to be called as soon as possible. The callback is called after call_soon() returns and when the control returns to the event loop.
loop.call_soon(callback,argument) − This method arranges for a callback that is to be called as soon as possible. The callback is called after call_soon() returns and when the control returns to the event loop.
loop.time() − This method is used to return the current time according to the event loop’s internal clock.
loop.time() − This method is used to return the current time according to the event loop’s internal clock.
asyncio.set_event_loop() − This method will set the event loop for the current context to the loop.
asyncio.set_event_loop() − This method will set the event loop for the current context to the loop.
asyncio.new_event_loop() − This method will create and return a new event loop object.
asyncio.new_event_loop() − This method will create and return a new event loop object.
loop.run_forever() − This method will run until stop() method is called.
loop.run_forever() − This method will run until stop() method is called.
The following example of event loop helps in printing hello world by using the get_event_loop() method. This example is taken from the Python official docs.
import asyncio
def hello_world(loop):
print('Hello World')
loop.stop()
loop = asyncio.get_event_loop()
loop.call_soon(hello_world, loop)
loop.run_forever()
loop.close()
Hello World
This is compatible with the concurrent.futures.Future class that represents a computation that has not been accomplished. There are following differences between asyncio.futures.Future and concurrent.futures.Future −
result() and exception() methods do not take a timeout argument and raise an exception when the future isn’t done yet.
result() and exception() methods do not take a timeout argument and raise an exception when the future isn’t done yet.
Callbacks registered with add_done_callback() are always called via the event loop’s call_soon().
Callbacks registered with add_done_callback() are always called via the event loop’s call_soon().
asyncio.futures.Future class is not compatible with the wait() and as_completed() functions in the concurrent.futures package.
asyncio.futures.Future class is not compatible with the wait() and as_completed() functions in the concurrent.futures package.
The following is an example that will help you understand how to use asyncio.futures.future class.
import asyncio
async def Myoperation(future):
await asyncio.sleep(2)
future.set_result('Future Completed')
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(Myoperation(future))
try:
loop.run_until_complete(future)
print(future.result())
finally:
loop.close()
Future Completed
The concept of coroutines in Asyncio is similar to the concept of standard Thread object under threading module. This is the generalization of the subroutine concept. A coroutine can be suspended during the execution so that it waits for the external processing and returns from the point at which it had stopped when the external processing was done. The following two ways help us in implementing coroutines −
This is a method for implementation of coroutines under Asyncio module. Following is a Python script for the same −
import asyncio
async def Myoperation():
print("First Coroutine")
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(Myoperation())
finally:
loop.close()
First Coroutine
Another method for implementation of coroutines is to utilize generators with the @asyncio.coroutine decorator. Following is a Python script for the same −
import asyncio
@asyncio.coroutine
def Myoperation():
print("First Coroutine")
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(Myoperation())
finally:
loop.close()
First Coroutine
This subclass of Asyncio module is responsible for execution of coroutines within an event loop in parallel manner. Following Python script is an example of processing some tasks in parallel.
import asyncio
import time
async def Task_ex(n):
time.sleep(1)
print("Processing {}".format(n))
async def Generator_task():
for i in range(10):
asyncio.ensure_future(Task_ex(i))
int("Tasks Completed")
asyncio.sleep(2)
loop = asyncio.get_event_loop()
loop.run_until_complete(Generator_task())
loop.close()
Tasks Completed
Processing 0
Processing 1
Processing 2
Processing 3
Processing 4
Processing 5
Processing 6
Processing 7
Processing 8
Processing 9
Asyncio module provides transport classes for implementing various types of communication. These classes are not thread safe and always paired with a protocol instance after establishment of communication channel.
Following are distinct types of transports inherited from the BaseTransport −
ReadTransport − This is an interface for read-only transports.
ReadTransport − This is an interface for read-only transports.
WriteTransport − This is an interface for write-only transports.
WriteTransport − This is an interface for write-only transports.
DatagramTransport − This is an interface for sending the data.
DatagramTransport − This is an interface for sending the data.
BaseSubprocessTransport − Similar to BaseTransport class.
BaseSubprocessTransport − Similar to BaseTransport class.
Followings are five distinct methods of BaseTransport class that are subsequently transient across the four transport types −
close() − It closes the transport.
close() − It closes the transport.
is_closing() − This method will return true if the transport is closing or is already closed.transports.
is_closing() − This method will return true if the transport is closing or is already closed.transports.
get_extra_info(name, default = none) − This will give us some extra information about transport.
get_extra_info(name, default = none) − This will give us some extra information about transport.
get_protocol() − This method will return the current protocol.
get_protocol() − This method will return the current protocol.
Asyncio module provides base classes that you can subclass to implement your network protocols. Those classes are used in conjunction with transports; the protocol parses incoming data and asks for the writing of outgoing data, while the transport is responsible for the actual I/O and buffering. Following are three classes of Protocol −
Protocol − This is the base class for implementing streaming protocols for use with TCP and SSL transports.
Protocol − This is the base class for implementing streaming protocols for use with TCP and SSL transports.
DatagramProtocol − This is the base class for implementing datagram protocols for use with UDP transports..
DatagramProtocol − This is the base class for implementing datagram protocols for use with UDP transports..
SubprocessProtocol − This is the base class for implementing protocols communicating with child processes through a set of unidirectional pipes.
SubprocessProtocol − This is the base class for implementing protocols communicating with child processes through a set of unidirectional pipes.
57 Lectures
8 hours
Denis Tishkov
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2497,
"s": 1922,
"text": "Event-driven programming focuses on events. Eventually, the flow of program depends upon events. Until now, we were dealing with either sequential or parallel execution model but the model having the concept of event-driven programming is called asynchronous model. Event-driven programming depends upon an event loop that is always listening for the new incoming events. The working of event-driven programming is dependent upon events. Once an event loops, then events decide what to execute and in what order. Following flowchart will help you understand how this works −"
},
{
"code": null,
"e": 2696,
"s": 2497,
"text": "Asyncio module was added in Python 3.4 and it provides infrastructure for writing single-threaded concurrent code using co-routines. Following are the different concepts used by the Asyncio module −"
},
{
"code": null,
"e": 3033,
"s": 2696,
"text": "Event-loop is a functionality to handle all the events in a computational code. It acts round the way during the execution of whole program and keeps track of the incoming and execution of events. The Asyncio module allows a single event loop per process. Followings are some methods provided by Asyncio module to manage an event loop −"
},
{
"code": null,
"e": 3124,
"s": 3033,
"text": "loop = get_event_loop() − This method will provide the event loop for the current context."
},
{
"code": null,
"e": 3215,
"s": 3124,
"text": "loop = get_event_loop() − This method will provide the event loop for the current context."
},
{
"code": null,
"e": 3358,
"s": 3215,
"text": "loop.call_later(time_delay,callback,argument) − This method arranges for the callback that is to be called after the given time_delay seconds."
},
{
"code": null,
"e": 3501,
"s": 3358,
"text": "loop.call_later(time_delay,callback,argument) − This method arranges for the callback that is to be called after the given time_delay seconds."
},
{
"code": null,
"e": 3712,
"s": 3501,
"text": "loop.call_soon(callback,argument) − This method arranges for a callback that is to be called as soon as possible. The callback is called after call_soon() returns and when the control returns to the event loop."
},
{
"code": null,
"e": 3923,
"s": 3712,
"text": "loop.call_soon(callback,argument) − This method arranges for a callback that is to be called as soon as possible. The callback is called after call_soon() returns and when the control returns to the event loop."
},
{
"code": null,
"e": 4030,
"s": 3923,
"text": "loop.time() − This method is used to return the current time according to the event loop’s internal clock."
},
{
"code": null,
"e": 4137,
"s": 4030,
"text": "loop.time() − This method is used to return the current time according to the event loop’s internal clock."
},
{
"code": null,
"e": 4237,
"s": 4137,
"text": "asyncio.set_event_loop() − This method will set the event loop for the current context to the loop."
},
{
"code": null,
"e": 4337,
"s": 4237,
"text": "asyncio.set_event_loop() − This method will set the event loop for the current context to the loop."
},
{
"code": null,
"e": 4424,
"s": 4337,
"text": "asyncio.new_event_loop() − This method will create and return a new event loop object."
},
{
"code": null,
"e": 4511,
"s": 4424,
"text": "asyncio.new_event_loop() − This method will create and return a new event loop object."
},
{
"code": null,
"e": 4584,
"s": 4511,
"text": "loop.run_forever() − This method will run until stop() method is called."
},
{
"code": null,
"e": 4657,
"s": 4584,
"text": "loop.run_forever() − This method will run until stop() method is called."
},
{
"code": null,
"e": 4814,
"s": 4657,
"text": "The following example of event loop helps in printing hello world by using the get_event_loop() method. This example is taken from the Python official docs."
},
{
"code": null,
"e": 4993,
"s": 4814,
"text": "import asyncio\n\ndef hello_world(loop):\n print('Hello World')\n loop.stop()\n\nloop = asyncio.get_event_loop()\n\nloop.call_soon(hello_world, loop)\n\nloop.run_forever()\nloop.close()"
},
{
"code": null,
"e": 5006,
"s": 4993,
"text": "Hello World\n"
},
{
"code": null,
"e": 5223,
"s": 5006,
"text": "This is compatible with the concurrent.futures.Future class that represents a computation that has not been accomplished. There are following differences between asyncio.futures.Future and concurrent.futures.Future −"
},
{
"code": null,
"e": 5342,
"s": 5223,
"text": "result() and exception() methods do not take a timeout argument and raise an exception when the future isn’t done yet."
},
{
"code": null,
"e": 5461,
"s": 5342,
"text": "result() and exception() methods do not take a timeout argument and raise an exception when the future isn’t done yet."
},
{
"code": null,
"e": 5559,
"s": 5461,
"text": "Callbacks registered with add_done_callback() are always called via the event loop’s call_soon()."
},
{
"code": null,
"e": 5657,
"s": 5559,
"text": "Callbacks registered with add_done_callback() are always called via the event loop’s call_soon()."
},
{
"code": null,
"e": 5784,
"s": 5657,
"text": "asyncio.futures.Future class is not compatible with the wait() and as_completed() functions in the concurrent.futures package."
},
{
"code": null,
"e": 5911,
"s": 5784,
"text": "asyncio.futures.Future class is not compatible with the wait() and as_completed() functions in the concurrent.futures package."
},
{
"code": null,
"e": 6010,
"s": 5911,
"text": "The following is an example that will help you understand how to use asyncio.futures.future class."
},
{
"code": null,
"e": 6317,
"s": 6010,
"text": "import asyncio\n\nasync def Myoperation(future):\n await asyncio.sleep(2)\n future.set_result('Future Completed')\n\nloop = asyncio.get_event_loop()\nfuture = asyncio.Future()\nasyncio.ensure_future(Myoperation(future))\ntry:\n loop.run_until_complete(future)\n print(future.result())\nfinally:\n loop.close()"
},
{
"code": null,
"e": 6335,
"s": 6317,
"text": "Future Completed\n"
},
{
"code": null,
"e": 6747,
"s": 6335,
"text": "The concept of coroutines in Asyncio is similar to the concept of standard Thread object under threading module. This is the generalization of the subroutine concept. A coroutine can be suspended during the execution so that it waits for the external processing and returns from the point at which it had stopped when the external processing was done. The following two ways help us in implementing coroutines −"
},
{
"code": null,
"e": 6863,
"s": 6747,
"text": "This is a method for implementation of coroutines under Asyncio module. Following is a Python script for the same −"
},
{
"code": null,
"e": 7038,
"s": 6863,
"text": "import asyncio\n\nasync def Myoperation():\n print(\"First Coroutine\")\n\nloop = asyncio.get_event_loop()\ntry:\n loop.run_until_complete(Myoperation())\n\nfinally:\n loop.close()"
},
{
"code": null,
"e": 7055,
"s": 7038,
"text": "First Coroutine\n"
},
{
"code": null,
"e": 7211,
"s": 7055,
"text": "Another method for implementation of coroutines is to utilize generators with the @asyncio.coroutine decorator. Following is a Python script for the same −"
},
{
"code": null,
"e": 7399,
"s": 7211,
"text": "import asyncio\n\[email protected]\ndef Myoperation():\n print(\"First Coroutine\")\n\nloop = asyncio.get_event_loop()\ntry:\n loop.run_until_complete(Myoperation())\n\nfinally:\n loop.close()"
},
{
"code": null,
"e": 7416,
"s": 7399,
"text": "First Coroutine\n"
},
{
"code": null,
"e": 7608,
"s": 7416,
"text": "This subclass of Asyncio module is responsible for execution of coroutines within an event loop in parallel manner. Following Python script is an example of processing some tasks in parallel."
},
{
"code": null,
"e": 7935,
"s": 7608,
"text": "import asyncio\nimport time\nasync def Task_ex(n):\n time.sleep(1)\n print(\"Processing {}\".format(n))\nasync def Generator_task():\n for i in range(10):\n asyncio.ensure_future(Task_ex(i))\n int(\"Tasks Completed\")\n asyncio.sleep(2)\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(Generator_task())\nloop.close()"
},
{
"code": null,
"e": 8082,
"s": 7935,
"text": "Tasks Completed\nProcessing 0\nProcessing 1\nProcessing 2\nProcessing 3\nProcessing 4\nProcessing 5\nProcessing 6\nProcessing 7\nProcessing 8\nProcessing 9\n"
},
{
"code": null,
"e": 8296,
"s": 8082,
"text": "Asyncio module provides transport classes for implementing various types of communication. These classes are not thread safe and always paired with a protocol instance after establishment of communication channel."
},
{
"code": null,
"e": 8374,
"s": 8296,
"text": "Following are distinct types of transports inherited from the BaseTransport −"
},
{
"code": null,
"e": 8438,
"s": 8374,
"text": "ReadTransport − This is an interface for read-only transports."
},
{
"code": null,
"e": 8502,
"s": 8438,
"text": "ReadTransport − This is an interface for read-only transports."
},
{
"code": null,
"e": 8568,
"s": 8502,
"text": "WriteTransport − This is an interface for write-only transports."
},
{
"code": null,
"e": 8634,
"s": 8568,
"text": "WriteTransport − This is an interface for write-only transports."
},
{
"code": null,
"e": 8698,
"s": 8634,
"text": "DatagramTransport − This is an interface for sending the data."
},
{
"code": null,
"e": 8762,
"s": 8698,
"text": "DatagramTransport − This is an interface for sending the data."
},
{
"code": null,
"e": 8820,
"s": 8762,
"text": "BaseSubprocessTransport − Similar to BaseTransport class."
},
{
"code": null,
"e": 8878,
"s": 8820,
"text": "BaseSubprocessTransport − Similar to BaseTransport class."
},
{
"code": null,
"e": 9004,
"s": 8878,
"text": "Followings are five distinct methods of BaseTransport class that are subsequently transient across the four transport types −"
},
{
"code": null,
"e": 9040,
"s": 9004,
"text": "close() − It closes the transport."
},
{
"code": null,
"e": 9076,
"s": 9040,
"text": "close() − It closes the transport."
},
{
"code": null,
"e": 9181,
"s": 9076,
"text": "is_closing() − This method will return true if the transport is closing or is already closed.transports."
},
{
"code": null,
"e": 9286,
"s": 9181,
"text": "is_closing() − This method will return true if the transport is closing or is already closed.transports."
},
{
"code": null,
"e": 9384,
"s": 9286,
"text": "get_extra_info(name, default = none) − This will give us some extra information about transport."
},
{
"code": null,
"e": 9482,
"s": 9384,
"text": "get_extra_info(name, default = none) − This will give us some extra information about transport."
},
{
"code": null,
"e": 9545,
"s": 9482,
"text": "get_protocol() − This method will return the current protocol."
},
{
"code": null,
"e": 9608,
"s": 9545,
"text": "get_protocol() − This method will return the current protocol."
},
{
"code": null,
"e": 9947,
"s": 9608,
"text": "Asyncio module provides base classes that you can subclass to implement your network protocols. Those classes are used in conjunction with transports; the protocol parses incoming data and asks for the writing of outgoing data, while the transport is responsible for the actual I/O and buffering. Following are three classes of Protocol −"
},
{
"code": null,
"e": 10056,
"s": 9947,
"text": "Protocol − This is the base class for implementing streaming protocols for use with TCP and SSL transports."
},
{
"code": null,
"e": 10165,
"s": 10056,
"text": "Protocol − This is the base class for implementing streaming protocols for use with TCP and SSL transports."
},
{
"code": null,
"e": 10273,
"s": 10165,
"text": "DatagramProtocol − This is the base class for implementing datagram protocols for use with UDP transports.."
},
{
"code": null,
"e": 10381,
"s": 10273,
"text": "DatagramProtocol − This is the base class for implementing datagram protocols for use with UDP transports.."
},
{
"code": null,
"e": 10526,
"s": 10381,
"text": "SubprocessProtocol − This is the base class for implementing protocols communicating with child processes through a set of unidirectional pipes."
},
{
"code": null,
"e": 10671,
"s": 10526,
"text": "SubprocessProtocol − This is the base class for implementing protocols communicating with child processes through a set of unidirectional pipes."
},
{
"code": null,
"e": 10704,
"s": 10671,
"text": "\n 57 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10719,
"s": 10704,
"text": " Denis Tishkov"
},
{
"code": null,
"e": 10726,
"s": 10719,
"text": " Print"
},
{
"code": null,
"e": 10737,
"s": 10726,
"text": " Add Notes"
}
] |
Ordinary Differential Equation (ODE) in Python | by Guangyuan(Frank) Li | Towards Data Science | Ordinary Differential Equation (ODE) can be used to describe a dynamic system. To some extent, we are living in a dynamic system, the weather outside of the window changes from dawn to dusk, the metabolism occurs in our body is also a dynamic system because thousands of reactions and molecules got synthesized and degraded as time goes.
More formally, if we define a set of variables, like the temperatures in a day, or the amount of molecule X in a certain time point, and it changes with the independent variable (in a dynamic system, usually it will be time t). ODE offers us a way to mathematically depict the dynamic changes of defined variables. The opposite system to that is called static system, thinking about taking a photo of the outside, this snapshot doesn’t contain any dynamics, in another word, it is static.
Solving Ordinary Differential Equations means determining how the variables will change as time goes by, the solution, sometimes referred to as solution curve (visually shown as below), provide informative prediction to the default behavior of any dynamic systems.
In this article, I am going to give an introduction to ODE and more important, how to solve ODE merely using Python.
Here I firstly introduce some terminologies from which readers may benefit. Ordinary Differential Equation (ODE) looks something like this:
It is an equation that involves the derivatives, but no partial derivative in the equation itself. In another word, we only consider one independent variable, that is time t. When we have more than one independent variable coming in, it becomes Partial Differential Equation (PDE), which is not within the scope of this article.
In ODE, if the coefficient of terms that contains dependent variable (in the above case, the variable R, the term contains R includes dR/dt and k2R) are independent of R, this ODE is regarded as linear ODE. To illustrate the point, let me show you a non-linear ODE as a comparison:
As you can see, now the coefficient of dR/dt is R, which violates the definition of linear ODE, so it turns into a non-linear ODE.
Finally, the last pair of terminology, if the derivative of variable is independent of the independent variable (here it is time t), we call them autonomous ODE, otherwise, it becomes a non-autonomous ODE. Again, a non-autonomous ODE is shown below:
You can see now time t is on the right-hand side, so it is a non-autonomous ODE.
First and foremost, the examples used in this article come from a marvelous review paper from Tyson et al. I would highly recommend checking it out if you are interested in that.
A sigmoidal signal-response curve describes a system like below:
It is the phosphorylation process that happened in our body, R is the substance, which will be converted to the phosphorylated form Rp to exert a lot of functions, this process is catalyzed by Signal S, and the ATP hydrolysis accompanying that. To describe this process, the original paper utilized the following ODE:
Now we first want to solve this equation, meaning to obtain the solution curve that describes how Rp would change with time.
Let’s start to code:
from scipy.integrate import odeintimport numpyimport matplotlib.pyplot as pltdef model(Rp,t,S): k1 = 1 k2 = 1 Rt = 1 km1 = 0.05 km2 = 0.05 dRpdt = (k1*S*(Rt-Rp)/(km1+Rt-Rp)) - k2*Rp/(km2+Rp) return dRpdt
The above code is just to set up the model as we described using a mathematical equation, here some parameters I just used what has been provided in the original paper.
We set the signal strength as 1, but it is really just for illustration, feel free to change it to whatever value you prefer. Then we set the initial value of Rp to three different possibilities: 0, 0.3, and 1. It can show us how different initialization will finally converge to the steady-state. We set the simulation time window from 0 to 20 just for simplicity. Finally, we use odeint function to solve this ODE.
S = 1Rp0 = [0,0.3,1]t = np.linspace(0,20,200)result = odeint(model,Rp0,t,args=(S,))
The result object is a NumPy array of the shape [200,3], 3 corresponds to three initialization conditions. Now we plot that:
fig,ax = plt.subplots()ax.plot(t,result[:,0],label='R0=0')ax.plot(t,result[:,1],label='R0=0.3')ax.plot(t,result[:,2],label='R0=1')ax.legend()ax.set_xlabel('t')ax.set_ylabel('Rp')
Here we can see, no matter where the Rp starts, they will converge to somewhere around 0.5, and this is called a steady-state. Steady-state is the gist of ODE because it defines the default behavior of a dynamic system. You may wonder why we call it a sigmoidal signal response curve? That is because apart from solving the solution curve, we are also interested in knowing how the signal strength will act upon the whole system, in ODE language, how signal strength will change the steady-state of the system? Now we are going to explore it!
Mathematically, a steady-state of a system is basically the root of the formula when setting dRp/dt = 0. A better illustration is as below:
So if we can solve the last equation with respect to Rp, we will have the value of Rp in the steady-state.
S_all = np.linspace(0,3,100)def equation(Rp,S): k1 = 1 k2 = 1 Rt = 1 km1 = 0.05 km2 = 0.05 return k1*S*(Rt-Rp)/(km1+Rt-Rp) - k2*Rp/(km2+Rp)from scipy.optimize import fsolvestore = []for S in S_all: Rp_ss = fsolve(equation,[1],args=(S,))[0] store.append(Rp_ss)
We first set the range of signal S from 0–3, then we use fsolvefunction from scipy.optimizeto do the job. The result basically will be the Rp value when S is equal to the different values within 0–3.
fig,ax = plt.subplots()ax.plot(S_all,store,c='k')ax.set_xlim(0,3)ax.set_xlabel('Signal(S)')ax.set_ylim(0,1.1)ax.set_ylabel('Response(R_ss)')
Now let’s look at the result:
Now I hope it becomes clear why it is called the sigmoidal signal-response curve because as the strength of the signal changes, the steady-state of the system will respond in a sigmoidal manner.
The above example is just to let you get a taste of what ODE is and how to use python to solve ODE in just a few lines of code. When the system becomes more complicated, for example, more than 1 components get involved (here we referred to as the first-order ODE), another python package called GEKKO or scipy.integrate.solve_ivp may help you do the job.
If we are interested in how to reproduce other figures in Tyson et al. I would recommend you check my Github repository where all the codes are provided.
https://github.com/frankligy/ScPyT/blob/main/ODE/submission/Frank_system_biology_hw.pdf
I hope you find this article interesting and useful, thanks for reading! If you like this article, follow me on medium, thank you so much for your support. Connect me on my Twitter or LinkedIn, also please let me know if you have any questions or what kind of tutorials you would like to see In the future! | [
{
"code": null,
"e": 509,
"s": 171,
"text": "Ordinary Differential Equation (ODE) can be used to describe a dynamic system. To some extent, we are living in a dynamic system, the weather outside of the window changes from dawn to dusk, the metabolism occurs in our body is also a dynamic system because thousands of reactions and molecules got synthesized and degraded as time goes."
},
{
"code": null,
"e": 998,
"s": 509,
"text": "More formally, if we define a set of variables, like the temperatures in a day, or the amount of molecule X in a certain time point, and it changes with the independent variable (in a dynamic system, usually it will be time t). ODE offers us a way to mathematically depict the dynamic changes of defined variables. The opposite system to that is called static system, thinking about taking a photo of the outside, this snapshot doesn’t contain any dynamics, in another word, it is static."
},
{
"code": null,
"e": 1263,
"s": 998,
"text": "Solving Ordinary Differential Equations means determining how the variables will change as time goes by, the solution, sometimes referred to as solution curve (visually shown as below), provide informative prediction to the default behavior of any dynamic systems."
},
{
"code": null,
"e": 1380,
"s": 1263,
"text": "In this article, I am going to give an introduction to ODE and more important, how to solve ODE merely using Python."
},
{
"code": null,
"e": 1520,
"s": 1380,
"text": "Here I firstly introduce some terminologies from which readers may benefit. Ordinary Differential Equation (ODE) looks something like this:"
},
{
"code": null,
"e": 1849,
"s": 1520,
"text": "It is an equation that involves the derivatives, but no partial derivative in the equation itself. In another word, we only consider one independent variable, that is time t. When we have more than one independent variable coming in, it becomes Partial Differential Equation (PDE), which is not within the scope of this article."
},
{
"code": null,
"e": 2131,
"s": 1849,
"text": "In ODE, if the coefficient of terms that contains dependent variable (in the above case, the variable R, the term contains R includes dR/dt and k2R) are independent of R, this ODE is regarded as linear ODE. To illustrate the point, let me show you a non-linear ODE as a comparison:"
},
{
"code": null,
"e": 2262,
"s": 2131,
"text": "As you can see, now the coefficient of dR/dt is R, which violates the definition of linear ODE, so it turns into a non-linear ODE."
},
{
"code": null,
"e": 2512,
"s": 2262,
"text": "Finally, the last pair of terminology, if the derivative of variable is independent of the independent variable (here it is time t), we call them autonomous ODE, otherwise, it becomes a non-autonomous ODE. Again, a non-autonomous ODE is shown below:"
},
{
"code": null,
"e": 2593,
"s": 2512,
"text": "You can see now time t is on the right-hand side, so it is a non-autonomous ODE."
},
{
"code": null,
"e": 2772,
"s": 2593,
"text": "First and foremost, the examples used in this article come from a marvelous review paper from Tyson et al. I would highly recommend checking it out if you are interested in that."
},
{
"code": null,
"e": 2837,
"s": 2772,
"text": "A sigmoidal signal-response curve describes a system like below:"
},
{
"code": null,
"e": 3155,
"s": 2837,
"text": "It is the phosphorylation process that happened in our body, R is the substance, which will be converted to the phosphorylated form Rp to exert a lot of functions, this process is catalyzed by Signal S, and the ATP hydrolysis accompanying that. To describe this process, the original paper utilized the following ODE:"
},
{
"code": null,
"e": 3280,
"s": 3155,
"text": "Now we first want to solve this equation, meaning to obtain the solution curve that describes how Rp would change with time."
},
{
"code": null,
"e": 3301,
"s": 3280,
"text": "Let’s start to code:"
},
{
"code": null,
"e": 3526,
"s": 3301,
"text": "from scipy.integrate import odeintimport numpyimport matplotlib.pyplot as pltdef model(Rp,t,S): k1 = 1 k2 = 1 Rt = 1 km1 = 0.05 km2 = 0.05 dRpdt = (k1*S*(Rt-Rp)/(km1+Rt-Rp)) - k2*Rp/(km2+Rp) return dRpdt"
},
{
"code": null,
"e": 3695,
"s": 3526,
"text": "The above code is just to set up the model as we described using a mathematical equation, here some parameters I just used what has been provided in the original paper."
},
{
"code": null,
"e": 4112,
"s": 3695,
"text": "We set the signal strength as 1, but it is really just for illustration, feel free to change it to whatever value you prefer. Then we set the initial value of Rp to three different possibilities: 0, 0.3, and 1. It can show us how different initialization will finally converge to the steady-state. We set the simulation time window from 0 to 20 just for simplicity. Finally, we use odeint function to solve this ODE."
},
{
"code": null,
"e": 4196,
"s": 4112,
"text": "S = 1Rp0 = [0,0.3,1]t = np.linspace(0,20,200)result = odeint(model,Rp0,t,args=(S,))"
},
{
"code": null,
"e": 4321,
"s": 4196,
"text": "The result object is a NumPy array of the shape [200,3], 3 corresponds to three initialization conditions. Now we plot that:"
},
{
"code": null,
"e": 4500,
"s": 4321,
"text": "fig,ax = plt.subplots()ax.plot(t,result[:,0],label='R0=0')ax.plot(t,result[:,1],label='R0=0.3')ax.plot(t,result[:,2],label='R0=1')ax.legend()ax.set_xlabel('t')ax.set_ylabel('Rp')"
},
{
"code": null,
"e": 5043,
"s": 4500,
"text": "Here we can see, no matter where the Rp starts, they will converge to somewhere around 0.5, and this is called a steady-state. Steady-state is the gist of ODE because it defines the default behavior of a dynamic system. You may wonder why we call it a sigmoidal signal response curve? That is because apart from solving the solution curve, we are also interested in knowing how the signal strength will act upon the whole system, in ODE language, how signal strength will change the steady-state of the system? Now we are going to explore it!"
},
{
"code": null,
"e": 5183,
"s": 5043,
"text": "Mathematically, a steady-state of a system is basically the root of the formula when setting dRp/dt = 0. A better illustration is as below:"
},
{
"code": null,
"e": 5290,
"s": 5183,
"text": "So if we can solve the last equation with respect to Rp, we will have the value of Rp in the steady-state."
},
{
"code": null,
"e": 5574,
"s": 5290,
"text": "S_all = np.linspace(0,3,100)def equation(Rp,S): k1 = 1 k2 = 1 Rt = 1 km1 = 0.05 km2 = 0.05 return k1*S*(Rt-Rp)/(km1+Rt-Rp) - k2*Rp/(km2+Rp)from scipy.optimize import fsolvestore = []for S in S_all: Rp_ss = fsolve(equation,[1],args=(S,))[0] store.append(Rp_ss)"
},
{
"code": null,
"e": 5774,
"s": 5574,
"text": "We first set the range of signal S from 0–3, then we use fsolvefunction from scipy.optimizeto do the job. The result basically will be the Rp value when S is equal to the different values within 0–3."
},
{
"code": null,
"e": 5915,
"s": 5774,
"text": "fig,ax = plt.subplots()ax.plot(S_all,store,c='k')ax.set_xlim(0,3)ax.set_xlabel('Signal(S)')ax.set_ylim(0,1.1)ax.set_ylabel('Response(R_ss)')"
},
{
"code": null,
"e": 5945,
"s": 5915,
"text": "Now let’s look at the result:"
},
{
"code": null,
"e": 6140,
"s": 5945,
"text": "Now I hope it becomes clear why it is called the sigmoidal signal-response curve because as the strength of the signal changes, the steady-state of the system will respond in a sigmoidal manner."
},
{
"code": null,
"e": 6495,
"s": 6140,
"text": "The above example is just to let you get a taste of what ODE is and how to use python to solve ODE in just a few lines of code. When the system becomes more complicated, for example, more than 1 components get involved (here we referred to as the first-order ODE), another python package called GEKKO or scipy.integrate.solve_ivp may help you do the job."
},
{
"code": null,
"e": 6649,
"s": 6495,
"text": "If we are interested in how to reproduce other figures in Tyson et al. I would recommend you check my Github repository where all the codes are provided."
},
{
"code": null,
"e": 6737,
"s": 6649,
"text": "https://github.com/frankligy/ScPyT/blob/main/ODE/submission/Frank_system_biology_hw.pdf"
}
] |
How to Get Hired by Google? | Towards Data Science | Recently, while searching a keyword “headless chrome” on Google I got an unusual pop-up on my window, with a message:
Curious developers are known to seek interesting problems. Solve one from Google?
I was surprised to see Google sending me a challenge to solve and I accepted it immediately! Clicking on “I want to play” landed me on Google’s Foobar page.
It was Google Foobar Challenge!
Google Foobar challenge is a secret hiring process by the company to recruit top programmers and developers around the world. And it is known that several developers at Google are hired by this process.
The challenge consists of five levels with a total of nine questions, with the level of difficulty increasing at each level.
After selecting “I want to play” option you land on Foobar’s website which has a Unix-like shell interface, including some standard Unix commands like help, cd, ls, cat and etcetera.
So, the challenge begins with a sci-fi adventure storyline (in the blue text above). To begin the time-limited challenge we have to enter a request command in the shell.
After requesting the challenge, four files are added in the command-line folder: solution.java , solution.py , readme.txt and constraints.txt which we have to access using cat and ls command (listed in help).
We have a choice to solve the question either in java or python 2.7 .
To start writing the code, we have to run the command edit file.py or edit file.java and a code editor will open-up on the same webpage (and save the code using the short-cut keys). We can verify our code at any time by running the verify file command. The code will be verified by running on several test cases of which two are visible and rest are hidden test cases. Once the code has passed all the test cases accurately, we can submit our solution to that question running thesubmit file command.
The level of difficulty keeps on increasing as progress further in the challenge.
Level 1: This level has only one question, which was pretty straightforward and easy to solve. It does not require any special algorithm to solve it. Forty-eight hours are given to solve this question.
Level 2: There are two questions at this stage with the time of seventy-two hours to solve each question. Both the questions were based on the basic principles of linear algebra and mathematics.
After solving both the questions at this level, we get a referral link i.e. we can invite our one friend to take Google Foobar Challenge!
Level 3: This is where the challenge starts to get a little tricky. To pass this level, we have to solve three questions with a time of seven days for each question.
To solve these questions, it required a good knowledge of mathematics and programming concepts like dynamic programming, Markov’s chaining, etc.
But you don’t need to worry if you don’t know these concepts, you can always learn these concepts online. Challenge gives you enough time to understand the concept and implement them in the given programming problem. In one of the questions, I solved the problem with the most intuitive method but it was not optimal enough for large values and required implementation of dynamic programming to get the result.
towardsdatascience.com
After completing level 3, we are asked to fill-out our details for being contacted by a Google recruiter!
They ask your basic information: name, phone number, email address, country, CV (optional), and if you are a student or a professional.
Level 4: I found this level the most difficult of all the five. It required the implementation of several concepts to solve a single problem. There are a total of two questions at this level and time of a total of two weeks is given to solve each question.
Extensive knowledge of algorithms and data structures is required at this level.
The first question was based on the concept of number theory and graphs. I had to implement the Bellman-Ford algorithm in order to solve this question.
It took me a lot of time to understand these concepts and implement them to solve these questions. But I was able to solve both of these questions on time.
After successfully completing level 4 you get another referral link to invite your one more friend to try this challenge!
Level 5: This was the second hardest problem of the whole challenge and was based on a purely mathematical concept. The final level only had a single question and twenty-two days were given to solve that problem!
The problem required understanding of permutations and combinations and implementation of the Pólya enumeration theorem and Burnside’s lemma. After understanding these two theorems coding part was pretty much simple.
With the submission of this question, the Google Foobar Challenge is completed!
After ending the challenge, I got an encrypted string which was easy to decrypt using base64.
import base64encrypted="THE ENCRYPTED MESSAGE"my_eyes=str.encode("MY USER NAME")decoded=base64.b64decode(encrypted)decrypted=""for i in range(0,len(decoded)):decrypted+=chr((my_eyes[i%len(my_eyes)] ^ decoded[i]))print(decrypted)
This was the code I used to decrypt the message. The decrypted message was:
{'success' : 'great', 'colleague' : 'esteemed', 'efforts' : 'incredible', 'achievement' : 'unlocked', 'rabbits' : 'safe', 'foo' : 'win!'}
After the successful completion of all the five levels, chances are that you will be contacted by Google’s recruiter for an interview.
You may receive an email or a phone call and if you cracked the interview then you can be hired at Google.
Unfortunately, this challenge is not available to everyone and Google sends it only to specific developers (it may be based on their search history — technical keywords).
Don’t worry if you didn’t get this invite yet, this is not the only way to get a job at Google.
Don’t find Foobar, let Foobar find you!
I would say this is a great opportunity to learn and I would recommend you to solve the questions if you get an invitation.
While solving the problems don’t keep your aim to get hired at Google but to learn the new techniques and experience one of the best coding challenges.
Foobar is more about learning and implementing, instead of knowing everything before!
If you have any queries or comments, please post them in the comment section.
To improve your code check out our article here.
Check this out: https://www.fiverr.com/share/LDDp34
Originally published at: www.patataeater.blogspot.com | [
{
"code": null,
"e": 290,
"s": 172,
"text": "Recently, while searching a keyword “headless chrome” on Google I got an unusual pop-up on my window, with a message:"
},
{
"code": null,
"e": 372,
"s": 290,
"text": "Curious developers are known to seek interesting problems. Solve one from Google?"
},
{
"code": null,
"e": 529,
"s": 372,
"text": "I was surprised to see Google sending me a challenge to solve and I accepted it immediately! Clicking on “I want to play” landed me on Google’s Foobar page."
},
{
"code": null,
"e": 561,
"s": 529,
"text": "It was Google Foobar Challenge!"
},
{
"code": null,
"e": 764,
"s": 561,
"text": "Google Foobar challenge is a secret hiring process by the company to recruit top programmers and developers around the world. And it is known that several developers at Google are hired by this process."
},
{
"code": null,
"e": 889,
"s": 764,
"text": "The challenge consists of five levels with a total of nine questions, with the level of difficulty increasing at each level."
},
{
"code": null,
"e": 1072,
"s": 889,
"text": "After selecting “I want to play” option you land on Foobar’s website which has a Unix-like shell interface, including some standard Unix commands like help, cd, ls, cat and etcetera."
},
{
"code": null,
"e": 1242,
"s": 1072,
"text": "So, the challenge begins with a sci-fi adventure storyline (in the blue text above). To begin the time-limited challenge we have to enter a request command in the shell."
},
{
"code": null,
"e": 1451,
"s": 1242,
"text": "After requesting the challenge, four files are added in the command-line folder: solution.java , solution.py , readme.txt and constraints.txt which we have to access using cat and ls command (listed in help)."
},
{
"code": null,
"e": 1521,
"s": 1451,
"text": "We have a choice to solve the question either in java or python 2.7 ."
},
{
"code": null,
"e": 2022,
"s": 1521,
"text": "To start writing the code, we have to run the command edit file.py or edit file.java and a code editor will open-up on the same webpage (and save the code using the short-cut keys). We can verify our code at any time by running the verify file command. The code will be verified by running on several test cases of which two are visible and rest are hidden test cases. Once the code has passed all the test cases accurately, we can submit our solution to that question running thesubmit file command."
},
{
"code": null,
"e": 2104,
"s": 2022,
"text": "The level of difficulty keeps on increasing as progress further in the challenge."
},
{
"code": null,
"e": 2306,
"s": 2104,
"text": "Level 1: This level has only one question, which was pretty straightforward and easy to solve. It does not require any special algorithm to solve it. Forty-eight hours are given to solve this question."
},
{
"code": null,
"e": 2501,
"s": 2306,
"text": "Level 2: There are two questions at this stage with the time of seventy-two hours to solve each question. Both the questions were based on the basic principles of linear algebra and mathematics."
},
{
"code": null,
"e": 2639,
"s": 2501,
"text": "After solving both the questions at this level, we get a referral link i.e. we can invite our one friend to take Google Foobar Challenge!"
},
{
"code": null,
"e": 2805,
"s": 2639,
"text": "Level 3: This is where the challenge starts to get a little tricky. To pass this level, we have to solve three questions with a time of seven days for each question."
},
{
"code": null,
"e": 2950,
"s": 2805,
"text": "To solve these questions, it required a good knowledge of mathematics and programming concepts like dynamic programming, Markov’s chaining, etc."
},
{
"code": null,
"e": 3361,
"s": 2950,
"text": "But you don’t need to worry if you don’t know these concepts, you can always learn these concepts online. Challenge gives you enough time to understand the concept and implement them in the given programming problem. In one of the questions, I solved the problem with the most intuitive method but it was not optimal enough for large values and required implementation of dynamic programming to get the result."
},
{
"code": null,
"e": 3384,
"s": 3361,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3490,
"s": 3384,
"text": "After completing level 3, we are asked to fill-out our details for being contacted by a Google recruiter!"
},
{
"code": null,
"e": 3626,
"s": 3490,
"text": "They ask your basic information: name, phone number, email address, country, CV (optional), and if you are a student or a professional."
},
{
"code": null,
"e": 3883,
"s": 3626,
"text": "Level 4: I found this level the most difficult of all the five. It required the implementation of several concepts to solve a single problem. There are a total of two questions at this level and time of a total of two weeks is given to solve each question."
},
{
"code": null,
"e": 3964,
"s": 3883,
"text": "Extensive knowledge of algorithms and data structures is required at this level."
},
{
"code": null,
"e": 4116,
"s": 3964,
"text": "The first question was based on the concept of number theory and graphs. I had to implement the Bellman-Ford algorithm in order to solve this question."
},
{
"code": null,
"e": 4272,
"s": 4116,
"text": "It took me a lot of time to understand these concepts and implement them to solve these questions. But I was able to solve both of these questions on time."
},
{
"code": null,
"e": 4394,
"s": 4272,
"text": "After successfully completing level 4 you get another referral link to invite your one more friend to try this challenge!"
},
{
"code": null,
"e": 4607,
"s": 4394,
"text": "Level 5: This was the second hardest problem of the whole challenge and was based on a purely mathematical concept. The final level only had a single question and twenty-two days were given to solve that problem!"
},
{
"code": null,
"e": 4825,
"s": 4607,
"text": "The problem required understanding of permutations and combinations and implementation of the Pólya enumeration theorem and Burnside’s lemma. After understanding these two theorems coding part was pretty much simple."
},
{
"code": null,
"e": 4905,
"s": 4825,
"text": "With the submission of this question, the Google Foobar Challenge is completed!"
},
{
"code": null,
"e": 4999,
"s": 4905,
"text": "After ending the challenge, I got an encrypted string which was easy to decrypt using base64."
},
{
"code": null,
"e": 5228,
"s": 4999,
"text": "import base64encrypted=\"THE ENCRYPTED MESSAGE\"my_eyes=str.encode(\"MY USER NAME\")decoded=base64.b64decode(encrypted)decrypted=\"\"for i in range(0,len(decoded)):decrypted+=chr((my_eyes[i%len(my_eyes)] ^ decoded[i]))print(decrypted)"
},
{
"code": null,
"e": 5304,
"s": 5228,
"text": "This was the code I used to decrypt the message. The decrypted message was:"
},
{
"code": null,
"e": 5442,
"s": 5304,
"text": "{'success' : 'great', 'colleague' : 'esteemed', 'efforts' : 'incredible', 'achievement' : 'unlocked', 'rabbits' : 'safe', 'foo' : 'win!'}"
},
{
"code": null,
"e": 5577,
"s": 5442,
"text": "After the successful completion of all the five levels, chances are that you will be contacted by Google’s recruiter for an interview."
},
{
"code": null,
"e": 5684,
"s": 5577,
"text": "You may receive an email or a phone call and if you cracked the interview then you can be hired at Google."
},
{
"code": null,
"e": 5855,
"s": 5684,
"text": "Unfortunately, this challenge is not available to everyone and Google sends it only to specific developers (it may be based on their search history — technical keywords)."
},
{
"code": null,
"e": 5951,
"s": 5855,
"text": "Don’t worry if you didn’t get this invite yet, this is not the only way to get a job at Google."
},
{
"code": null,
"e": 5991,
"s": 5951,
"text": "Don’t find Foobar, let Foobar find you!"
},
{
"code": null,
"e": 6115,
"s": 5991,
"text": "I would say this is a great opportunity to learn and I would recommend you to solve the questions if you get an invitation."
},
{
"code": null,
"e": 6267,
"s": 6115,
"text": "While solving the problems don’t keep your aim to get hired at Google but to learn the new techniques and experience one of the best coding challenges."
},
{
"code": null,
"e": 6353,
"s": 6267,
"text": "Foobar is more about learning and implementing, instead of knowing everything before!"
},
{
"code": null,
"e": 6431,
"s": 6353,
"text": "If you have any queries or comments, please post them in the comment section."
},
{
"code": null,
"e": 6480,
"s": 6431,
"text": "To improve your code check out our article here."
},
{
"code": null,
"e": 6532,
"s": 6480,
"text": "Check this out: https://www.fiverr.com/share/LDDp34"
}
] |
QTP - Error Handling | There are various ways of handling errors in QTP. There are three possible types of errors, one would encounter, while working with QTP. They are −
Syntax Errors
Logical Errors
Run Time Errors
Syntax errors are the typos or a piece of the code that does not confirm with the VBscripting language grammar. Syntax errors occur at the time of compilation of code and cannot be executed until the errors are fixed.
To verify the syntax, use the keyboard shortcut Ctrl+F7 and the result is displayed as shown below. If the window is not displayed one can navigate to "View" → "Errors".
If the script is syntactically correct but it produces unexpected results, then it is known as a Logical error. Logical error usually does not interrupt the execution but produces incorrect results. Logical errors could occur due to variety of reasons, viz- wrong assumptions or misunderstandings of the requirement and sometimes incorrect program logics (using do-while instead of do-Until) or Infinite Loops.
One of the ways to detect a logical error is to perform peer reviews and also verify the QTP output file/result file to ensure that the tool has performed the way it was supposed to do.
As the name states, this kind of error happens during Run Time. The reason for such kind of errors is that the script trying to perform something is unable to do so and the script usually stops, as it is unable to continue with the execution. Classic examples for Run Time Errors are −
File NOT found but the script trying to read the file
Object NOT found but the script is trying to act on that particular object
Dividing a number by Zero
Array Index out of bounds while accessing array elements
There are various ways to handle errors in the code.
1. Using Test Settings − Error handling can be defined the Test Settings by Navigating to "File" >> "Settings" >> "Run" Tab as shown below. We can select any of the specified settings and click "OK".
2. Using On Error Statement − The ‘On Error’ statement is used to notify the VBScript engine of intentions to handle the run-time errors by a tester, rather than allowing the VBScript engine to display error messages that are not user-friendly.
On Error Resume Next − On Error Resume Next informs the VBScript engine to process executing the next line of code when an error is encountered.
On Error Resume Next − On Error Resume Next informs the VBScript engine to process executing the next line of code when an error is encountered.
On error Goto 0 − This helps the testers to turn off the error handling.
On error Goto 0 − This helps the testers to turn off the error handling.
3. Using Err Object − Error object is an in-built object within VBScript that captures the run-time error number and error description with which we are able to debug the code easily.
Err.Number − The Number property returns or sets a numeric value specifying an error. If Err.Number value is 0 then No error has occurred.
Err.Number − The Number property returns or sets a numeric value specifying an error. If Err.Number value is 0 then No error has occurred.
Err.Description − The Description property returns or sets a brief description about an error.
Err.Description − The Description property returns or sets a brief description about an error.
Err.Clear − The Clear method resets the Err object and clears all the previous values associated with it.
Err.Clear − The Clear method resets the Err object and clears all the previous values associated with it.
'Call the function to Add two Numbers Call Addition(num1,num2)
Function Addition(a,b)
On error resume next
If NOT IsNumeric(a) or IsNumeric(b) Then
Print "Error number is " & err.number & " and description is :
" & err.description
Err.Clear
Exit Function
End If
Addition = a+b
'disables error handling
On Error Goto 0
End function
4. Using Exit Statement − Exit Statements can be used along with Err object to exit from a test or action or iteration based on the Err.Number value. Let us see each one of those Exit statements in detail.
ExitTest − Exits from the entire QTP test, no matter what the run-time iteration settings are.
ExitTest − Exits from the entire QTP test, no matter what the run-time iteration settings are.
ExitAction − Exits the current action.
ExitAction − Exits the current action.
ExitActionIteration − Exits the current iteration of the action.
ExitActionIteration − Exits the current iteration of the action.
ExitTestIteration − Exits the current iteration of the QTP test and proceeds to the next iteration.
ExitTestIteration − Exits the current iteration of the QTP test and proceeds to the next iteration.
5. Recovery Scenarios − Upon encountering an error, recovery scenarios are triggered based on certain conditions and it is dealt in detail in a separate chapter.
6. Reporter Object − Reporter Object helps us to report an event to the run results. It helps us to identify if the concerned action/step is pass/fail.
'Syntax: Reporter.ReportEventEventStatus, ReportStepName, Details,
[ImageFilePath]
'Example
Reporter.ReportEvent micFail, "Login", "User is unable to Login."
108 Lectures
8 hours
Pavan Lalwani
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2270,
"s": 2122,
"text": "There are various ways of handling errors in QTP. There are three possible types of errors, one would encounter, while working with QTP. They are −"
},
{
"code": null,
"e": 2284,
"s": 2270,
"text": "Syntax Errors"
},
{
"code": null,
"e": 2299,
"s": 2284,
"text": "Logical Errors"
},
{
"code": null,
"e": 2315,
"s": 2299,
"text": "Run Time Errors"
},
{
"code": null,
"e": 2533,
"s": 2315,
"text": "Syntax errors are the typos or a piece of the code that does not confirm with the VBscripting language grammar. Syntax errors occur at the time of compilation of code and cannot be executed until the errors are fixed."
},
{
"code": null,
"e": 2703,
"s": 2533,
"text": "To verify the syntax, use the keyboard shortcut Ctrl+F7 and the result is displayed as shown below. If the window is not displayed one can navigate to \"View\" → \"Errors\"."
},
{
"code": null,
"e": 3114,
"s": 2703,
"text": "If the script is syntactically correct but it produces unexpected results, then it is known as a Logical error. Logical error usually does not interrupt the execution but produces incorrect results. Logical errors could occur due to variety of reasons, viz- wrong assumptions or misunderstandings of the requirement and sometimes incorrect program logics (using do-while instead of do-Until) or Infinite Loops."
},
{
"code": null,
"e": 3300,
"s": 3114,
"text": "One of the ways to detect a logical error is to perform peer reviews and also verify the QTP output file/result file to ensure that the tool has performed the way it was supposed to do."
},
{
"code": null,
"e": 3586,
"s": 3300,
"text": "As the name states, this kind of error happens during Run Time. The reason for such kind of errors is that the script trying to perform something is unable to do so and the script usually stops, as it is unable to continue with the execution. Classic examples for Run Time Errors are −"
},
{
"code": null,
"e": 3640,
"s": 3586,
"text": "File NOT found but the script trying to read the file"
},
{
"code": null,
"e": 3715,
"s": 3640,
"text": "Object NOT found but the script is trying to act on that particular object"
},
{
"code": null,
"e": 3741,
"s": 3715,
"text": "Dividing a number by Zero"
},
{
"code": null,
"e": 3798,
"s": 3741,
"text": "Array Index out of bounds while accessing array elements"
},
{
"code": null,
"e": 3851,
"s": 3798,
"text": "There are various ways to handle errors in the code."
},
{
"code": null,
"e": 4051,
"s": 3851,
"text": "1. Using Test Settings − Error handling can be defined the Test Settings by Navigating to \"File\" >> \"Settings\" >> \"Run\" Tab as shown below. We can select any of the specified settings and click \"OK\"."
},
{
"code": null,
"e": 4296,
"s": 4051,
"text": "2. Using On Error Statement − The ‘On Error’ statement is used to notify the VBScript engine of intentions to handle the run-time errors by a tester, rather than allowing the VBScript engine to display error messages that are not user-friendly."
},
{
"code": null,
"e": 4441,
"s": 4296,
"text": "On Error Resume Next − On Error Resume Next informs the VBScript engine to process executing the next line of code when an error is encountered."
},
{
"code": null,
"e": 4586,
"s": 4441,
"text": "On Error Resume Next − On Error Resume Next informs the VBScript engine to process executing the next line of code when an error is encountered."
},
{
"code": null,
"e": 4659,
"s": 4586,
"text": "On error Goto 0 − This helps the testers to turn off the error handling."
},
{
"code": null,
"e": 4732,
"s": 4659,
"text": "On error Goto 0 − This helps the testers to turn off the error handling."
},
{
"code": null,
"e": 4916,
"s": 4732,
"text": "3. Using Err Object − Error object is an in-built object within VBScript that captures the run-time error number and error description with which we are able to debug the code easily."
},
{
"code": null,
"e": 5055,
"s": 4916,
"text": "Err.Number − The Number property returns or sets a numeric value specifying an error. If Err.Number value is 0 then No error has occurred."
},
{
"code": null,
"e": 5194,
"s": 5055,
"text": "Err.Number − The Number property returns or sets a numeric value specifying an error. If Err.Number value is 0 then No error has occurred."
},
{
"code": null,
"e": 5289,
"s": 5194,
"text": "Err.Description − The Description property returns or sets a brief description about an error."
},
{
"code": null,
"e": 5384,
"s": 5289,
"text": "Err.Description − The Description property returns or sets a brief description about an error."
},
{
"code": null,
"e": 5490,
"s": 5384,
"text": "Err.Clear − The Clear method resets the Err object and clears all the previous values associated with it."
},
{
"code": null,
"e": 5596,
"s": 5490,
"text": "Err.Clear − The Clear method resets the Err object and clears all the previous values associated with it."
},
{
"code": null,
"e": 6012,
"s": 5596,
"text": "'Call the function to Add two Numbers Call Addition(num1,num2) \n\nFunction Addition(a,b) \n On error resume next \n If NOT IsNumeric(a) or IsNumeric(b) Then \n Print \"Error number is \" & err.number & \" and description is : \n \" & err.description \n Err.Clear \n Exit Function \n End If \n Addition = a+b \n\n 'disables error handling \n On Error Goto 0 \nEnd function "
},
{
"code": null,
"e": 6218,
"s": 6012,
"text": "4. Using Exit Statement − Exit Statements can be used along with Err object to exit from a test or action or iteration based on the Err.Number value. Let us see each one of those Exit statements in detail."
},
{
"code": null,
"e": 6313,
"s": 6218,
"text": "ExitTest − Exits from the entire QTP test, no matter what the run-time iteration settings are."
},
{
"code": null,
"e": 6408,
"s": 6313,
"text": "ExitTest − Exits from the entire QTP test, no matter what the run-time iteration settings are."
},
{
"code": null,
"e": 6447,
"s": 6408,
"text": "ExitAction − Exits the current action."
},
{
"code": null,
"e": 6486,
"s": 6447,
"text": "ExitAction − Exits the current action."
},
{
"code": null,
"e": 6551,
"s": 6486,
"text": "ExitActionIteration − Exits the current iteration of the action."
},
{
"code": null,
"e": 6616,
"s": 6551,
"text": "ExitActionIteration − Exits the current iteration of the action."
},
{
"code": null,
"e": 6716,
"s": 6616,
"text": "ExitTestIteration − Exits the current iteration of the QTP test and proceeds to the next iteration."
},
{
"code": null,
"e": 6816,
"s": 6716,
"text": "ExitTestIteration − Exits the current iteration of the QTP test and proceeds to the next iteration."
},
{
"code": null,
"e": 6978,
"s": 6816,
"text": "5. Recovery Scenarios − Upon encountering an error, recovery scenarios are triggered based on certain conditions and it is dealt in detail in a separate chapter."
},
{
"code": null,
"e": 7130,
"s": 6978,
"text": "6. Reporter Object − Reporter Object helps us to report an event to the run results. It helps us to identify if the concerned action/step is pass/fail."
},
{
"code": null,
"e": 7294,
"s": 7130,
"text": "'Syntax: Reporter.ReportEventEventStatus, ReportStepName, Details, \n[ImageFilePath] \n\n'Example \nReporter.ReportEvent micFail, \"Login\", \"User is unable to Login.\" "
},
{
"code": null,
"e": 7328,
"s": 7294,
"text": "\n 108 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7343,
"s": 7328,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 7350,
"s": 7343,
"text": " Print"
},
{
"code": null,
"e": 7361,
"s": 7350,
"text": " Add Notes"
}
] |
Batch Script - Appending to Files | Content writing to files is also done with the help of the double redirection filter >>. This filter can be used to append any output to a file. Following is a simple example of how to create a file using the redirection command to append data to files.
@echo off
echo "This is the directory listing of C:\ Drive">C:\new.txt
dir C:\>>C:\new.txt
In the above example, you can see that the first echo command is used to create the file using the single redirection command whereas the DIR command is outputted to the file using the double redirection filter.
If you open the file new.txt on your C drive, you will get the contents of your C drive in this file plus the string “This is the directory listing of C:\ Drive” . Following is a sample output.
"This is the directory listing of C:\ Drive"
Volume in drive C is Windows8_OS
Volume Serial Number is E41C-6F43
Directory of C:\
12/22/2015 09:02 PM <DIR> 01 - Music
06/14/2015 10:31 AM <DIR> 02 - Videos
09/12/2015 06:23 AM <DIR> 03 - Pictures
12/17/2015 12:19 AM <DIR> 04 - Software
12/15/2015 11:06 PM <DIR> 05 - Studies
12/20/2014 09:09 AM <DIR> 06 - Future
12/20/2014 09:07 AM <DIR> 07 - Fitness
09/19/2015 09:56 AM <DIR> 08 - Tracking
10/19/2015 10:28 PM <DIR> 09 – Misc
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2423,
"s": 2169,
"text": "Content writing to files is also done with the help of the double redirection filter >>. This filter can be used to append any output to a file. Following is a simple example of how to create a file using the redirection command to append data to files."
},
{
"code": null,
"e": 2514,
"s": 2423,
"text": "@echo off\necho \"This is the directory listing of C:\\ Drive\">C:\\new.txt\ndir C:\\>>C:\\new.txt"
},
{
"code": null,
"e": 2726,
"s": 2514,
"text": "In the above example, you can see that the first echo command is used to create the file using the single redirection command whereas the DIR command is outputted to the file using the double redirection filter."
},
{
"code": null,
"e": 2920,
"s": 2726,
"text": "If you open the file new.txt on your C drive, you will get the contents of your C drive in this file plus the string “This is the directory listing of C:\\ Drive” . Following is a sample output."
},
{
"code": null,
"e": 3471,
"s": 2920,
"text": "\"This is the directory listing of C:\\ Drive\"\nVolume in drive C is Windows8_OS\nVolume Serial Number is E41C-6F43\n\nDirectory of C:\\\n\n12/22/2015 09:02 PM <DIR> 01 - Music\n06/14/2015 10:31 AM <DIR> 02 - Videos\n09/12/2015 06:23 AM <DIR> 03 - Pictures\n12/17/2015 12:19 AM <DIR> 04 - Software\n12/15/2015 11:06 PM <DIR> 05 - Studies\n12/20/2014 09:09 AM <DIR> 06 - Future\n12/20/2014 09:07 AM <DIR> 07 - Fitness\n09/19/2015 09:56 AM <DIR> 08 - Tracking\n10/19/2015 10:28 PM <DIR> 09 – Misc\n"
},
{
"code": null,
"e": 3478,
"s": 3471,
"text": " Print"
},
{
"code": null,
"e": 3489,
"s": 3478,
"text": " Add Notes"
}
] |
PHP switch Statement | If a program needs a series of if statements that perform different process for vaarying value of an expression, it may get very clumsy with each if statement having its own set of curly brackets. This is where using swtich-case construct can make the program compact and readable. With switch construct, it is possible to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to.
switch (expr) {
case val1:
code to be executed if expr=val1;
break;
case val2:
code to be executed if expr=val2;
break;
...
...
default:
code to be executed if expr is not equal to any of above values;
}
It is important to give break statement after each case block in order to void program flow falling through the rest of the cases.
In following example, user is asked to input two numbers and a number for type of arithmetic operation 1/2/3/4 for add/subtract/multiply/divide
Live Demo
<?php
$first=(int)readline("enter a number");
$second=(int)readline("enter another number");
$x=readline("enter 1/2/3/4 for add/subtract/multiply/divide");
$result=0;
switch($x){
case 1: echo $first+$second; break;
case 2: echo $first-$second; break;
case 3: echo $first*$second; break;
case 4: echo $first/$second; break;
default: echo "Incorrect input";
}
?>
This will produce following result −
Incorrect input
The default keyword is used to specify block of statements to be executed if switch expression doesn't match specific cases
If a particular case block is empty, it simply passes the flow to next case.
Live Demo
<?php
$x=(int)readline("enter a number");
switch($x){
case 1:
case 2: echo "x is less than 3"; break;
case 3: echo "x is equal to 3"; break;
case 4: echo "x is greater than 3";break;
default: echo "x is beyound 1 to 4";
}
?>
This will produce following result −
x is beyound 1 to 4
It is possible to use string values to be compared with switch expression
Live Demo
<?php
$x=readline("enter a something..");
switch($x){
case "India": echo "you entered India"; break;
case "USA": echo "You typed USA"; break;
case "Mumbai": echo "you entered Mumbai";break;
default: echo "you entered something else";
}
?>
This will produce following result −
you entered something else | [
{
"code": null,
"e": 1532,
"s": 1062,
"text": "If a program needs a series of if statements that perform different process for vaarying value of an expression, it may get very clumsy with each if statement having its own set of curly brackets. This is where using swtich-case construct can make the program compact and readable. With switch construct, it is possible to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to."
},
{
"code": null,
"e": 1772,
"s": 1532,
"text": "switch (expr) {\n case val1:\n code to be executed if expr=val1;\n break;\n case val2:\n code to be executed if expr=val2;\n break;\n ...\n ...\n default:\n code to be executed if expr is not equal to any of above values;\n}"
},
{
"code": null,
"e": 1903,
"s": 1772,
"text": "It is important to give break statement after each case block in order to void program flow falling through the rest of the cases."
},
{
"code": null,
"e": 2047,
"s": 1903,
"text": "In following example, user is asked to input two numbers and a number for type of arithmetic operation 1/2/3/4 for add/subtract/multiply/divide"
},
{
"code": null,
"e": 2058,
"s": 2047,
"text": " Live Demo"
},
{
"code": null,
"e": 2434,
"s": 2058,
"text": "<?php\n$first=(int)readline(\"enter a number\");\n$second=(int)readline(\"enter another number\");\n$x=readline(\"enter 1/2/3/4 for add/subtract/multiply/divide\");\n$result=0;\nswitch($x){\n case 1: echo $first+$second; break;\n case 2: echo $first-$second; break;\n case 3: echo $first*$second; break;\n case 4: echo $first/$second; break;\n default: echo \"Incorrect input\";\n}\n?>"
},
{
"code": null,
"e": 2471,
"s": 2434,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2487,
"s": 2471,
"text": "Incorrect input"
},
{
"code": null,
"e": 2611,
"s": 2487,
"text": "The default keyword is used to specify block of statements to be executed if switch expression doesn't match specific cases"
},
{
"code": null,
"e": 2688,
"s": 2611,
"text": "If a particular case block is empty, it simply passes the flow to next case."
},
{
"code": null,
"e": 2699,
"s": 2688,
"text": " Live Demo"
},
{
"code": null,
"e": 2939,
"s": 2699,
"text": "<?php\n$x=(int)readline(\"enter a number\");\nswitch($x){\n case 1:\n case 2: echo \"x is less than 3\"; break;\n case 3: echo \"x is equal to 3\"; break;\n case 4: echo \"x is greater than 3\";break;\n default: echo \"x is beyound 1 to 4\";\n}\n?>"
},
{
"code": null,
"e": 2976,
"s": 2939,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2996,
"s": 2976,
"text": "x is beyound 1 to 4"
},
{
"code": null,
"e": 3070,
"s": 2996,
"text": "It is possible to use string values to be compared with switch expression"
},
{
"code": null,
"e": 3081,
"s": 3070,
"text": " Live Demo"
},
{
"code": null,
"e": 3332,
"s": 3081,
"text": "<?php\n$x=readline(\"enter a something..\");\nswitch($x){\n case \"India\": echo \"you entered India\"; break;\n case \"USA\": echo \"You typed USA\"; break;\n case \"Mumbai\": echo \"you entered Mumbai\";break;\n default: echo \"you entered something else\";\n}\n?>"
},
{
"code": null,
"e": 3369,
"s": 3332,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3396,
"s": 3369,
"text": "you entered something else"
}
] |
How to Write a Jupyter Notebook Extension | by Will Koehrsen | Towards Data Science | Jupyter Notebook Extensions are simple add-ons which can significantly improve your productivity in the notebook environment. They automate tedious tasks such as formatting code or add features like creating a table of contents. While there are numerous existing extensions, we can also write our own extension to do extend the functionality of Jupyter.
In this article, we’ll see how to write a Jupyter Notebook extension that adds a default cell to the top of each new notebook which is useful when there are libraries you find yourself importing into every notebook. If you want the background on extensions, then check out this article. The complete code for this extension is available on GitHub.
The final outcome of the Default cell extension is shown below:
(If you don’t yet have Jupyter Extensions, check out this article or just run the following code in a command prompt: pip install jupyter_contrib_nbextensions && jupyter contrib nbextensions install and then start a new notebook server and navigate to the extensions tab).
Unfortunately, there’s not much official documentation on writing your own extension. My tactic was to read the other extensions, copy and paste copiously, and experiment until I figured it out. This Stack Overflow question and answer provided the basic code for this extension.
There are 3 parts (at minimum) to any Jupyter Notebook extension:
description.yaml : A configuration file read by Jupytermain.js : The Javascript code for the extension itselfREADME.md : A markdown description of extension
description.yaml : A configuration file read by Jupyter
main.js : The Javascript code for the extension itself
README.md : A markdown description of extension
(We can also have more functions in other files or css for styling).
These 3 files should live in a single directory which we’ll call default_cell . This folder, in turn, needs to be in the nbextensions subdirectory of the jupyter_contrib_extensions library (what you installed with pip. To find the location of a library installed with pip run pip view package. )
My jupyter_contrib_extensions directory is:
/usr/local/lib/python3.6/site-packages/jupyter_contrib_nbextensions/nbextensions
So the file structure looks like (with nbextensions as shown above):
nbextensions/ default_cell/ - description.yaml - main.js - README.md
When you run jupyter notebook, Jupyter looks in this location for extensions, and shows them on the extensions tab on the server:
When you make a change to the extension files while developing and you want to see the effects in a Jupyter Notebook,you need to run the command jupyter contrib nbextensions install to rewrite the Jupyter config files. Then, restart the notebook server to see your changes.
With the details out of the way, let’s go through the three files we need.
YAML (YAML Ain’t Markup Language) is a human-readable standard for writing configuration and header files. The YAML file describes the extension to the Jupyter Extensions Configurator to be rendered on the extensions tab.
This is a fairly easy file to copy + paste and modify to our needs.
This is then rendered nicely on the NBExtensions tab in the notebook:
The compatibility indicates the versions of Jupyter for which the extension works. I just added all of them (3.x — 6.x) and it seemed to work fine!
This is the heart of the application where the actual logic for the extension lives. Jupyter Notebooks are run in the browser, which means that extensions must be written in Javascript, the language of the web.
It can be a little difficult to figure out what commands to use to make the notebook do what you want. One way to experiment is using the Chrome developer tools (cntrl + shift + i on Windows) or right-click > inspect.
With the developer tools open, we can use the console tab to run commands.
Try opening the developer tools in a Jupyter Notebook and play with options that start with Jupyter.notebook. Any commands you enter will have to be in Javascript. An example of this behavior can be seen in the clip below. I open up the developer tools and then run a few commands to execute cells, insert a new cell, and select the previous cell.
Developing the Javascript code required a lot of experimenting like this! It also helps to read the other extensions to figure out what you need to do.
The final main.js is below:
The most important part of the code is the add_cell function.
var add_cell = function() { Jupyter.notebook. insert_cell_above('code'). // Define default cell here set_text(`Define default cell here`); Jupyter.notebook.select_prev(); Jupyter.notebook.execute_cell_and_select_below();};
This adds a code cell above the currently selected cell with the python code written in the parenthesis (in the set_text call). This is where the default code cell should be defined. The function then executes the cell and selects the one below.
The load_ipython_extension function first checks the number of cells in the notebook. If there is only one cell — a new notebook — it calls the add_cell function which places the default cell at the top of the notebook.
// Run on startfunction load_ipython_extension() {// Add a default cell if a new notebook if (Jupyter.notebook.get_cells().length===1){ add_cell(); } defaultCellButton();}
It then runs the defaultCellButton function which places a button on the Jupyter Notebook toolbar. We can use this button to add and run the default cell above the currently selected cell. This could be useful when we have an already started notebook and we want our normal imports.
There is an almost unlimited number of tasks we could accomplish with Javascript in the browser. This is only a simple application, but there are many more complex Jupyter extensions (such as the Variable Inspector) that demonstrate more of the capabilities. We can also write applications in Javascript that call on Python scripts for even greater control.
A readme markdown file should be familiar to anyone with even a little experience programming. Here is where we explain what our application does and how to use it. This is displayed on the extensions tab:
(The actual code is pretty boring but for completeness, here it is)
Default Cell=========Adds and runs a default cell at the top of each new notebook. To change the default cell, edit the `add_cell` function in the `main.js` file. The relevant section is`Jupyter.notebook.insert_cell_above('code', 0).set_text(``)`Set the `text` to whatever you would like.This extension also adds a button to the toolbar allowing you to insert and run the default cell above your current cell. This can be helpful if you open an already started notebook and notice you are missing some common imports.This extension is a work in progress and any help would be appreciated. Feel free to make contributions on GitHub or contact the author (Will Koehrsen) at [email protected]
Once you have the three required files, your extension is complete.
To see the extension working, make sure the default_cell directory is in the correct location, run jupyter contrib nbextensions install and start up a Jupyter Notebook server. If you navigate to the NBExtensions tab, you will be able to enable the extension (if you don’t have the tab, open a notebook and got to Edit > nbextensions config).
Start up a new notebook and see your extension at work:
This extension isn’t life-changing, but it might save you a few seconds!
Part of the joy of gaining computer literacy is realizing that if you want to accomplish something on a computer, chances are that you probably can with the right tools and willingness to learn. This small example of making a Jupyter Notebook extension demonstrates that we are not limited by what we get out of the box. We just need a few lines of code to accomplish our goals.
Hopefully, either this extension proves useful to you or inspires you to write your own. I have gotten a lot of use from extensions and am looking forward to seeing what else people can develop. Once you do develop an extension, share it so others can marvel at your code and benefit from your hard work.
As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will or through my personal website willk.online. | [
{
"code": null,
"e": 525,
"s": 171,
"text": "Jupyter Notebook Extensions are simple add-ons which can significantly improve your productivity in the notebook environment. They automate tedious tasks such as formatting code or add features like creating a table of contents. While there are numerous existing extensions, we can also write our own extension to do extend the functionality of Jupyter."
},
{
"code": null,
"e": 873,
"s": 525,
"text": "In this article, we’ll see how to write a Jupyter Notebook extension that adds a default cell to the top of each new notebook which is useful when there are libraries you find yourself importing into every notebook. If you want the background on extensions, then check out this article. The complete code for this extension is available on GitHub."
},
{
"code": null,
"e": 937,
"s": 873,
"text": "The final outcome of the Default cell extension is shown below:"
},
{
"code": null,
"e": 1210,
"s": 937,
"text": "(If you don’t yet have Jupyter Extensions, check out this article or just run the following code in a command prompt: pip install jupyter_contrib_nbextensions && jupyter contrib nbextensions install and then start a new notebook server and navigate to the extensions tab)."
},
{
"code": null,
"e": 1489,
"s": 1210,
"text": "Unfortunately, there’s not much official documentation on writing your own extension. My tactic was to read the other extensions, copy and paste copiously, and experiment until I figured it out. This Stack Overflow question and answer provided the basic code for this extension."
},
{
"code": null,
"e": 1555,
"s": 1489,
"text": "There are 3 parts (at minimum) to any Jupyter Notebook extension:"
},
{
"code": null,
"e": 1712,
"s": 1555,
"text": "description.yaml : A configuration file read by Jupytermain.js : The Javascript code for the extension itselfREADME.md : A markdown description of extension"
},
{
"code": null,
"e": 1768,
"s": 1712,
"text": "description.yaml : A configuration file read by Jupyter"
},
{
"code": null,
"e": 1823,
"s": 1768,
"text": "main.js : The Javascript code for the extension itself"
},
{
"code": null,
"e": 1871,
"s": 1823,
"text": "README.md : A markdown description of extension"
},
{
"code": null,
"e": 1940,
"s": 1871,
"text": "(We can also have more functions in other files or css for styling)."
},
{
"code": null,
"e": 2236,
"s": 1940,
"text": "These 3 files should live in a single directory which we’ll call default_cell . This folder, in turn, needs to be in the nbextensions subdirectory of the jupyter_contrib_extensions library (what you installed with pip. To find the location of a library installed with pip run pip view package. )"
},
{
"code": null,
"e": 2280,
"s": 2236,
"text": "My jupyter_contrib_extensions directory is:"
},
{
"code": null,
"e": 2361,
"s": 2280,
"text": "/usr/local/lib/python3.6/site-packages/jupyter_contrib_nbextensions/nbextensions"
},
{
"code": null,
"e": 2430,
"s": 2361,
"text": "So the file structure looks like (with nbextensions as shown above):"
},
{
"code": null,
"e": 2527,
"s": 2430,
"text": "nbextensions/ default_cell/ - description.yaml - main.js - README.md"
},
{
"code": null,
"e": 2657,
"s": 2527,
"text": "When you run jupyter notebook, Jupyter looks in this location for extensions, and shows them on the extensions tab on the server:"
},
{
"code": null,
"e": 2931,
"s": 2657,
"text": "When you make a change to the extension files while developing and you want to see the effects in a Jupyter Notebook,you need to run the command jupyter contrib nbextensions install to rewrite the Jupyter config files. Then, restart the notebook server to see your changes."
},
{
"code": null,
"e": 3006,
"s": 2931,
"text": "With the details out of the way, let’s go through the three files we need."
},
{
"code": null,
"e": 3228,
"s": 3006,
"text": "YAML (YAML Ain’t Markup Language) is a human-readable standard for writing configuration and header files. The YAML file describes the extension to the Jupyter Extensions Configurator to be rendered on the extensions tab."
},
{
"code": null,
"e": 3296,
"s": 3228,
"text": "This is a fairly easy file to copy + paste and modify to our needs."
},
{
"code": null,
"e": 3366,
"s": 3296,
"text": "This is then rendered nicely on the NBExtensions tab in the notebook:"
},
{
"code": null,
"e": 3514,
"s": 3366,
"text": "The compatibility indicates the versions of Jupyter for which the extension works. I just added all of them (3.x — 6.x) and it seemed to work fine!"
},
{
"code": null,
"e": 3725,
"s": 3514,
"text": "This is the heart of the application where the actual logic for the extension lives. Jupyter Notebooks are run in the browser, which means that extensions must be written in Javascript, the language of the web."
},
{
"code": null,
"e": 3943,
"s": 3725,
"text": "It can be a little difficult to figure out what commands to use to make the notebook do what you want. One way to experiment is using the Chrome developer tools (cntrl + shift + i on Windows) or right-click > inspect."
},
{
"code": null,
"e": 4018,
"s": 3943,
"text": "With the developer tools open, we can use the console tab to run commands."
},
{
"code": null,
"e": 4366,
"s": 4018,
"text": "Try opening the developer tools in a Jupyter Notebook and play with options that start with Jupyter.notebook. Any commands you enter will have to be in Javascript. An example of this behavior can be seen in the clip below. I open up the developer tools and then run a few commands to execute cells, insert a new cell, and select the previous cell."
},
{
"code": null,
"e": 4518,
"s": 4366,
"text": "Developing the Javascript code required a lot of experimenting like this! It also helps to read the other extensions to figure out what you need to do."
},
{
"code": null,
"e": 4546,
"s": 4518,
"text": "The final main.js is below:"
},
{
"code": null,
"e": 4608,
"s": 4546,
"text": "The most important part of the code is the add_cell function."
},
{
"code": null,
"e": 4849,
"s": 4608,
"text": "var add_cell = function() { Jupyter.notebook. insert_cell_above('code'). // Define default cell here set_text(`Define default cell here`); Jupyter.notebook.select_prev(); Jupyter.notebook.execute_cell_and_select_below();};"
},
{
"code": null,
"e": 5095,
"s": 4849,
"text": "This adds a code cell above the currently selected cell with the python code written in the parenthesis (in the set_text call). This is where the default code cell should be defined. The function then executes the cell and selects the one below."
},
{
"code": null,
"e": 5315,
"s": 5095,
"text": "The load_ipython_extension function first checks the number of cells in the notebook. If there is only one cell — a new notebook — it calls the add_cell function which places the default cell at the top of the notebook."
},
{
"code": null,
"e": 5503,
"s": 5315,
"text": "// Run on startfunction load_ipython_extension() {// Add a default cell if a new notebook if (Jupyter.notebook.get_cells().length===1){ add_cell(); } defaultCellButton();}"
},
{
"code": null,
"e": 5786,
"s": 5503,
"text": "It then runs the defaultCellButton function which places a button on the Jupyter Notebook toolbar. We can use this button to add and run the default cell above the currently selected cell. This could be useful when we have an already started notebook and we want our normal imports."
},
{
"code": null,
"e": 6144,
"s": 5786,
"text": "There is an almost unlimited number of tasks we could accomplish with Javascript in the browser. This is only a simple application, but there are many more complex Jupyter extensions (such as the Variable Inspector) that demonstrate more of the capabilities. We can also write applications in Javascript that call on Python scripts for even greater control."
},
{
"code": null,
"e": 6350,
"s": 6144,
"text": "A readme markdown file should be familiar to anyone with even a little experience programming. Here is where we explain what our application does and how to use it. This is displayed on the extensions tab:"
},
{
"code": null,
"e": 6418,
"s": 6350,
"text": "(The actual code is pretty boring but for completeness, here it is)"
},
{
"code": null,
"e": 7105,
"s": 6418,
"text": "Default Cell=========Adds and runs a default cell at the top of each new notebook. To change the default cell, edit the `add_cell` function in the `main.js` file. The relevant section is`Jupyter.notebook.insert_cell_above('code', 0).set_text(``)`Set the `text` to whatever you would like.This extension also adds a button to the toolbar allowing you to insert and run the default cell above your current cell. This can be helpful if you open an already started notebook and notice you are missing some common imports.This extension is a work in progress and any help would be appreciated. Feel free to make contributions on GitHub or contact the author (Will Koehrsen) at [email protected]"
},
{
"code": null,
"e": 7173,
"s": 7105,
"text": "Once you have the three required files, your extension is complete."
},
{
"code": null,
"e": 7515,
"s": 7173,
"text": "To see the extension working, make sure the default_cell directory is in the correct location, run jupyter contrib nbextensions install and start up a Jupyter Notebook server. If you navigate to the NBExtensions tab, you will be able to enable the extension (if you don’t have the tab, open a notebook and got to Edit > nbextensions config)."
},
{
"code": null,
"e": 7571,
"s": 7515,
"text": "Start up a new notebook and see your extension at work:"
},
{
"code": null,
"e": 7644,
"s": 7571,
"text": "This extension isn’t life-changing, but it might save you a few seconds!"
},
{
"code": null,
"e": 8023,
"s": 7644,
"text": "Part of the joy of gaining computer literacy is realizing that if you want to accomplish something on a computer, chances are that you probably can with the right tools and willingness to learn. This small example of making a Jupyter Notebook extension demonstrates that we are not limited by what we get out of the box. We just need a few lines of code to accomplish our goals."
},
{
"code": null,
"e": 8328,
"s": 8023,
"text": "Hopefully, either this extension proves useful to you or inspires you to write your own. I have gotten a lot of use from extensions and am looking forward to seeing what else people can develop. Once you do develop an extension, share it so others can marvel at your code and benefit from your hard work."
}
] |
Isolation Forest: A Tree-based Algorithm for Anomaly Detection | by Mahbubul Alam | Towards Data Science | This is the 10th in a series of small, bite-sized articles I am writing about algorithms that are commonly used in anomaly detection (I’ll put links to all other articles towards the end). In today’s article, I’ll focus on a tree-based machine learning algorithm — Isolation Forest — that can efficiently isolate outliers from a multi-dimensional dataset.
My objective here is to give an intuition of how the algorithm works and how to implement it in a few lines of codes as a demonstration. So I am not going deep into the theory, but just enough to help readers understand the basics. You can always search and lookup for details if there’s a specific part of the algorithm that you are interested. So let’s dive right in!
Isolation Forest or iForest is one of the more recent algorithms which was first proposed in 2008 [1] and later published in a paper in 2012 [2]. Around 2016 it was incorporated within the Python Scikit-Learn library.
It is a tree-based algorithm, built around the theory of decision trees and random forests. When presented with a dataset, the algorithm splits the data into two parts based on a random threshold value. This process continues recursively until each data point is isolated. Once the algorithm runs through the whole data, it filters the data points which took fewer steps than others to be isolated. Isolation Forest in sklearn is part of the Ensemble model class, it returns the anomaly score of each instance to measure abnormality.
In most unsupervised methods, “normal” data points are first profiled and anomalies are reported if they do not resemble that profile. Isolation forest, on the other hand, takes a different approach; it isolates anomalous data points explicitly.
It is important to mention that Isolation Forest is an unsupervised machine learning algorithm. Meaning, there is no actual “training” or “learning” involved in the process and there is no pre-determined labeling of “outlier” or “not-outlier” in the dataset. So there is no accuracy test in the conventional machine learning sense.
Now let’s get into the implementation of the algorithm in just 5 steps.
You will need pandas and numpy for data wrangling, matplotlib for data visualization and, of course, the algorithm itself from sklearn library.
# librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.ensemble import IsolationForest
So that you can follow along, I’m not importing any external dataset, rather creating a simple two dimensional numpy array with just one outlier as presented in the two-dimensional plot.
# datasetX = np.array([[1, 2], [2, 1], [3, 2], [0, 1], [25, 30], [3, 5]])# using just numpy array for visualizationplt.scatter(X[:,0], X[:,1], color = "r", s = 50)plt.grid()
Like most algorithms in the Scikit Learn library, instantiating and fitting the model takes only a couple of lines of code.
Two important parameters in building the model are n_estimators and contamination, the latter specifying the percentage of data to be identified as outliers.
# instantiate modelmodel = IsolationForest(n_estimators = 10)# fit modelmodel.fit(X)
When it comes to the prediction, the process involves showing the model a two-dimensional array and the model will spit out either 1 for normal data and -1 for an outlier.
# predict on new data new_data = np.array([[10, 15]])model.predict(new_data)>> array([-1])
Like I said in the beginning, the algorithm uses anomaly scores as a metric, which represents an average anomaly score of the input sample.
# average anomaly scoremodel.decision_function(np.array(new_data))>> array([-0.11147288])
Thanks for reading, hope this article was useful to get an intuition of what Isolation Forest is and how to implement it in Python sklearn library. I wrote a series of articles in this publication focusing on several other algorithms. If you are interested to check out, below are the links. And as always, feel free to reach out via Twitter or LinkedIn and follow me on Medium to get notification of latest articles.
1. K-Nearest Neighbors (kNN)
2. Support Vector Machines (SVM)
3. DBSCAN, an unsupervised algorithm
4. Elliptic Envelope
5. Local Outlier Factor (LOF)
6. Z-score
7. Boxplot
8. Statistical techniques
9. Time series anomaly detection
References
[1] Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. “Isolation forest.” Data Mining, 2008. ICDM’08. Eighth IEEE International Conference on.
[2] Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. “Isolation-based anomaly detection.” ACM Transactions on Knowledge Discovery from Data (TKDD) 6.1 (2012): 3. | [
{
"code": null,
"e": 528,
"s": 172,
"text": "This is the 10th in a series of small, bite-sized articles I am writing about algorithms that are commonly used in anomaly detection (I’ll put links to all other articles towards the end). In today’s article, I’ll focus on a tree-based machine learning algorithm — Isolation Forest — that can efficiently isolate outliers from a multi-dimensional dataset."
},
{
"code": null,
"e": 898,
"s": 528,
"text": "My objective here is to give an intuition of how the algorithm works and how to implement it in a few lines of codes as a demonstration. So I am not going deep into the theory, but just enough to help readers understand the basics. You can always search and lookup for details if there’s a specific part of the algorithm that you are interested. So let’s dive right in!"
},
{
"code": null,
"e": 1116,
"s": 898,
"text": "Isolation Forest or iForest is one of the more recent algorithms which was first proposed in 2008 [1] and later published in a paper in 2012 [2]. Around 2016 it was incorporated within the Python Scikit-Learn library."
},
{
"code": null,
"e": 1650,
"s": 1116,
"text": "It is a tree-based algorithm, built around the theory of decision trees and random forests. When presented with a dataset, the algorithm splits the data into two parts based on a random threshold value. This process continues recursively until each data point is isolated. Once the algorithm runs through the whole data, it filters the data points which took fewer steps than others to be isolated. Isolation Forest in sklearn is part of the Ensemble model class, it returns the anomaly score of each instance to measure abnormality."
},
{
"code": null,
"e": 1896,
"s": 1650,
"text": "In most unsupervised methods, “normal” data points are first profiled and anomalies are reported if they do not resemble that profile. Isolation forest, on the other hand, takes a different approach; it isolates anomalous data points explicitly."
},
{
"code": null,
"e": 2228,
"s": 1896,
"text": "It is important to mention that Isolation Forest is an unsupervised machine learning algorithm. Meaning, there is no actual “training” or “learning” involved in the process and there is no pre-determined labeling of “outlier” or “not-outlier” in the dataset. So there is no accuracy test in the conventional machine learning sense."
},
{
"code": null,
"e": 2300,
"s": 2228,
"text": "Now let’s get into the implementation of the algorithm in just 5 steps."
},
{
"code": null,
"e": 2444,
"s": 2300,
"text": "You will need pandas and numpy for data wrangling, matplotlib for data visualization and, of course, the algorithm itself from sklearn library."
},
{
"code": null,
"e": 2568,
"s": 2444,
"text": "# librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.ensemble import IsolationForest"
},
{
"code": null,
"e": 2755,
"s": 2568,
"text": "So that you can follow along, I’m not importing any external dataset, rather creating a simple two dimensional numpy array with just one outlier as presented in the two-dimensional plot."
},
{
"code": null,
"e": 2929,
"s": 2755,
"text": "# datasetX = np.array([[1, 2], [2, 1], [3, 2], [0, 1], [25, 30], [3, 5]])# using just numpy array for visualizationplt.scatter(X[:,0], X[:,1], color = \"r\", s = 50)plt.grid()"
},
{
"code": null,
"e": 3053,
"s": 2929,
"text": "Like most algorithms in the Scikit Learn library, instantiating and fitting the model takes only a couple of lines of code."
},
{
"code": null,
"e": 3211,
"s": 3053,
"text": "Two important parameters in building the model are n_estimators and contamination, the latter specifying the percentage of data to be identified as outliers."
},
{
"code": null,
"e": 3296,
"s": 3211,
"text": "# instantiate modelmodel = IsolationForest(n_estimators = 10)# fit modelmodel.fit(X)"
},
{
"code": null,
"e": 3468,
"s": 3296,
"text": "When it comes to the prediction, the process involves showing the model a two-dimensional array and the model will spit out either 1 for normal data and -1 for an outlier."
},
{
"code": null,
"e": 3559,
"s": 3468,
"text": "# predict on new data new_data = np.array([[10, 15]])model.predict(new_data)>> array([-1])"
},
{
"code": null,
"e": 3699,
"s": 3559,
"text": "Like I said in the beginning, the algorithm uses anomaly scores as a metric, which represents an average anomaly score of the input sample."
},
{
"code": null,
"e": 3789,
"s": 3699,
"text": "# average anomaly scoremodel.decision_function(np.array(new_data))>> array([-0.11147288])"
},
{
"code": null,
"e": 4207,
"s": 3789,
"text": "Thanks for reading, hope this article was useful to get an intuition of what Isolation Forest is and how to implement it in Python sklearn library. I wrote a series of articles in this publication focusing on several other algorithms. If you are interested to check out, below are the links. And as always, feel free to reach out via Twitter or LinkedIn and follow me on Medium to get notification of latest articles."
},
{
"code": null,
"e": 4236,
"s": 4207,
"text": "1. K-Nearest Neighbors (kNN)"
},
{
"code": null,
"e": 4269,
"s": 4236,
"text": "2. Support Vector Machines (SVM)"
},
{
"code": null,
"e": 4306,
"s": 4269,
"text": "3. DBSCAN, an unsupervised algorithm"
},
{
"code": null,
"e": 4327,
"s": 4306,
"text": "4. Elliptic Envelope"
},
{
"code": null,
"e": 4357,
"s": 4327,
"text": "5. Local Outlier Factor (LOF)"
},
{
"code": null,
"e": 4368,
"s": 4357,
"text": "6. Z-score"
},
{
"code": null,
"e": 4379,
"s": 4368,
"text": "7. Boxplot"
},
{
"code": null,
"e": 4405,
"s": 4379,
"text": "8. Statistical techniques"
},
{
"code": null,
"e": 4438,
"s": 4405,
"text": "9. Time series anomaly detection"
},
{
"code": null,
"e": 4449,
"s": 4438,
"text": "References"
},
{
"code": null,
"e": 4591,
"s": 4449,
"text": "[1] Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. “Isolation forest.” Data Mining, 2008. ICDM’08. Eighth IEEE International Conference on."
}
] |
Python Pandas - Sparse Data | Sparse objects are “compressed” when any data matching a specific value (NaN / missing value, though any value can be chosen) is omitted. A special SparseIndex object tracks where data has been “sparsified”. This will make much more sense in an example. All of the standard Pandas data structures apply the to_sparse method −
import pandas as pd
import numpy as np
ts = pd.Series(np.random.randn(10))
ts[2:-2] = np.nan
sts = ts.to_sparse()
print sts
Its output is as follows −
0 -0.810497
1 -1.419954
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 0.439240
9 -1.095910
dtype: float64
BlockIndex
Block locations: array([0, 8], dtype=int32)
Block lengths: array([2, 2], dtype=int32)
The sparse objects exist for memory efficiency reasons.
Let us now assume you had a large NA DataFrame and execute the following code −
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10000, 4))
df.ix[:9998] = np.nan
sdf = df.to_sparse()
print sdf.density
Its output is as follows −
0.0001
Any sparse object can be converted back to the standard dense form by calling to_dense −
import pandas as pd
import numpy as np
ts = pd.Series(np.random.randn(10))
ts[2:-2] = np.nan
sts = ts.to_sparse()
print sts.to_dense()
Its output is as follows −
0 -0.810497
1 -1.419954
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 0.439240
9 -1.095910
dtype: float64
Sparse data should have the same dtype as its dense representation. Currently, float64, int64 and booldtypes are supported. Depending on the original dtype, fill_value default changes −
float64 − np.nan
float64 − np.nan
int64 − 0
int64 − 0
bool − False
bool − False
Let us execute the following code to understand the same −
import pandas as pd
import numpy as np
s = pd.Series([1, np.nan, np.nan])
print s
s.to_sparse()
print s
Its output is as follows −
0 1.0
1 NaN
2 NaN
dtype: float64
0 1.0
1 NaN
2 NaN
dtype: float64
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2769,
"s": 2443,
"text": "Sparse objects are “compressed” when any data matching a specific value (NaN / missing value, though any value can be chosen) is omitted. A special SparseIndex object tracks where data has been “sparsified”. This will make much more sense in an example. All of the standard Pandas data structures apply the to_sparse method −"
},
{
"code": null,
"e": 2894,
"s": 2769,
"text": "import pandas as pd\nimport numpy as np\n\nts = pd.Series(np.random.randn(10))\nts[2:-2] = np.nan\nsts = ts.to_sparse()\nprint sts"
},
{
"code": null,
"e": 2921,
"s": 2894,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3174,
"s": 2921,
"text": "0 -0.810497\n1 -1.419954\n2 NaN\n3 NaN\n4 NaN\n5 NaN\n6 NaN\n7 NaN\n8 0.439240\n9 -1.095910\ndtype: float64\nBlockIndex\nBlock locations: array([0, 8], dtype=int32)\nBlock lengths: array([2, 2], dtype=int32)\n"
},
{
"code": null,
"e": 3230,
"s": 3174,
"text": "The sparse objects exist for memory efficiency reasons."
},
{
"code": null,
"e": 3310,
"s": 3230,
"text": "Let us now assume you had a large NA DataFrame and execute the following code −"
},
{
"code": null,
"e": 3457,
"s": 3310,
"text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(10000, 4))\ndf.ix[:9998] = np.nan\nsdf = df.to_sparse()\n\nprint sdf.density"
},
{
"code": null,
"e": 3484,
"s": 3457,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3492,
"s": 3484,
"text": "0.0001\n"
},
{
"code": null,
"e": 3581,
"s": 3492,
"text": "Any sparse object can be converted back to the standard dense form by calling to_dense −"
},
{
"code": null,
"e": 3716,
"s": 3581,
"text": "import pandas as pd\nimport numpy as np\nts = pd.Series(np.random.randn(10))\nts[2:-2] = np.nan\nsts = ts.to_sparse()\nprint sts.to_dense()"
},
{
"code": null,
"e": 3743,
"s": 3716,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3899,
"s": 3743,
"text": "0 -0.810497\n1 -1.419954\n2 NaN\n3 NaN\n4 NaN\n5 NaN\n6 NaN\n7 NaN\n8 0.439240\n9 -1.095910\ndtype: float64\n"
},
{
"code": null,
"e": 4085,
"s": 3899,
"text": "Sparse data should have the same dtype as its dense representation. Currently, float64, int64 and booldtypes are supported. Depending on the original dtype, fill_value default changes −"
},
{
"code": null,
"e": 4102,
"s": 4085,
"text": "float64 − np.nan"
},
{
"code": null,
"e": 4119,
"s": 4102,
"text": "float64 − np.nan"
},
{
"code": null,
"e": 4129,
"s": 4119,
"text": "int64 − 0"
},
{
"code": null,
"e": 4139,
"s": 4129,
"text": "int64 − 0"
},
{
"code": null,
"e": 4152,
"s": 4139,
"text": "bool − False"
},
{
"code": null,
"e": 4165,
"s": 4152,
"text": "bool − False"
},
{
"code": null,
"e": 4224,
"s": 4165,
"text": "Let us execute the following code to understand the same −"
},
{
"code": null,
"e": 4330,
"s": 4224,
"text": "import pandas as pd\nimport numpy as np\n\ns = pd.Series([1, np.nan, np.nan])\nprint s\n\ns.to_sparse()\nprint s"
},
{
"code": null,
"e": 4357,
"s": 4330,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4437,
"s": 4357,
"text": "0 1.0\n1 NaN\n2 NaN\ndtype: float64\n\n0 1.0\n1 NaN\n2 NaN\ndtype: float64\n"
},
{
"code": null,
"e": 4474,
"s": 4437,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4490,
"s": 4474,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4523,
"s": 4490,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4542,
"s": 4523,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4577,
"s": 4542,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4599,
"s": 4577,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4633,
"s": 4599,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4661,
"s": 4633,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4696,
"s": 4661,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4710,
"s": 4696,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4743,
"s": 4710,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4760,
"s": 4743,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4767,
"s": 4760,
"text": " Print"
},
{
"code": null,
"e": 4778,
"s": 4767,
"text": " Add Notes"
}
] |
Change of Basis. If you think it’s easy, you’re probably... | by Jeremy Cowles | Towards Data Science | I’ve recently been working the USD Unity SDK and one topic that has come up a few times is basis conversion from right-handed systems (like OpenGL/USD) to left-handed systems (like Unity/DirectX). If you need to convert a matrix or vector from a left handed coordinate system to a right handed coordinate system, you know my pain; and in the spirit of pragmatism, I’ll present the solution first and then we can dive into the details. I’ll also present one weird trick and who knows, maybe we can just multiply Z by -1.
Below is the fully general change of basis formula:
B = P * A * inverse(P)
The erudite reader will identify this change of basis formula as a similarity transform. It can be applied to a matrix A in a right-handed coordinate system to produce the equivalent matrix B in a left-handed coordinate system. The matrix P is the change of basis transformation. So what is the change of basis matrix exactly? If your intent is to convert values from the DirectX to OpenGL default coordinate systems, which differ by a scale of -1 on the Z axis, then the change of basis matrix is the transformation between these systems:
P = [[ 1 0 0 0] [ 0 1 0 0] [ 0 0 -1 0] [ 0 0 0 1]]
This matrix has a special property in that it is involutory (it doesn’t change under inversion). Also note that the change of basis formula with this change of basis matrix only results in six non-identity multiplies. To make the solution fully concrete, here is the implementation in C# using the Unity Engine API:
Matrix4x4 ChangeBasis(Matrix4x4 input) { var basisChange = Matrix4x4.identity; // Invert the forward vector. basisChange[2, 2] = -1; // Note the inverse of this matrix is the matrix itself. var basisChangeInverse = basisChange; // This multiply could be simplified to // -1 * elements [2,6,8,9,11,14], which can be simplified // further; see Eberly's proof for details. return basisChange * input * basisChangeInverse;}Vector3 ChangeBasis(Vector3 point) { UnityEngine.Matrix4x4 mat = UnityEngine.Matrix4x4.identity; mat[2, 2] = -1; return mat.MultiplyPoint3x4(point);}
So there you have a fully general and symmetrical solution for vectors, transforms, cameras, and lights. Note that changing the basis of an entire asset means converting the points, transforms, normals, tangents and all secondary data (e.g. directional vectors which are parameters to shaders). This is no small task. If the asset is animated, you may also need to do this every frame.
You may ask yourself, “but can’t I avoid all these multiplies by using one weird trick?” Well yes, but it’s actually two tricks and it comes at a cost; but before diving into tricks, let’s first agree that the change of basis is the correct general solution.
Anyone who has needed to interchange data between DirectX and OpenGL has felt the pain of needing to change basis between the two coordinate systems. Before finding the fully general solution, I spent way too long flailing around with the wrong solution, in which I attempted to simply invert the Z coordinate of all values. This *appears* to do the right thing when inspecting positions, however it fails to account for rotations and sheering. To understand why this is incorrect, it helps to look at the effect of a proper change of basis on a matrix of ones:
[[ 1 0 0 0] [[1 1 1 1] [[1 0 0 0] [[ 1 1 -1 1] [ 0 1 0 0] x [1 1 1 1] x [0 1 0 0] = [ 1 1 -1 1] [ 0 0 -1 0] [1 1 1 1] [0 0 -1 0] [-1 -1 1 -1] [ 0 0 0 1]] [1 1 1 1]] [0 0 0 1]] [ 1 1 -1 1]]
Oh hai, a lot more than just the Z translation is inverted! We now see the six multiplies I claimed above and clearly, this is not equivalent to multiplying Z by -1, but why is this solution correct?
Perhaps you’ve also stumbled across this document by David Eberly. While logical, seemingly correct, and only requiring four matrix multiplies in three special cases, it was difficult for me to see how it generalized and I didn’t want to blindly apply the formula without really understanding what I was doing.
From linear algebra, I knew that what I really wanted was to perform a change of basis, so I set out to find some mathematical foundations for that instead. What I ultimately found was the text book definition of change of basis.
On Wikipedia, you will find the formula above, but accompanied by a far more inscrutable description than Eberly’s. The underpinnings of this transformation are actually simple to compute and understand, but difficult to explain, so here I’m going to direct you to the 3Blue1Brown video on change of basis. He arrives at the similarity transformation 11 minutes into the video.
Ok, now that we all agree the change of basis formula is fully general and fully correct, let’s get weird.
I didn’t like that this transformation required two matrix multiplies (modulo optimization) per transform and had to be applied to every point, transform and normal (etc) in the asset; and again, this can be particularly slow for animation — so can’t we avoid it? The knowledge of the internet will tell you, “no, it can’t be avoided, suck it up”, but this isn’t completely true, assuming you’re comfortable with a few caveats.
Let’s think about how the change of basis transformation manifests in our data. Assume we have a chain of transforms applied to a vertex position. In a real asset, we have tons of other data, but this limited view of the world is enough to illustrate the idea. Our goal is to transform a point from object space to world space. Assuming T0..T2 are 4x4 matrix transforms, V is a 4x1 vector position to be transformed, our matrix multiplication looks like this when applying the fully general change of basis:
V' = P * T0 * inverse(P) * P * T1 * inverse(P) * P * T2 * inverse(P) * P * V
All those matrix multiplies look extremely redundant, can’t we operate in an intermediate space and only apply the conversion when we’re done? Well yes, but we’d like to avoid having to write this code explicitly in every shader in the system. Instead, we leverage the fact that we know there is a contiguous subgraph in a consistent space (i.e. a single output conversation step should suffice).
V' = P * T0 * T1 * T2 * V
That’s a huge reduction in work! Only the root transform needs to be converted and all other data can remain in its native coordinate space. This works because T0..T2 and V are in the same coordinate system, so rotations work as expected. Additionally, the final output transformation P converts the resulting point correctly, since by definition it cannot be a rotation (it’s just a position). Finally the camera is in the space which P outputs, so the resulting scene appears correct. So what’s the catch?
If we apply this trick while including a camera transform, the camera must either be fully converted or we’ve left the final vertex value in a different coordinate space than where it started when viewing it through this camera. However, to keep all the scene data in a consistent coordinate space, we can instead complete the partial change of basis transformation via the camera’s view transform:
C' = C * inverse(P)
Now, when we go to render our left-handed camera and data in a right-handed coordinate system (for example), the typical camera space transformation will result in the correct final similarity transformation as follows:
CameraSpaceV = (view) * (model) * (vertex) = C * T0 * T1 * T2 * V = inverse(P) * C * P * T0 * T1 * T2 * V = P * C * inverse(P) * T0 * T1 * T2 * V
And now we have two weird tricks :)
The net result has reduced an O(N) number of matrix multiplies on the incoming asset data to O(1).
There are actually a few caveats worth mentioning:
On import, this leaves the raw matrix and vertex data in the other coordinate system. Anyone inspecting this data by hand may be confused by what they are seeing versus the values of the data.The root transform will contain a negative scale. Naive matrix decomposition algorithms will fail to handle this correctly and will convert the scale into a rotation. It is possible to detect this change of basis scale and handle it correctly when decomposing a matrix.If you are operating on matrix data which gets applied directly to the view transform, this trick will require additional fixes.
On import, this leaves the raw matrix and vertex data in the other coordinate system. Anyone inspecting this data by hand may be confused by what they are seeing versus the values of the data.
The root transform will contain a negative scale. Naive matrix decomposition algorithms will fail to handle this correctly and will convert the scale into a rotation. It is possible to detect this change of basis scale and handle it correctly when decomposing a matrix.
If you are operating on matrix data which gets applied directly to the view transform, this trick will require additional fixes.
Above all, I hope the fully general solution is helpful to anyone scouring the internet for a quick solution. Secondarily, I hope that pointing out the fact that ALL data must be converted exposes the corollary that it is actually fraught with peril and the caveats of the “one weird trick” / partial change of basis may actually be preferable in some cases, not only for performance, but for the sake of correctness. | [
{
"code": null,
"e": 692,
"s": 172,
"text": "I’ve recently been working the USD Unity SDK and one topic that has come up a few times is basis conversion from right-handed systems (like OpenGL/USD) to left-handed systems (like Unity/DirectX). If you need to convert a matrix or vector from a left handed coordinate system to a right handed coordinate system, you know my pain; and in the spirit of pragmatism, I’ll present the solution first and then we can dive into the details. I’ll also present one weird trick and who knows, maybe we can just multiply Z by -1."
},
{
"code": null,
"e": 744,
"s": 692,
"text": "Below is the fully general change of basis formula:"
},
{
"code": null,
"e": 767,
"s": 744,
"text": "B = P * A * inverse(P)"
},
{
"code": null,
"e": 1307,
"s": 767,
"text": "The erudite reader will identify this change of basis formula as a similarity transform. It can be applied to a matrix A in a right-handed coordinate system to produce the equivalent matrix B in a left-handed coordinate system. The matrix P is the change of basis transformation. So what is the change of basis matrix exactly? If your intent is to convert values from the DirectX to OpenGL default coordinate systems, which differ by a scale of -1 on the Z axis, then the change of basis matrix is the transformation between these systems:"
},
{
"code": null,
"e": 1381,
"s": 1307,
"text": "P = [[ 1 0 0 0] [ 0 1 0 0] [ 0 0 -1 0] [ 0 0 0 1]]"
},
{
"code": null,
"e": 1697,
"s": 1381,
"text": "This matrix has a special property in that it is involutory (it doesn’t change under inversion). Also note that the change of basis formula with this change of basis matrix only results in six non-identity multiplies. To make the solution fully concrete, here is the implementation in C# using the Unity Engine API:"
},
{
"code": null,
"e": 2303,
"s": 1697,
"text": "Matrix4x4 ChangeBasis(Matrix4x4 input) { var basisChange = Matrix4x4.identity; // Invert the forward vector. basisChange[2, 2] = -1; // Note the inverse of this matrix is the matrix itself. var basisChangeInverse = basisChange; // This multiply could be simplified to // -1 * elements [2,6,8,9,11,14], which can be simplified // further; see Eberly's proof for details. return basisChange * input * basisChangeInverse;}Vector3 ChangeBasis(Vector3 point) { UnityEngine.Matrix4x4 mat = UnityEngine.Matrix4x4.identity; mat[2, 2] = -1; return mat.MultiplyPoint3x4(point);}"
},
{
"code": null,
"e": 2689,
"s": 2303,
"text": "So there you have a fully general and symmetrical solution for vectors, transforms, cameras, and lights. Note that changing the basis of an entire asset means converting the points, transforms, normals, tangents and all secondary data (e.g. directional vectors which are parameters to shaders). This is no small task. If the asset is animated, you may also need to do this every frame."
},
{
"code": null,
"e": 2948,
"s": 2689,
"text": "You may ask yourself, “but can’t I avoid all these multiplies by using one weird trick?” Well yes, but it’s actually two tricks and it comes at a cost; but before diving into tricks, let’s first agree that the change of basis is the correct general solution."
},
{
"code": null,
"e": 3510,
"s": 2948,
"text": "Anyone who has needed to interchange data between DirectX and OpenGL has felt the pain of needing to change basis between the two coordinate systems. Before finding the fully general solution, I spent way too long flailing around with the wrong solution, in which I attempted to simply invert the Z coordinate of all values. This *appears* to do the right thing when inspecting positions, however it fails to account for rotations and sheering. To understand why this is incorrect, it helps to look at the effect of a proper change of basis on a matrix of ones:"
},
{
"code": null,
"e": 3776,
"s": 3510,
"text": "[[ 1 0 0 0] [[1 1 1 1] [[1 0 0 0] [[ 1 1 -1 1] [ 0 1 0 0] x [1 1 1 1] x [0 1 0 0] = [ 1 1 -1 1] [ 0 0 -1 0] [1 1 1 1] [0 0 -1 0] [-1 -1 1 -1] [ 0 0 0 1]] [1 1 1 1]] [0 0 0 1]] [ 1 1 -1 1]]"
},
{
"code": null,
"e": 3976,
"s": 3776,
"text": "Oh hai, a lot more than just the Z translation is inverted! We now see the six multiplies I claimed above and clearly, this is not equivalent to multiplying Z by -1, but why is this solution correct?"
},
{
"code": null,
"e": 4287,
"s": 3976,
"text": "Perhaps you’ve also stumbled across this document by David Eberly. While logical, seemingly correct, and only requiring four matrix multiplies in three special cases, it was difficult for me to see how it generalized and I didn’t want to blindly apply the formula without really understanding what I was doing."
},
{
"code": null,
"e": 4517,
"s": 4287,
"text": "From linear algebra, I knew that what I really wanted was to perform a change of basis, so I set out to find some mathematical foundations for that instead. What I ultimately found was the text book definition of change of basis."
},
{
"code": null,
"e": 4895,
"s": 4517,
"text": "On Wikipedia, you will find the formula above, but accompanied by a far more inscrutable description than Eberly’s. The underpinnings of this transformation are actually simple to compute and understand, but difficult to explain, so here I’m going to direct you to the 3Blue1Brown video on change of basis. He arrives at the similarity transformation 11 minutes into the video."
},
{
"code": null,
"e": 5002,
"s": 4895,
"text": "Ok, now that we all agree the change of basis formula is fully general and fully correct, let’s get weird."
},
{
"code": null,
"e": 5430,
"s": 5002,
"text": "I didn’t like that this transformation required two matrix multiplies (modulo optimization) per transform and had to be applied to every point, transform and normal (etc) in the asset; and again, this can be particularly slow for animation — so can’t we avoid it? The knowledge of the internet will tell you, “no, it can’t be avoided, suck it up”, but this isn’t completely true, assuming you’re comfortable with a few caveats."
},
{
"code": null,
"e": 5938,
"s": 5430,
"text": "Let’s think about how the change of basis transformation manifests in our data. Assume we have a chain of transforms applied to a vertex position. In a real asset, we have tons of other data, but this limited view of the world is enough to illustrate the idea. Our goal is to transform a point from object space to world space. Assuming T0..T2 are 4x4 matrix transforms, V is a 4x1 vector position to be transformed, our matrix multiplication looks like this when applying the fully general change of basis:"
},
{
"code": null,
"e": 6021,
"s": 5938,
"text": "V' = P * T0 * inverse(P) * P * T1 * inverse(P) * P * T2 * inverse(P) * P * V"
},
{
"code": null,
"e": 6418,
"s": 6021,
"text": "All those matrix multiplies look extremely redundant, can’t we operate in an intermediate space and only apply the conversion when we’re done? Well yes, but we’d like to avoid having to write this code explicitly in every shader in the system. Instead, we leverage the fact that we know there is a contiguous subgraph in a consistent space (i.e. a single output conversation step should suffice)."
},
{
"code": null,
"e": 6456,
"s": 6418,
"text": "V' = P * T0 * T1 * T2 * V"
},
{
"code": null,
"e": 6964,
"s": 6456,
"text": "That’s a huge reduction in work! Only the root transform needs to be converted and all other data can remain in its native coordinate space. This works because T0..T2 and V are in the same coordinate system, so rotations work as expected. Additionally, the final output transformation P converts the resulting point correctly, since by definition it cannot be a rotation (it’s just a position). Finally the camera is in the space which P outputs, so the resulting scene appears correct. So what’s the catch?"
},
{
"code": null,
"e": 7363,
"s": 6964,
"text": "If we apply this trick while including a camera transform, the camera must either be fully converted or we’ve left the final vertex value in a different coordinate space than where it started when viewing it through this camera. However, to keep all the scene data in a consistent coordinate space, we can instead complete the partial change of basis transformation via the camera’s view transform:"
},
{
"code": null,
"e": 7383,
"s": 7363,
"text": "C' = C * inverse(P)"
},
{
"code": null,
"e": 7603,
"s": 7383,
"text": "Now, when we go to render our left-handed camera and data in a right-handed coordinate system (for example), the typical camera space transformation will result in the correct final similarity transformation as follows:"
},
{
"code": null,
"e": 7785,
"s": 7603,
"text": "CameraSpaceV = (view) * (model) * (vertex) = C * T0 * T1 * T2 * V = inverse(P) * C * P * T0 * T1 * T2 * V = P * C * inverse(P) * T0 * T1 * T2 * V"
},
{
"code": null,
"e": 7821,
"s": 7785,
"text": "And now we have two weird tricks :)"
},
{
"code": null,
"e": 7920,
"s": 7821,
"text": "The net result has reduced an O(N) number of matrix multiplies on the incoming asset data to O(1)."
},
{
"code": null,
"e": 7971,
"s": 7920,
"text": "There are actually a few caveats worth mentioning:"
},
{
"code": null,
"e": 8561,
"s": 7971,
"text": "On import, this leaves the raw matrix and vertex data in the other coordinate system. Anyone inspecting this data by hand may be confused by what they are seeing versus the values of the data.The root transform will contain a negative scale. Naive matrix decomposition algorithms will fail to handle this correctly and will convert the scale into a rotation. It is possible to detect this change of basis scale and handle it correctly when decomposing a matrix.If you are operating on matrix data which gets applied directly to the view transform, this trick will require additional fixes."
},
{
"code": null,
"e": 8754,
"s": 8561,
"text": "On import, this leaves the raw matrix and vertex data in the other coordinate system. Anyone inspecting this data by hand may be confused by what they are seeing versus the values of the data."
},
{
"code": null,
"e": 9024,
"s": 8754,
"text": "The root transform will contain a negative scale. Naive matrix decomposition algorithms will fail to handle this correctly and will convert the scale into a rotation. It is possible to detect this change of basis scale and handle it correctly when decomposing a matrix."
},
{
"code": null,
"e": 9153,
"s": 9024,
"text": "If you are operating on matrix data which gets applied directly to the view transform, this trick will require additional fixes."
}
] |
Collections in Java - GeeksforGeeks | 09 Dec, 2021
Any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface in it.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes.
What is a Framework?
A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. However, an optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task.
Need for a Separate Collection Framework
Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods for grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these collections had no common interface. Therefore, though the main aim of all the collections is the same, the implementation of all these collections was defined independently and had no correlation among them. And also, it is very difficult for the users to remember all the different methods, syntax, and constructors present in every collection class.
Let’s understand this with an example of adding an element in a hashtable and a vector.
Java
// Java program to demonstrate// why collection framework was neededimport java.io.*;import java.util.*; class CollectionDemo { public static void main(String[] args) { // Creating instances of the array, // vector and hashtable int arr[] = new int[] { 1, 2, 3, 4 }; Vector<Integer> v = new Vector(); Hashtable<Integer, String> h = new Hashtable(); // Adding the elements into the // vector v.addElement(1); v.addElement(2); // Adding the element into the // hashtable h.put(1, "geeks"); h.put(2, "4geeks"); // Array instance creation requires [], // while Vector and hastable require () // Vector element insertion requires addElement(), // but hashtable element insertion requires put() // Accessing the first element of the // array, vector and hashtable System.out.println(arr[0]); System.out.println(v.elementAt(0)); System.out.println(h.get(1)); // Array elements are accessed using [], // vector elements using elementAt() // and hashtable elements using get() }}
Output:
1
1
geeks
As we can observe, none of these collections(Array, Vector, or Hashtable) implements a standard member access interface, it was very difficult for programmers to write algorithms that can work for all kinds of Collections. Another drawback is that most of the ‘Vector’ methods are final, meaning we cannot extend the ’Vector’ class to implement a similar kind of Collection. Therefore, Java developers decided to come up with a common interface to deal with the above-mentioned problems and introduced the Collection Framework in JDK 1.2 post which both, legacy Vectors and Hashtables were modified to conform to the Collection Framework.
Advantages of the Collection Framework: Since the lack of a collection framework gave rise to the above set of disadvantages, the following are the advantages of the collection framework.
Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map, all the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have some common set of methods. Reduces programming effort: A programmer doesn’t have to worry about the design of the Collection but rather he can focus on its best use in his program. Therefore, the basic concept of Object-oriented programming (i.e.) abstraction has been successfully implemented. Increases program speed and quality: Increases performance by providing high-performance implementations of useful data structures and algorithms because in this case, the programmer need not think of the best implementation of a specific data structure. He can simply use the best implementation to drastically boost the performance of his algorithm/program.
Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map, all the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have some common set of methods.
Reduces programming effort: A programmer doesn’t have to worry about the design of the Collection but rather he can focus on its best use in his program. Therefore, the basic concept of Object-oriented programming (i.e.) abstraction has been successfully implemented.
Increases program speed and quality: Increases performance by providing high-performance implementations of useful data structures and algorithms because in this case, the programmer need not think of the best implementation of a specific data structure. He can simply use the best implementation to drastically boost the performance of his algorithm/program.
The utility package, (java.util) contains all the classes and interfaces that are required by the collection framework. The collection framework contains an interface named an iterable interface which provides the iterator to iterate through all the collections. This interface is extended by the main collection interface which acts as a root for the collection framework. All the collections extend this collection interface thereby extending the properties of the iterator and the methods of this interface. The following figure illustrates the hierarchy of the collection framework.
Before understanding the different components in the above framework, let’s first understand a class and an interface.
Class: A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.
Interface: Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how. It is the blueprint of the class.
This interface contains various methods which can be directly used by all the collections which implement this interface. They are:
Method
Description
The collection framework contains multiple interfaces where every interface is used to store a specific type of data. The following are the interfaces present in the framework.
1. Iterable Interface: This is the root interface for the entire collection framework. The collection interface extends the iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections. Therefore, this interface contains only one abstract method which is the iterator. It returns the
Iterator iterator();
2. Collection Interface: This interface extends the iterable interface and is implemented by all the classes in the collection framework. This interface contains all the basic methods which every collection has like adding the data into the collection, removing the data, clearing the data, etc. All these methods are implemented in this interface because these methods are implemented by all the classes irrespective of their style of implementation. And also, having these methods in this interface ensures that the names of the methods are universal for all the collections. Therefore, in short, we can say that this interface builds a foundation on which the collection classes are implemented.
3. List Interface: This is a child interface of the collection interface. This interface is dedicated to the data of the list type in which we can store all the ordered collection of the objects. This also allows duplicate data to be present in it. This list interface is implemented by various classes like ArrayList, Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list object with any of these classes. For example,
List <T> al = new ArrayList<> (); List <T> ll = new LinkedList<> (); List <T> v = new Vector<> ();
Where T is the type of the object
The classes which implement the List interface are as follows:
A. ArrayList: ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. The size of an ArrayList is increased automatically if the collection grows or shrinks if the objects are removed from the collection. Java ArrayList allows us to randomly access the list. ArrayList can not be used for primitive types, like int, char, etc. We will need a wrapper class for such cases. Let’s understand the ArrayList with the following example:
Java
// Java program to demonstrate the// working of ArrayListimport java.io.*;import java.util.*; class GFG { // Main Method public static void main(String[] args) { // Declaring the ArrayList with // initial size n ArrayList<Integer> al = new ArrayList<Integer>(); // Appending new elements at // the end of the list for (int i = 1; i <= 5; i++) al.add(i); // Printing elements System.out.println(al); // Remove element at index 3 al.remove(3); // Displaying the ArrayList // after deletion System.out.println(al); // Printing elements one by one for (int i = 0; i < al.size(); i++) System.out.print(al.get(i) + " "); }}
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
B. LinkedList: LinkedList class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Let’s understand the LinkedList with the following example:
Java
// Java program to demonstrate the// working of LinkedListimport java.io.*;import java.util.*; class GFG { // Main Method public static void main(String[] args) { // Declaring the LinkedList LinkedList<Integer> ll = new LinkedList<Integer>(); // Appending new elements at // the end of the list for (int i = 1; i <= 5; i++) ll.add(i); // Printing elements System.out.println(ll); // Remove element at index 3 ll.remove(3); // Displaying the List // after deletion System.out.println(ll); // Printing elements one by one for (int i = 0; i < ll.size(); i++) System.out.print(ll.get(i) + " "); }}
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
C. Vector: A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This is identical to ArrayList in terms of implementation. However, the primary difference between a vector and an ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized. Let’s understand the Vector with an example:
Java
// Java program to demonstrate the// working of Vectorimport java.io.*;import java.util.*; class GFG { // Main Method public static void main(String[] args) { // Declaring the Vector Vector<Integer> v = new Vector<Integer>(); // Appending new elements at // the end of the list for (int i = 1; i <= 5; i++) v.add(i); // Printing elements System.out.println(v); // Remove element at index 3 v.remove(3); // Displaying the Vector // after deletion System.out.println(v); // Printing elements one by one for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + " "); }}
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
D. Stack: Stack class models and implements the Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be referred to as the subclass of Vector. Let’s understand the stack with an example:
Java
// Java program to demonstrate the// working of a stackimport java.util.*;public class GFG { // Main Method public static void main(String args[]) { Stack<String> stack = new Stack<String>(); stack.push("Geeks"); stack.push("For"); stack.push("Geeks"); stack.push("Geeks"); // Iterator for the stack Iterator<String> itr = stack.iterator(); // Printing the stack while (itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println(); stack.pop(); // Iterator for the stack itr = stack.iterator(); // Printing the stack while (itr.hasNext()) { System.out.print(itr.next() + " "); } }}
Geeks For Geeks Geeks
Geeks For Geeks
Note: Stack is a subclass of Vector and a legacy class. It is thread-safe which might be overhead in an environment where thread safety is not needed. An alternate to Stack is to use ArrayDequeue which is not thread-safe and has faster array implementation.
4. Queue Interface: As the name suggests, a queue interface maintains the FIFO(First In First Out) order similar to a real-world queue line. This interface is dedicated to storing all the elements where the order of the elements matter. For example, whenever we try to book a ticket, the tickets are sold on a first come first serve basis. Therefore, the person whose request arrives first into the queue gets the ticket. There are various classes like PriorityQueue, ArrayDeque, etc. Since all these subclasses implement the queue, we can instantiate a queue object with any of these classes. For example,
Queue <T> pq = new PriorityQueue<> (); Queue <T> ad = new ArrayDeque<> ();
Where T is the type of the object.
The most frequently used implementation of the queue interface is the PriorityQueue. Priority Queue: A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority and this class is used in these cases. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. Let’s understand the priority queue with an example:
Java
// Java program to demonstrate the working of// priority queue in Javaimport java.util.*; class GfG { // Main Method public static void main(String args[]) { // Creating empty priority queue PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}
10
10
15
5. Deque Interface: This is a very slight variation of the queue data structure. Deque, also known as a double-ended queue, is a data structure where we can add and remove the elements from both ends of the queue. This interface extends the queue interface. The class which implements this interface is ArrayDeque. Since ArrayDeque class implements the Deque interface, we can instantiate a deque object with this class. For example,
Deque<T> ad = new ArrayDeque<> ();
Where T is the type of the object.
The class which implements the deque interface is ArrayDeque.
ArrayDeque: ArrayDeque class which is implemented in the collection framework provides us with a way to apply resizable-array. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue. Array deques have no capacity restrictions and they grow as necessary to support usage. Let’s understand ArrayDeque with an example:
Java
// Java program to demonstrate the// ArrayDeque class in Java import java.util.*;public class ArrayDequeDemo { public static void main(String[] args) { // Initializing an deque ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(10); // add() method to insert de_que.add(10); de_que.add(20); de_que.add(30); de_que.add(40); de_que.add(50); System.out.println(de_que); // clear() method de_que.clear(); // addFirst() method to insert the // elements at the head de_que.addFirst(564); de_que.addFirst(291); // addLast() method to insert the // elements at the tail de_que.addLast(24); de_que.addLast(14); System.out.println(de_que); }}
[10, 20, 30, 40, 50]
[291, 564, 24, 14]
6. Set Interface: A set is an unordered collection of objects in which duplicate values cannot be stored. This collection is used when we wish to avoid the duplication of the objects and wish to store only the unique objects. This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc. Since all the subclasses implement the set, we can instantiate a set object with any of these classes. For example,
Set<T> hs = new HashSet<> (); Set<T> lhs = new LinkedHashSet<> (); Set<T> ts = new TreeSet<> ();
Where T is the type of the object.
The following are the classes that implement the Set interface:
A. HashSet: The HashSet class is an inherent implementation of the hash table data structure. The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s understand HashSet with an example:
Java
// Java program to demonstrate the// working of a HashSetimport java.util.*; public class HashSetDemo { // Main Method public static void main(String args[]) { // Creating HashSet and // adding elements HashSet<String> hs = new HashSet<String>(); hs.add("Geeks"); hs.add("For"); hs.add("Geeks"); hs.add("Is"); hs.add("Very helpful"); // Traversing elements Iterator<String> itr = hs.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}
Very helpful
Geeks
For
Is
B. LinkedHashSet: A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked list to store the data and retains the ordering of the elements. Let’s understand the LinkedHashSet with an example:
Java
// Java program to demonstrate the// working of a LinkedHashSetimport java.util.*; public class LinkedHashSetDemo { // Main Method public static void main(String args[]) { // Creating LinkedHashSet and // adding elements LinkedHashSet<String> lhs = new LinkedHashSet<String>(); lhs.add("Geeks"); lhs.add("For"); lhs.add("Geeks"); lhs.add("Is"); lhs.add("Very helpful"); // Traversing elements Iterator<String> itr = lhs.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}
Geeks
For
Is
Very helpful
7. Sorted Set Interface: This interface is very similar to the set interface. The only difference is that this interface has extra methods that maintain the ordering of the elements. The sorted set interface extends the set interface and is used to handle the data which needs to be sorted. The class which implements this interface is TreeSet. Since this class implements the SortedSet, we can instantiate a SortedSet object with this class. For example,
SortedSet<T> ts = new TreeSet<> ();
Where T is the type of the object.
The class which implements the sorted set interface is TreeSet. TreeSet: The TreeSet class uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. Let’s understand TreeSet with an example:
Java
// Java program to demonstrate the// working of a TreeSetimport java.util.*; public class TreeSetDemo { // Main Method public static void main(String args[]) { // Creating TreeSet and // adding elements TreeSet<String> ts = new TreeSet<String>(); ts.add("Geeks"); ts.add("For"); ts.add("Geeks"); ts.add("Is"); ts.add("Very helpful"); // Traversing elements Iterator<String> itr = ts.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}
For
Geeks
Is
Very helpful
8. Map Interface: A map is a data structure that supports the key-value pair mapping for the data. This interface doesn’t support duplicate keys because the same key cannot have multiple mappings. A map is useful if there is data and we wish to perform operations on the basis of the key. This map interface is implemented by various classes like HashMap, TreeMap, etc. Since all the subclasses implement the map, we can instantiate a map object with any of these classes. For example,
Map<T> hm = new HashMap<> (); Map<T> tm = new TreeMap<> (); Where T is the type of the object.
The frequently used implementation of a Map interface is a HashMap. HashMap: HashMap provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value in a HashMap, we must know its key. HashMap uses a technique called Hashing. Hashing is a technique of converting a large String to a small String that represents the same String so that the indexing and search operations are faster. HashSet also uses HashMap internally. Let’s understand the HashMap with an example:
Java
// Java program to demonstrate the// working of a HashMapimport java.util.*; public class HashMapDemo { // Main Method public static void main(String args[]) { // Creating HashMap and // adding elements HashMap<Integer, String> hm = new HashMap<Integer, String>(); hm.put(1, "Geeks"); hm.put(2, "For"); hm.put(3, "Geeks"); // Finding the value for a key System.out.println("Value for 1 is " + hm.get(1)); // Traversing through the HashMap for (Map.Entry<Integer, String> e : hm.entrySet()) System.out.println(e.getKey() + " " + e.getValue()); }}
Value for 1 is Geeks
1 Geeks
2 For
3 Geeks
List InterfaceAbstract List ClassAbstract Sequential List ClassArray ListVector ClassStack ClassLinkedList Class
Abstract List Class
Abstract Sequential List Class
Array List
Vector Class
Stack Class
LinkedList Class
Queue InterfaceBlocking Queue InterfaceAbstractQueue ClassPriorityQueue ClassPriorityBlockingQueue ClassConcurrentLinkedQueue ClassArrayBlockingQueue ClassDelayQueue ClassLinkedBlockingQueue ClassLinkedTransferQueue
Blocking Queue Interface
AbstractQueue Class
PriorityQueue Class
PriorityBlockingQueue Class
ConcurrentLinkedQueue Class
ArrayBlockingQueue Class
DelayQueue Class
LinkedBlockingQueue Class
LinkedTransferQueue
Deque InterfaceBlockingDeque InterfaceConcurrentLinkedDeque ClassArrayDeque Class
BlockingDeque Interface
ConcurrentLinkedDeque Class
ArrayDeque Class
Set InterfaceAbstract Set ClassCopyOnWriteArraySet ClassEnumSet ClassConcurrentHashMap ClassHashSet ClassLinkedHashSet Class
Abstract Set Class
CopyOnWriteArraySet Class
EnumSet Class
ConcurrentHashMap Class
HashSet Class
LinkedHashSet Class
SortedSet InterfaceNavigableSet InterfaceTreeSetConcurrentSkipListSet Class
NavigableSet Interface
TreeSet
ConcurrentSkipListSet Class
Map InterfaceSortedMap InterfaceNavigableMap InterfaceConcurrentMap InterfaceTreeMap ClassAbstractMap ClassConcurrentHashMap ClassEnumMap ClassHashMap ClassIdentityHashMap ClassLinkedHashMap ClassHashTable ClassProperties Class
SortedMap Interface
NavigableMap Interface
ConcurrentMap Interface
TreeMap Class
AbstractMap Class
ConcurrentHashMap Class
EnumMap Class
HashMap Class
IdentityHashMap Class
LinkedHashMap Class
HashTable Class
Properties Class
Other Important ConceptsHow to convert HashMap to ArrayListRandomly select items from a ListHow to add all items from a collection to an ArrayListConversion of Java Maps to ListArray to ArrayList ConversionArrayList to Array ConversionDifferences between Array and ArrayList
How to convert HashMap to ArrayList
Randomly select items from a List
How to add all items from a collection to an ArrayList
Conversion of Java Maps to List
Array to ArrayList Conversion
ArrayList to Array Conversion
Differences between Array and ArrayList
ThakurYogeshwarSingh
SiddharthPandey7
kartik
KaashyapMSK
suraj mall
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
How to iterate any Map in Java
Singleton Class in Java
Initializing a List in Java
Different ways of Reading a text file in Java
Stream In Java
How to add an element to an Array in Java? | [
{
"code": null,
"e": 28950,
"s": 28922,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 29216,
"s": 28950,
"text": "Any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface in it. "
},
{
"code": null,
"e": 29361,
"s": 29216,
"text": "The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes."
},
{
"code": null,
"e": 29382,
"s": 29361,
"text": "What is a Framework?"
},
{
"code": null,
"e": 29716,
"s": 29382,
"text": "A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. However, an optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task. "
},
{
"code": null,
"e": 29757,
"s": 29716,
"text": "Need for a Separate Collection Framework"
},
{
"code": null,
"e": 30294,
"s": 29757,
"text": "Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods for grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these collections had no common interface. Therefore, though the main aim of all the collections is the same, the implementation of all these collections was defined independently and had no correlation among them. And also, it is very difficult for the users to remember all the different methods, syntax, and constructors present in every collection class. "
},
{
"code": null,
"e": 30383,
"s": 30294,
"text": "Let’s understand this with an example of adding an element in a hashtable and a vector. "
},
{
"code": null,
"e": 30388,
"s": 30383,
"text": "Java"
},
{
"code": "// Java program to demonstrate// why collection framework was neededimport java.io.*;import java.util.*; class CollectionDemo { public static void main(String[] args) { // Creating instances of the array, // vector and hashtable int arr[] = new int[] { 1, 2, 3, 4 }; Vector<Integer> v = new Vector(); Hashtable<Integer, String> h = new Hashtable(); // Adding the elements into the // vector v.addElement(1); v.addElement(2); // Adding the element into the // hashtable h.put(1, \"geeks\"); h.put(2, \"4geeks\"); // Array instance creation requires [], // while Vector and hastable require () // Vector element insertion requires addElement(), // but hashtable element insertion requires put() // Accessing the first element of the // array, vector and hashtable System.out.println(arr[0]); System.out.println(v.elementAt(0)); System.out.println(h.get(1)); // Array elements are accessed using [], // vector elements using elementAt() // and hashtable elements using get() }}",
"e": 31556,
"s": 30388,
"text": null
},
{
"code": null,
"e": 31566,
"s": 31556,
"text": "Output: "
},
{
"code": null,
"e": 31576,
"s": 31566,
"text": "1\n1\ngeeks"
},
{
"code": null,
"e": 32216,
"s": 31576,
"text": "As we can observe, none of these collections(Array, Vector, or Hashtable) implements a standard member access interface, it was very difficult for programmers to write algorithms that can work for all kinds of Collections. Another drawback is that most of the ‘Vector’ methods are final, meaning we cannot extend the ’Vector’ class to implement a similar kind of Collection. Therefore, Java developers decided to come up with a common interface to deal with the above-mentioned problems and introduced the Collection Framework in JDK 1.2 post which both, legacy Vectors and Hashtables were modified to conform to the Collection Framework. "
},
{
"code": null,
"e": 32405,
"s": 32216,
"text": "Advantages of the Collection Framework: Since the lack of a collection framework gave rise to the above set of disadvantages, the following are the advantages of the collection framework. "
},
{
"code": null,
"e": 33241,
"s": 32405,
"text": "Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map, all the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have some common set of methods. Reduces programming effort: A programmer doesn’t have to worry about the design of the Collection but rather he can focus on its best use in his program. Therefore, the basic concept of Object-oriented programming (i.e.) abstraction has been successfully implemented. Increases program speed and quality: Increases performance by providing high-performance implementations of useful data structures and algorithms because in this case, the programmer need not think of the best implementation of a specific data structure. He can simply use the best implementation to drastically boost the performance of his algorithm/program."
},
{
"code": null,
"e": 33450,
"s": 33241,
"text": "Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map, all the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have some common set of methods. "
},
{
"code": null,
"e": 33719,
"s": 33450,
"text": "Reduces programming effort: A programmer doesn’t have to worry about the design of the Collection but rather he can focus on its best use in his program. Therefore, the basic concept of Object-oriented programming (i.e.) abstraction has been successfully implemented. "
},
{
"code": null,
"e": 34079,
"s": 33719,
"text": "Increases program speed and quality: Increases performance by providing high-performance implementations of useful data structures and algorithms because in this case, the programmer need not think of the best implementation of a specific data structure. He can simply use the best implementation to drastically boost the performance of his algorithm/program."
},
{
"code": null,
"e": 34667,
"s": 34079,
"text": "The utility package, (java.util) contains all the classes and interfaces that are required by the collection framework. The collection framework contains an interface named an iterable interface which provides the iterator to iterate through all the collections. This interface is extended by the main collection interface which acts as a root for the collection framework. All the collections extend this collection interface thereby extending the properties of the iterator and the methods of this interface. The following figure illustrates the hierarchy of the collection framework. "
},
{
"code": null,
"e": 34787,
"s": 34667,
"text": "Before understanding the different components in the above framework, let’s first understand a class and an interface. "
},
{
"code": null,
"e": 34967,
"s": 34787,
"text": "Class: A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. "
},
{
"code": null,
"e": 35223,
"s": 34967,
"text": "Interface: Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how. It is the blueprint of the class."
},
{
"code": null,
"e": 35355,
"s": 35223,
"text": "This interface contains various methods which can be directly used by all the collections which implement this interface. They are:"
},
{
"code": null,
"e": 35362,
"s": 35355,
"text": "Method"
},
{
"code": null,
"e": 35374,
"s": 35362,
"text": "Description"
},
{
"code": null,
"e": 35552,
"s": 35374,
"text": "The collection framework contains multiple interfaces where every interface is used to store a specific type of data. The following are the interfaces present in the framework. "
},
{
"code": null,
"e": 35964,
"s": 35552,
"text": "1. Iterable Interface: This is the root interface for the entire collection framework. The collection interface extends the iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections. Therefore, this interface contains only one abstract method which is the iterator. It returns the "
},
{
"code": null,
"e": 35986,
"s": 35964,
"text": "Iterator iterator(); "
},
{
"code": null,
"e": 36685,
"s": 35986,
"text": "2. Collection Interface: This interface extends the iterable interface and is implemented by all the classes in the collection framework. This interface contains all the basic methods which every collection has like adding the data into the collection, removing the data, clearing the data, etc. All these methods are implemented in this interface because these methods are implemented by all the classes irrespective of their style of implementation. And also, having these methods in this interface ensures that the names of the methods are universal for all the collections. Therefore, in short, we can say that this interface builds a foundation on which the collection classes are implemented."
},
{
"code": null,
"e": 37144,
"s": 36685,
"text": "3. List Interface: This is a child interface of the collection interface. This interface is dedicated to the data of the list type in which we can store all the ordered collection of the objects. This also allows duplicate data to be present in it. This list interface is implemented by various classes like ArrayList, Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list object with any of these classes. For example, "
},
{
"code": null,
"e": 37244,
"s": 37144,
"text": "List <T> al = new ArrayList<> (); List <T> ll = new LinkedList<> (); List <T> v = new Vector<> (); "
},
{
"code": null,
"e": 37279,
"s": 37244,
"text": "Where T is the type of the object "
},
{
"code": null,
"e": 37342,
"s": 37279,
"text": "The classes which implement the List interface are as follows:"
},
{
"code": null,
"e": 37896,
"s": 37342,
"text": "A. ArrayList: ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. The size of an ArrayList is increased automatically if the collection grows or shrinks if the objects are removed from the collection. Java ArrayList allows us to randomly access the list. ArrayList can not be used for primitive types, like int, char, etc. We will need a wrapper class for such cases. Let’s understand the ArrayList with the following example:"
},
{
"code": null,
"e": 37901,
"s": 37896,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of ArrayListimport java.io.*;import java.util.*; class GFG { // Main Method public static void main(String[] args) { // Declaring the ArrayList with // initial size n ArrayList<Integer> al = new ArrayList<Integer>(); // Appending new elements at // the end of the list for (int i = 1; i <= 5; i++) al.add(i); // Printing elements System.out.println(al); // Remove element at index 3 al.remove(3); // Displaying the ArrayList // after deletion System.out.println(al); // Printing elements one by one for (int i = 0; i < al.size(); i++) System.out.print(al.get(i) + \" \"); }}",
"e": 38677,
"s": 37901,
"text": null
},
{
"code": null,
"e": 38714,
"s": 38677,
"text": "[1, 2, 3, 4, 5]\n[1, 2, 3, 5]\n1 2 3 5"
},
{
"code": null,
"e": 39114,
"s": 38716,
"text": "B. LinkedList: LinkedList class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Let’s understand the LinkedList with the following example:"
},
{
"code": null,
"e": 39119,
"s": 39114,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of LinkedListimport java.io.*;import java.util.*; class GFG { // Main Method public static void main(String[] args) { // Declaring the LinkedList LinkedList<Integer> ll = new LinkedList<Integer>(); // Appending new elements at // the end of the list for (int i = 1; i <= 5; i++) ll.add(i); // Printing elements System.out.println(ll); // Remove element at index 3 ll.remove(3); // Displaying the List // after deletion System.out.println(ll); // Printing elements one by one for (int i = 0; i < ll.size(); i++) System.out.print(ll.get(i) + \" \"); }}",
"e": 39864,
"s": 39119,
"text": null
},
{
"code": null,
"e": 39901,
"s": 39864,
"text": "[1, 2, 3, 4, 5]\n[1, 2, 3, 5]\n1 2 3 5"
},
{
"code": null,
"e": 40333,
"s": 39903,
"text": "C. Vector: A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This is identical to ArrayList in terms of implementation. However, the primary difference between a vector and an ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized. Let’s understand the Vector with an example:"
},
{
"code": null,
"e": 40338,
"s": 40333,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of Vectorimport java.io.*;import java.util.*; class GFG { // Main Method public static void main(String[] args) { // Declaring the Vector Vector<Integer> v = new Vector<Integer>(); // Appending new elements at // the end of the list for (int i = 1; i <= 5; i++) v.add(i); // Printing elements System.out.println(v); // Remove element at index 3 v.remove(3); // Displaying the Vector // after deletion System.out.println(v); // Printing elements one by one for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + \" \"); }}",
"e": 41062,
"s": 40338,
"text": null
},
{
"code": null,
"e": 41099,
"s": 41062,
"text": "[1, 2, 3, 4, 5]\n[1, 2, 3, 5]\n1 2 3 5"
},
{
"code": null,
"e": 41457,
"s": 41101,
"text": "D. Stack: Stack class models and implements the Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be referred to as the subclass of Vector. Let’s understand the stack with an example:"
},
{
"code": null,
"e": 41462,
"s": 41457,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of a stackimport java.util.*;public class GFG { // Main Method public static void main(String args[]) { Stack<String> stack = new Stack<String>(); stack.push(\"Geeks\"); stack.push(\"For\"); stack.push(\"Geeks\"); stack.push(\"Geeks\"); // Iterator for the stack Iterator<String> itr = stack.iterator(); // Printing the stack while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } System.out.println(); stack.pop(); // Iterator for the stack itr = stack.iterator(); // Printing the stack while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } }}",
"e": 42230,
"s": 41462,
"text": null
},
{
"code": null,
"e": 42269,
"s": 42230,
"text": "Geeks For Geeks Geeks \nGeeks For Geeks"
},
{
"code": null,
"e": 42529,
"s": 42271,
"text": "Note: Stack is a subclass of Vector and a legacy class. It is thread-safe which might be overhead in an environment where thread safety is not needed. An alternate to Stack is to use ArrayDequeue which is not thread-safe and has faster array implementation."
},
{
"code": null,
"e": 43138,
"s": 42529,
"text": "4. Queue Interface: As the name suggests, a queue interface maintains the FIFO(First In First Out) order similar to a real-world queue line. This interface is dedicated to storing all the elements where the order of the elements matter. For example, whenever we try to book a ticket, the tickets are sold on a first come first serve basis. Therefore, the person whose request arrives first into the queue gets the ticket. There are various classes like PriorityQueue, ArrayDeque, etc. Since all these subclasses implement the queue, we can instantiate a queue object with any of these classes. For example, "
},
{
"code": null,
"e": 43214,
"s": 43138,
"text": "Queue <T> pq = new PriorityQueue<> (); Queue <T> ad = new ArrayDeque<> (); "
},
{
"code": null,
"e": 43251,
"s": 43214,
"text": "Where T is the type of the object. "
},
{
"code": null,
"e": 43925,
"s": 43251,
"text": "The most frequently used implementation of the queue interface is the PriorityQueue. Priority Queue: A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority and this class is used in these cases. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. Let’s understand the priority queue with an example:"
},
{
"code": null,
"e": 43930,
"s": 43925,
"text": "Java"
},
{
"code": "// Java program to demonstrate the working of// priority queue in Javaimport java.util.*; class GfG { // Main Method public static void main(String args[]) { // Creating empty priority queue PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}",
"e": 44658,
"s": 43930,
"text": null
},
{
"code": null,
"e": 44667,
"s": 44658,
"text": "10\n10\n15"
},
{
"code": null,
"e": 45105,
"s": 44669,
"text": "5. Deque Interface: This is a very slight variation of the queue data structure. Deque, also known as a double-ended queue, is a data structure where we can add and remove the elements from both ends of the queue. This interface extends the queue interface. The class which implements this interface is ArrayDeque. Since ArrayDeque class implements the Deque interface, we can instantiate a deque object with this class. For example, "
},
{
"code": null,
"e": 45141,
"s": 45105,
"text": "Deque<T> ad = new ArrayDeque<> (); "
},
{
"code": null,
"e": 45178,
"s": 45141,
"text": "Where T is the type of the object. "
},
{
"code": null,
"e": 45241,
"s": 45178,
"text": "The class which implements the deque interface is ArrayDeque. "
},
{
"code": null,
"e": 45620,
"s": 45241,
"text": "ArrayDeque: ArrayDeque class which is implemented in the collection framework provides us with a way to apply resizable-array. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue. Array deques have no capacity restrictions and they grow as necessary to support usage. Let’s understand ArrayDeque with an example: "
},
{
"code": null,
"e": 45625,
"s": 45620,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// ArrayDeque class in Java import java.util.*;public class ArrayDequeDemo { public static void main(String[] args) { // Initializing an deque ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(10); // add() method to insert de_que.add(10); de_que.add(20); de_que.add(30); de_que.add(40); de_que.add(50); System.out.println(de_que); // clear() method de_que.clear(); // addFirst() method to insert the // elements at the head de_que.addFirst(564); de_que.addFirst(291); // addLast() method to insert the // elements at the tail de_que.addLast(24); de_que.addLast(14); System.out.println(de_que); }}",
"e": 46422,
"s": 45625,
"text": null
},
{
"code": null,
"e": 46462,
"s": 46422,
"text": "[10, 20, 30, 40, 50]\n[291, 564, 24, 14]"
},
{
"code": null,
"e": 46902,
"s": 46464,
"text": "6. Set Interface: A set is an unordered collection of objects in which duplicate values cannot be stored. This collection is used when we wish to avoid the duplication of the objects and wish to store only the unique objects. This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc. Since all the subclasses implement the set, we can instantiate a set object with any of these classes. For example,"
},
{
"code": null,
"e": 47000,
"s": 46902,
"text": "Set<T> hs = new HashSet<> (); Set<T> lhs = new LinkedHashSet<> (); Set<T> ts = new TreeSet<> (); "
},
{
"code": null,
"e": 47037,
"s": 47000,
"text": "Where T is the type of the object. "
},
{
"code": null,
"e": 47101,
"s": 47037,
"text": "The following are the classes that implement the Set interface:"
},
{
"code": null,
"e": 47437,
"s": 47101,
"text": "A. HashSet: The HashSet class is an inherent implementation of the hash table data structure. The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s understand HashSet with an example:"
},
{
"code": null,
"e": 47442,
"s": 47437,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of a HashSetimport java.util.*; public class HashSetDemo { // Main Method public static void main(String args[]) { // Creating HashSet and // adding elements HashSet<String> hs = new HashSet<String>(); hs.add(\"Geeks\"); hs.add(\"For\"); hs.add(\"Geeks\"); hs.add(\"Is\"); hs.add(\"Very helpful\"); // Traversing elements Iterator<String> itr = hs.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}",
"e": 48016,
"s": 47442,
"text": null
},
{
"code": null,
"e": 48042,
"s": 48016,
"text": "Very helpful\nGeeks\nFor\nIs"
},
{
"code": null,
"e": 48275,
"s": 48044,
"text": "B. LinkedHashSet: A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked list to store the data and retains the ordering of the elements. Let’s understand the LinkedHashSet with an example: "
},
{
"code": null,
"e": 48280,
"s": 48275,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of a LinkedHashSetimport java.util.*; public class LinkedHashSetDemo { // Main Method public static void main(String args[]) { // Creating LinkedHashSet and // adding elements LinkedHashSet<String> lhs = new LinkedHashSet<String>(); lhs.add(\"Geeks\"); lhs.add(\"For\"); lhs.add(\"Geeks\"); lhs.add(\"Is\"); lhs.add(\"Very helpful\"); // Traversing elements Iterator<String> itr = lhs.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}",
"e": 48891,
"s": 48280,
"text": null
},
{
"code": null,
"e": 48917,
"s": 48891,
"text": "Geeks\nFor\nIs\nVery helpful"
},
{
"code": null,
"e": 49375,
"s": 48919,
"text": "7. Sorted Set Interface: This interface is very similar to the set interface. The only difference is that this interface has extra methods that maintain the ordering of the elements. The sorted set interface extends the set interface and is used to handle the data which needs to be sorted. The class which implements this interface is TreeSet. Since this class implements the SortedSet, we can instantiate a SortedSet object with this class. For example,"
},
{
"code": null,
"e": 49412,
"s": 49375,
"text": "SortedSet<T> ts = new TreeSet<> (); "
},
{
"code": null,
"e": 49449,
"s": 49412,
"text": "Where T is the type of the object. "
},
{
"code": null,
"e": 49937,
"s": 49449,
"text": "The class which implements the sorted set interface is TreeSet. TreeSet: The TreeSet class uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. Let’s understand TreeSet with an example:"
},
{
"code": null,
"e": 49942,
"s": 49937,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of a TreeSetimport java.util.*; public class TreeSetDemo { // Main Method public static void main(String args[]) { // Creating TreeSet and // adding elements TreeSet<String> ts = new TreeSet<String>(); ts.add(\"Geeks\"); ts.add(\"For\"); ts.add(\"Geeks\"); ts.add(\"Is\"); ts.add(\"Very helpful\"); // Traversing elements Iterator<String> itr = ts.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}",
"e": 50516,
"s": 49942,
"text": null
},
{
"code": null,
"e": 50542,
"s": 50516,
"text": "For\nGeeks\nIs\nVery helpful"
},
{
"code": null,
"e": 51031,
"s": 50544,
"text": "8. Map Interface: A map is a data structure that supports the key-value pair mapping for the data. This interface doesn’t support duplicate keys because the same key cannot have multiple mappings. A map is useful if there is data and we wish to perform operations on the basis of the key. This map interface is implemented by various classes like HashMap, TreeMap, etc. Since all the subclasses implement the map, we can instantiate a map object with any of these classes. For example, "
},
{
"code": null,
"e": 51127,
"s": 51031,
"text": "Map<T> hm = new HashMap<> (); Map<T> tm = new TreeMap<> (); Where T is the type of the object. "
},
{
"code": null,
"e": 51655,
"s": 51127,
"text": "The frequently used implementation of a Map interface is a HashMap. HashMap: HashMap provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value in a HashMap, we must know its key. HashMap uses a technique called Hashing. Hashing is a technique of converting a large String to a small String that represents the same String so that the indexing and search operations are faster. HashSet also uses HashMap internally. Let’s understand the HashMap with an example:"
},
{
"code": null,
"e": 51660,
"s": 51655,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of a HashMapimport java.util.*; public class HashMapDemo { // Main Method public static void main(String args[]) { // Creating HashMap and // adding elements HashMap<Integer, String> hm = new HashMap<Integer, String>(); hm.put(1, \"Geeks\"); hm.put(2, \"For\"); hm.put(3, \"Geeks\"); // Finding the value for a key System.out.println(\"Value for 1 is \" + hm.get(1)); // Traversing through the HashMap for (Map.Entry<Integer, String> e : hm.entrySet()) System.out.println(e.getKey() + \" \" + e.getValue()); }}",
"e": 52312,
"s": 51660,
"text": null
},
{
"code": null,
"e": 52355,
"s": 52312,
"text": "Value for 1 is Geeks\n1 Geeks\n2 For\n3 Geeks"
},
{
"code": null,
"e": 52470,
"s": 52357,
"text": "List InterfaceAbstract List ClassAbstract Sequential List ClassArray ListVector ClassStack ClassLinkedList Class"
},
{
"code": null,
"e": 52490,
"s": 52470,
"text": "Abstract List Class"
},
{
"code": null,
"e": 52521,
"s": 52490,
"text": "Abstract Sequential List Class"
},
{
"code": null,
"e": 52532,
"s": 52521,
"text": "Array List"
},
{
"code": null,
"e": 52545,
"s": 52532,
"text": "Vector Class"
},
{
"code": null,
"e": 52557,
"s": 52545,
"text": "Stack Class"
},
{
"code": null,
"e": 52574,
"s": 52557,
"text": "LinkedList Class"
},
{
"code": null,
"e": 52790,
"s": 52574,
"text": "Queue InterfaceBlocking Queue InterfaceAbstractQueue ClassPriorityQueue ClassPriorityBlockingQueue ClassConcurrentLinkedQueue ClassArrayBlockingQueue ClassDelayQueue ClassLinkedBlockingQueue ClassLinkedTransferQueue"
},
{
"code": null,
"e": 52815,
"s": 52790,
"text": "Blocking Queue Interface"
},
{
"code": null,
"e": 52835,
"s": 52815,
"text": "AbstractQueue Class"
},
{
"code": null,
"e": 52855,
"s": 52835,
"text": "PriorityQueue Class"
},
{
"code": null,
"e": 52883,
"s": 52855,
"text": "PriorityBlockingQueue Class"
},
{
"code": null,
"e": 52911,
"s": 52883,
"text": "ConcurrentLinkedQueue Class"
},
{
"code": null,
"e": 52936,
"s": 52911,
"text": "ArrayBlockingQueue Class"
},
{
"code": null,
"e": 52953,
"s": 52936,
"text": "DelayQueue Class"
},
{
"code": null,
"e": 52979,
"s": 52953,
"text": "LinkedBlockingQueue Class"
},
{
"code": null,
"e": 52999,
"s": 52979,
"text": "LinkedTransferQueue"
},
{
"code": null,
"e": 53081,
"s": 52999,
"text": "Deque InterfaceBlockingDeque InterfaceConcurrentLinkedDeque ClassArrayDeque Class"
},
{
"code": null,
"e": 53105,
"s": 53081,
"text": "BlockingDeque Interface"
},
{
"code": null,
"e": 53133,
"s": 53105,
"text": "ConcurrentLinkedDeque Class"
},
{
"code": null,
"e": 53150,
"s": 53133,
"text": "ArrayDeque Class"
},
{
"code": null,
"e": 53275,
"s": 53150,
"text": "Set InterfaceAbstract Set ClassCopyOnWriteArraySet ClassEnumSet ClassConcurrentHashMap ClassHashSet ClassLinkedHashSet Class"
},
{
"code": null,
"e": 53294,
"s": 53275,
"text": "Abstract Set Class"
},
{
"code": null,
"e": 53320,
"s": 53294,
"text": "CopyOnWriteArraySet Class"
},
{
"code": null,
"e": 53334,
"s": 53320,
"text": "EnumSet Class"
},
{
"code": null,
"e": 53358,
"s": 53334,
"text": "ConcurrentHashMap Class"
},
{
"code": null,
"e": 53372,
"s": 53358,
"text": "HashSet Class"
},
{
"code": null,
"e": 53392,
"s": 53372,
"text": "LinkedHashSet Class"
},
{
"code": null,
"e": 53468,
"s": 53392,
"text": "SortedSet InterfaceNavigableSet InterfaceTreeSetConcurrentSkipListSet Class"
},
{
"code": null,
"e": 53491,
"s": 53468,
"text": "NavigableSet Interface"
},
{
"code": null,
"e": 53499,
"s": 53491,
"text": "TreeSet"
},
{
"code": null,
"e": 53527,
"s": 53499,
"text": "ConcurrentSkipListSet Class"
},
{
"code": null,
"e": 53755,
"s": 53527,
"text": "Map InterfaceSortedMap InterfaceNavigableMap InterfaceConcurrentMap InterfaceTreeMap ClassAbstractMap ClassConcurrentHashMap ClassEnumMap ClassHashMap ClassIdentityHashMap ClassLinkedHashMap ClassHashTable ClassProperties Class"
},
{
"code": null,
"e": 53775,
"s": 53755,
"text": "SortedMap Interface"
},
{
"code": null,
"e": 53798,
"s": 53775,
"text": "NavigableMap Interface"
},
{
"code": null,
"e": 53822,
"s": 53798,
"text": "ConcurrentMap Interface"
},
{
"code": null,
"e": 53836,
"s": 53822,
"text": "TreeMap Class"
},
{
"code": null,
"e": 53854,
"s": 53836,
"text": "AbstractMap Class"
},
{
"code": null,
"e": 53878,
"s": 53854,
"text": "ConcurrentHashMap Class"
},
{
"code": null,
"e": 53892,
"s": 53878,
"text": "EnumMap Class"
},
{
"code": null,
"e": 53906,
"s": 53892,
"text": "HashMap Class"
},
{
"code": null,
"e": 53928,
"s": 53906,
"text": "IdentityHashMap Class"
},
{
"code": null,
"e": 53948,
"s": 53928,
"text": "LinkedHashMap Class"
},
{
"code": null,
"e": 53964,
"s": 53948,
"text": "HashTable Class"
},
{
"code": null,
"e": 53981,
"s": 53964,
"text": "Properties Class"
},
{
"code": null,
"e": 54256,
"s": 53981,
"text": "Other Important ConceptsHow to convert HashMap to ArrayListRandomly select items from a ListHow to add all items from a collection to an ArrayListConversion of Java Maps to ListArray to ArrayList ConversionArrayList to Array ConversionDifferences between Array and ArrayList"
},
{
"code": null,
"e": 54292,
"s": 54256,
"text": "How to convert HashMap to ArrayList"
},
{
"code": null,
"e": 54326,
"s": 54292,
"text": "Randomly select items from a List"
},
{
"code": null,
"e": 54381,
"s": 54326,
"text": "How to add all items from a collection to an ArrayList"
},
{
"code": null,
"e": 54413,
"s": 54381,
"text": "Conversion of Java Maps to List"
},
{
"code": null,
"e": 54443,
"s": 54413,
"text": "Array to ArrayList Conversion"
},
{
"code": null,
"e": 54473,
"s": 54443,
"text": "ArrayList to Array Conversion"
},
{
"code": null,
"e": 54513,
"s": 54473,
"text": "Differences between Array and ArrayList"
},
{
"code": null,
"e": 54537,
"s": 54516,
"text": "ThakurYogeshwarSingh"
},
{
"code": null,
"e": 54554,
"s": 54537,
"text": "SiddharthPandey7"
},
{
"code": null,
"e": 54561,
"s": 54554,
"text": "kartik"
},
{
"code": null,
"e": 54573,
"s": 54561,
"text": "KaashyapMSK"
},
{
"code": null,
"e": 54584,
"s": 54573,
"text": "suraj mall"
},
{
"code": null,
"e": 54601,
"s": 54584,
"text": "Java-Collections"
},
{
"code": null,
"e": 54606,
"s": 54601,
"text": "Java"
},
{
"code": null,
"e": 54611,
"s": 54606,
"text": "Java"
},
{
"code": null,
"e": 54628,
"s": 54611,
"text": "Java-Collections"
},
{
"code": null,
"e": 54726,
"s": 54628,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 54770,
"s": 54726,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 54806,
"s": 54770,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 54831,
"s": 54806,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 54863,
"s": 54831,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 54894,
"s": 54863,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 54918,
"s": 54894,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 54946,
"s": 54918,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 54992,
"s": 54946,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 55007,
"s": 54992,
"text": "Stream In Java"
}
] |
How to remove rows from a Numpy array based on multiple conditions ? - GeeksforGeeks | 03 Jul, 2021
In this article, we will learn how to remove rows from a NumPy array based on multiple conditions. For doing our task, we will need some inbuilt methods provided by the NumPy module which are as follows:
np.delete(ndarray, index, axis): Delete items of rows or columns from the NumPy array based on given index conditions and axis specified, the parameter ndarray is the array on which the manipulation will happen, the index is the particular rows based on conditions to be deleted, axis=0 for removing rows in our case.
np.where(conditions): Operate on array items depending on conditions on rows or columns depending on the axis given.
Note: For 2-dimensional NumPy arrays, rows are removed if axis=0, and columns are removed if axis=1. But here we intend is to remove rows, so we will keep axis=0.
Let us take the NumPy array sample. Here we have taken a NumPy array having elements from 0 to 40 and reshaped the array into 8 rows and 5 columns.
Python3
import numpy as np nparray = np.arange(40).reshape((8, 5))print("Given numpy array:\n", nparray)
Output:
Example 1: Remove rows having elements between 5 and 20 from the NumPy array
Here np.where((nparray >= 5) & (nparray <= 20))[0], axis=0) means it will delete the rows in which there is at least one or more elements that is greater than or equal to 5 and less than or equal to 20. So, 2nd, 3rd,4th, and 5th rows have elements according to the conditions given, so it gets deleted or removed.
Python3
nparray = np.delete(nparray, np.where( (nparray >= 5) & (nparray <= 20))[0], axis=0) print("After deletion of rows containing numbers between 5 and 20: \n", nparray)
Output:
Example 2: Remove rows whose first element is greater than 25 and less than 35 from the NumPy array
Here (np.where(nparray[:, 0] >= 25) & (nparray[:, 0] <= 35))[0], axis=0)means it will delete the rows in which there is at least one or more elements whose first element is greater than or equal to 25 and less than to equal to 35. The nparray[:, 0] to point to the first element of each row. So, 6th, 7th, 8th rows have elements according to the conditions given, so it gets deleted or removed.
Python3
nparray = np.delete(nparray, np.where( (nparray[:, 0] >= 25) & (nparray[:, 0] <= 35))[0], axis=0) print("After deletion of rows whose first element \is between 25 and 35:\n", nparray)
Output:
Example 3: Remove rows whose third item is divisible by 2, 5th and 4th items are divisible by 3
Here np.where((nparray[:, 2] % 2 == 0) | (nparray[:, 4] % 3 == 0)| (nparray[:, 3] % 3 == 0))[0], axis=0) means it will delete the rows in which there is at least one or more elements whose 3rd column item(s) are divisible by 3 or rows in which there is at least one or more elements whose 5th and 4th column item(s) are divisible by 3 axis=0 to remove the rows. The nparray[:, 2], nparray[:, 4], nparray[:, 3] to point to the third, 5th, and 4th item of each row respectively. So, 6th, 7rd, 8th rows have elements according to the conditions given, so it gets deleted or removed.
Python3
nparray = np.delete(nparray, np.where((nparray[:, 2] % 2 == 0) | ( nparray[:, 4] % 3 == 0) | (nparray[:, 3] % 3 == 0))[0], axis=0) print("After removing required rows :\n", nparray)
Output:
akshaysingh98088
Picked
Python numpy-arrayManipulation
Python numpy-Indexing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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 | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n03 Jul, 2021"
},
{
"code": null,
"e": 24522,
"s": 24318,
"text": "In this article, we will learn how to remove rows from a NumPy array based on multiple conditions. For doing our task, we will need some inbuilt methods provided by the NumPy module which are as follows:"
},
{
"code": null,
"e": 24840,
"s": 24522,
"text": "np.delete(ndarray, index, axis): Delete items of rows or columns from the NumPy array based on given index conditions and axis specified, the parameter ndarray is the array on which the manipulation will happen, the index is the particular rows based on conditions to be deleted, axis=0 for removing rows in our case."
},
{
"code": null,
"e": 24957,
"s": 24840,
"text": "np.where(conditions): Operate on array items depending on conditions on rows or columns depending on the axis given."
},
{
"code": null,
"e": 25120,
"s": 24957,
"text": "Note: For 2-dimensional NumPy arrays, rows are removed if axis=0, and columns are removed if axis=1. But here we intend is to remove rows, so we will keep axis=0."
},
{
"code": null,
"e": 25269,
"s": 25120,
"text": "Let us take the NumPy array sample. Here we have taken a NumPy array having elements from 0 to 40 and reshaped the array into 8 rows and 5 columns."
},
{
"code": null,
"e": 25277,
"s": 25269,
"text": "Python3"
},
{
"code": "import numpy as np nparray = np.arange(40).reshape((8, 5))print(\"Given numpy array:\\n\", nparray)",
"e": 25374,
"s": 25277,
"text": null
},
{
"code": null,
"e": 25382,
"s": 25374,
"text": "Output:"
},
{
"code": null,
"e": 25459,
"s": 25382,
"text": "Example 1: Remove rows having elements between 5 and 20 from the NumPy array"
},
{
"code": null,
"e": 25773,
"s": 25459,
"text": "Here np.where((nparray >= 5) & (nparray <= 20))[0], axis=0) means it will delete the rows in which there is at least one or more elements that is greater than or equal to 5 and less than or equal to 20. So, 2nd, 3rd,4th, and 5th rows have elements according to the conditions given, so it gets deleted or removed."
},
{
"code": null,
"e": 25781,
"s": 25773,
"text": "Python3"
},
{
"code": "nparray = np.delete(nparray, np.where( (nparray >= 5) & (nparray <= 20))[0], axis=0) print(\"After deletion of rows containing numbers between 5 and 20: \\n\", nparray)",
"e": 25955,
"s": 25781,
"text": null
},
{
"code": null,
"e": 25964,
"s": 25955,
"text": " Output:"
},
{
"code": null,
"e": 26064,
"s": 25964,
"text": "Example 2: Remove rows whose first element is greater than 25 and less than 35 from the NumPy array"
},
{
"code": null,
"e": 26459,
"s": 26064,
"text": "Here (np.where(nparray[:, 0] >= 25) & (nparray[:, 0] <= 35))[0], axis=0)means it will delete the rows in which there is at least one or more elements whose first element is greater than or equal to 25 and less than to equal to 35. The nparray[:, 0] to point to the first element of each row. So, 6th, 7th, 8th rows have elements according to the conditions given, so it gets deleted or removed."
},
{
"code": null,
"e": 26467,
"s": 26459,
"text": "Python3"
},
{
"code": "nparray = np.delete(nparray, np.where( (nparray[:, 0] >= 25) & (nparray[:, 0] <= 35))[0], axis=0) print(\"After deletion of rows whose first element \\is between 25 and 35:\\n\", nparray)",
"e": 26654,
"s": 26467,
"text": null
},
{
"code": null,
"e": 26662,
"s": 26654,
"text": "Output:"
},
{
"code": null,
"e": 26758,
"s": 26662,
"text": "Example 3: Remove rows whose third item is divisible by 2, 5th and 4th items are divisible by 3"
},
{
"code": null,
"e": 27338,
"s": 26758,
"text": "Here np.where((nparray[:, 2] % 2 == 0) | (nparray[:, 4] % 3 == 0)| (nparray[:, 3] % 3 == 0))[0], axis=0) means it will delete the rows in which there is at least one or more elements whose 3rd column item(s) are divisible by 3 or rows in which there is at least one or more elements whose 5th and 4th column item(s) are divisible by 3 axis=0 to remove the rows. The nparray[:, 2], nparray[:, 4], nparray[:, 3] to point to the third, 5th, and 4th item of each row respectively. So, 6th, 7rd, 8th rows have elements according to the conditions given, so it gets deleted or removed."
},
{
"code": null,
"e": 27346,
"s": 27338,
"text": "Python3"
},
{
"code": "nparray = np.delete(nparray, np.where((nparray[:, 2] % 2 == 0) | ( nparray[:, 4] % 3 == 0) | (nparray[:, 3] % 3 == 0))[0], axis=0) print(\"After removing required rows :\\n\", nparray)",
"e": 27531,
"s": 27346,
"text": null
},
{
"code": null,
"e": 27539,
"s": 27531,
"text": "Output:"
},
{
"code": null,
"e": 27556,
"s": 27539,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 27563,
"s": 27556,
"text": "Picked"
},
{
"code": null,
"e": 27594,
"s": 27563,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 27616,
"s": 27594,
"text": "Python numpy-Indexing"
},
{
"code": null,
"e": 27629,
"s": 27616,
"text": "Python-numpy"
},
{
"code": null,
"e": 27636,
"s": 27629,
"text": "Python"
},
{
"code": null,
"e": 27734,
"s": 27636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27766,
"s": 27734,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27822,
"s": 27766,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27864,
"s": 27822,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27906,
"s": 27864,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27928,
"s": 27906,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27959,
"s": 27928,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27998,
"s": 27959,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28053,
"s": 27998,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28082,
"s": 28053,
"text": "Create a directory in Python"
}
] |
Understanding Dynamic Programming | by Aniruddha Karajgi | Towards Data Science | Dynamic programming, or DP, is an optimization technique. It is used in several fields, though this article focuses on its applications in the field of algorithms and computer programming. Its a topic often asked in algorithmic interviews.
Since DP isn’t very intuitive, most people (myself included!) often find it tricky to model a problem as a dynamic programming model. In this post, we’ll discuss when we use DP, followed by its types and then finally work through an example.
When is DP used? - Overlapping Sub-problems - Optimal SubstructureThe Two kinds of DP - The top-down approach - The bottom-up approachAn example - The Problem - The analysis - A recursive Solution - The base case - A dynamic programming approach - Improving the Algorithm
There are two necessary conditions a problem must satisfy for DP to work.
Overlapping Sub-problems
Optimal substructure
Let's go over these in a little more detail.
This property is exactly what it sounds like: repeating sub-problems. But for this to make sense, we need to know what a sub-problem is.
A sub-problem is simply a smaller version of the problem at hand. In most cases, this would mean smaller parameter values which you would pass to your recursive function.
If you’re looking for a particular page in a book, what would you do? You’d open the book to a particular page and compare the page number you’re on with the page number you’re looking for.
If the current page is smaller than the required page, you’d start looking in between the current page and the last page. On the other hand, if the current page number is greater, you’d start searching between the start of the book and the current page.
You’d continue this until you found the page.
If you had to model this as a recursive function, what would that look like? Maybe something like this.
Note: The following snippets have been written in a form of pseudocode to improve readability
Pretty straightforward. There’s a getpage function which returns the page (target_page, here) we’re looking for. The function looks at the middle page between from_page and to_page and checks if we have a match.
If not, the function looks at either the left half or the right half of the section we are looking at.
But what do those two recursive calls to getpage represent? You’ll notice that at each recursive call, we are reducing our search space by half. What we’re doing is solving the same problem, that is, looking for a specific page, in a smaller space. We’re solving sub-problems.
Divide and Conquer, or DAC algorithms work through the principle of sub-problems. The “divide” part refers to splitting a problem into sub-problems. Sorting algorithms like mergesort and quicksort are great examples. Note that binary search isn’t exactly a DAC algorithm for the simple reason that it doesn’t have a “combine” step, whereas an actual divide and conquer algorithm would combine the results of its sub-problems to get the final solution.
Now that we have answered the question of what a sub-problem is, we move on to the other word: “overlapping”.
When these sub-problems have to be solved more than once, they are said to be overlapping. Look at the call graph for computing the value of the nth Fibonacci term.
The recurrence relation is:
the relationf(n) = f(n - 1) + f(n-2)the base casef(0) = 0f(1) = 1
The calls have been shaded to represent overlapping subproblems. Compare this with something like binary search, where the subproblems aren’t overlapping.
The optimal substructure property is slightly more intricate: it refers to the scenario where optimal solutions to sub-problems can directly be considered when computed the overall optimal solution.
A quick example? Say you want to find the shortest path from A to B. Let X be an intermediate point between A and B with a single edge connecting it to A.
To solve this, we can find the shortest path from all intermediate nodes (X) to B, and then find the path from A to X plus the shortest path from X to B which is shortest for all X.
shortest(A, B) = min(AX + shortest(X, B)) for all intermediate nodes X.
What we’re doing here is using an optimal intermediate solution (shortest(X, B)) and use that (as opposed to considering every solution for a sub-problem) to find the final optimal answer.
In a top-down approach, we start from the highest level of our problem. In this approach, we initially check if have already solved the current sub-problem. If we have, we just return that value. If not, we solve that sub-problem. We use recursive calls to solve our sub-problem.
Since those calls require solving smaller sub-problems which we haven’t seen before, we continue this way, until we encounter a sub-problem we have either solved or know the answer to trivially.
In this approach, we start at the very bottom and then work our way to the top. Since we start from the “base case”, and use our recurrence relation, we don’t really need recursion, and so, this approach is iterative.
The main difference between the two approaches is that bottom-up calculates all solutions, while top-down computes only those that are required. For example, to find the shortest path between source and destination, using the top-down approach, we only compute the distances with intermediate points near the shortest path, choosing the minimum at each stage.
On the other hand, in a bottom-up approach, we end up calculating the shortest distance between each point on the grid and the destination, finally returning the shortest distance from the start to the end.
As a comparison, let's look at a possible top-down and bottom-up function that returns the nth Fibonacci term.
While both approaches have the same asymptotic time complexities, the recursive calls in a top-down implementation may lead to a stack overflow, which is a non-issue owing to the iterative nature of the bottom-up approach.
Remember that though we implement the latter iteratively, your logic would still use the recurrence relation from the very basic recursive approach, as we shall see in this example.
Let's go over a problem which we’ll solve using both approaches to dynamic programming.
Find the maximum sum of elements in an array ensuring that no adjacent elements are included. Let’s assume that no elements are negative.
example 1:[1, 2, 3] => 1 + 3 = 4example 2:[1, 1, 1, 1] => 1 + 1 = 2example 3:[2, 5, 2] => 5 = 5
First, let's try a greedy approach.
Since our goal is to maximize the sum of the elements we choose, we could hope to accomplish this by choosing the biggest elements, ignoring its neighbours, and then continuing this way. Here, we’re ensuring that at each step of the way, we have a maximum sum. But this would be correct only in a local context, while we are, of course, looking for a global solution.
This approach could work in certain cases.
[1, 5, 1, 10, 1, 5, 1]
Here, we first choose 10, since it’s the biggest element. We then ignore its neighbours, so that we don’t violate the condition that we aren’t allowed to choose adjacent elements.
Next, we choose both the 5’s, since they’re the next biggest elements, and then ignore their neighbours. Our algorithm ends here since there aren’t any elements left. The result we get — 10 + 5 + 5 — is in fact, the right answer.
But this won’t always work. Take the following example:
[1, 1, 9, 10, 9, 1, 1]
At every step, if you chose the maximum element, ignored its neighbours and continued that way, you’d end up choosing 10, then 1 and then 1 again after ignoring both the 9's, which would add up to 12, but the right answer would be 1 + 9 + 9 + 1, which is 20.
Its clear this approach isn’t the right one. Let’s start from a basic recursive solution and work up to one that uses dynamic programming one.
This is the difference between the greedy and dynamic programming approaches. While a greedy approach focuses on doing its best to reach the goal at every step, DP looks at the overall picture. With a greedy approach, there’s no guarantee you’ll even end up with an optimal solution, unlike DP. Greedy algorithms often get trapped in local maxima, leading to sub-optimal solutions.
After thinking for a bit, you can probably see that we have a condition to keep in mind: no adjacent elements. You can probably figure out that:
we can choose to either consider an element in our sum or ignore it
if we consider it, we will have to ignore its adjacent element
For the sake of brevity, let f(a..b) represent a call to f our array from index a to index b (both inclusive). That function f would represent our recursive function which would solve the problem.
So f(0..4) would mean running the function from index 0 to index 4.
The two arrows pointing from a cell represent our choices of subsequent function calls. Since this is a maximization problem, we’d have to choose the maximum out of these options.
Let’s come back to our array.
[5, 10, 100, 10, 5]
Keeping the conditions discussed above in mind let’s actually write down what we would be doing.
Our first call would be on the entire array, which is of length 5 as can be seen above.
f(0..4)
For the element at index 0 (which happens to be 5 here), we can either choose to:
include it in our sum: our current sum would then be 5 + the maximum sum of the rest of the array, but excluding the next element (index 1). Thus, our sum becomes 5 + f(2..4). Or to generalize it, arr[0] + f(2..4)
exclude it: our current sum would then just be equal to the maximum sum of the remaining array. This can be written as: 0 + f(1..4). Notice that our next call is from index 1 and not 2 as in the previous case. Since we aren’t considering the element at index 0, we are free to consider the element at index 1 — we aren’t forced to ignore it.
The graph here visually explains this. As mentioned earlier, all arrows at a given level represent our choices, from which we choose the greatest one.
So our final answer would be:
f(0..4) = max(arr[0] + f(2..4), f(1..4))
Let’s expand this for the next iteration.
First, we’ll do it for the left tree, which is f(2..4). This is just like what we did for the first call to f. Remember that the arr[0] + part is still there. It will be added to the value of f(2..4) on our way back up the call tree.
Our choices:
consider arr[2] in our sum: our sum at this stage becomes arr[2] + f(4..4). Remember that since we’re considering the element at index 2, we would have to ignore the next element — index 3.
ignore arr[2]: our sum here is the same as the maximum result of the remaining array without having to ignore the adjacent element. So, that's f(3..4).
Just like before, the value of f(2..4) would be the maximum of our two choices.
f(2..4) = max(arr[2] + f(4..4), f(3..4))
What do you think f(4..4) would evaluate to? Following our notation, it is the result of our function call on the array from index 4 to ... well, index 4. That means that we are calling the function on a single element. The maximum sum of a single element is itself.
Another thing to keep in mind: in f(a..b), a should never be greater than b. Since this call represents starting from index a and going up to index b, we would have to return 0 if a ever gets bigger than b. There is no maximum sum if there are no elements.
We have our base case here. Our function f, when called on a single element, would return that element directly and returns 0 if we are not in a valid range. There are no further recursive calls. That’s why its called the base case.
In our case, our call to f(3..4) leads to an invalid call to f(5..4), which we handle by returning 0. We’ll generalize this later.
f(4..4) = arr[4]f(5..4) = 0
Let’s have another look at our results.
first call:f(0..4) = max(arr[0] + f(2..4), f(1..4))second call:f(2..4) = max(arr[2] + f(4..4), f(3..4))the base case:f(4..4) = arr[4]f(5..4) = 0
Notice a pattern in the first two results? If we generalize these, we get:
f(a..b) = max(arr[a] + f(a+2 .. b), f(a+1, b))
This still isn’t the most simplified version of our relation. Notice the occurrences of b here. In fact, go back and look at our specific calls in the previous block.
They don’t change. There’s no b + 1 or b + 2. It’s always b. And what’s the value of b in our first call? The last index. Since b is constant throughout our algorithm, we can remove it.
Our recurrence relation becomes:
f(a) = max(arr[a] + f(a+2), f(a+1))
where f(a) is a call on the array from index a onwards.
Another thing to realize is that similar to how we removed b since it was always equal to the last index in the array, the base case, which refers to a single element, would only happen if that element was the last in the array.
A generalized version of our base case is:
f(n-1) = arr[n-1] where n is the size of the arrayf(a) = 0 if a >= n where n is the size of the array
Thus, we have our relation:
f(a) = max(arr[a] + f(a+2), f(a+1))f(n-1) = arr[n-1] where n is the size of the arrayf(a) = 0 if a >= n where n is the size of the array
Let’s implement the recursive approach based on this relation.
This function would be called like so:
array := [1, 5, 2, 4, ...]return f(array, 0)
What would be the complexity of this?
If we were to approximate the complexity based on the size of the array (n) we are operating on, we get something like this:
T(n) = T(n-2) + T(n-1) + O(1)T(0) = O(1)
Intuitively, every call to f on an array of size n — represented as T(n) — leads to two calls on f on arrays of size n-2 and n-1. That is, at each stage, we’re doubling the number of calls to f.
The asymptotic time complexity is exponential. With the above reasoning, we get O(2^n).
This is a loose estimate on the upper bound, since the n-2 tree is bound to end before the n-1 tree, and so we are doing slightly less than doubling the calls. The actual complexity is O(phi^n) — phi is the golden ratio — or O(1.618^n), which is slightly lesser than our original estimate, but let's stick to O(2^n).
Another thing to notice is that the recurrence relation above is similar to that of the nth Fibonacci term, which would hence give a similar complexity.
Here’s where dynamic programming comes into the picture.
If you look closely, you’ll see the overlapping sub-problems we were talking about earlier.
Now comes the important part — converting this recursive implementation to a dynamic programming approach. What if we stored the values of the function calls that are being repeated?
Let’s maintain an array where the ith element is the value of f(i), which in turn, is the maximum sum of the array from index i to the end.
dp[i] = f(i..n) = f(i)
And since we already have a result for f(i),
dp[i] = max(arr[i] + f(i + 2), f(i + 1))
Now that we have this relation, we can go two different ways. Either we go the top-down route, where our function is still recursive, like our result above, or we remove all recursive calls and go the bottom-up route.
We’ll focus on the bottom-up route, but let's discuss the top-down approach.
Look at our previous result.
dp[i] = max(arr[i] + f(i + 2), f(i + 1))
That’s all we need to implement the top-down approach. For any call to f, we’ll first check in our array dp if we have already made that call earlier, and if we have, we use the pre-calculated value directly.
On the other hand, if the call we are making has never been done before, we have to compute the entire thing. In that case, once we arrive at a value, we make sure to store it in our array dp so that we won’t have to repeat the whole process.
The call tree should look something like this:
Let’s implement this algorithm.
The additional space required to store the results of our sub-problems grows linearly with the size of the input array. Hence, apart from the O(n) space required due to the recursive stack, we have an O(n) space for the dp array, n being the size of the input array.
The time complexity, though harder to compute, is linear to the input size. This is because we are storing the answers to the sub-problems we have already solved, and so, we have O(n) unique sub-problems that we have to solve. This result can also be verified with the complexity we get using the bottom-up approach.
Recall that in this approach, we seek to eliminate all recursive calls by following an iterative approach, where we start from the base case, or the “bottom” and make our way up.
Let’s replace the other calls to f with accessing elements of dp.
dp[i] = max(arr[i] + dp[i + 2], dp[i + 1])
What about the base case, f(n-1) = arr[n-1]? This would be the last element of the array dp.
dp[n-1] = arr[n-1]
And just like that, we have our solution for a bottom-up dp approach!
Let’s implement this, just like we did for the recursive approach.
This function would be called like so:
array := [1, 5, 2, 4, ...]output(f(array))
The complexity here would be linear in both space and time.
Why?
We are running a single for-loop n-1 times, and in each iteration, we are performing constant time operations — a linear time complexity.
Since the size of the array dp depends on the size of the input array — which, of course, is variable — our space complexity is also linear.
But can we do better? Let’s see.
In terms of asymptotic time complexity, we can’t do better. To find the answer, we have to check every element of the array. So we can’t do better than linear time.
But what about space complexity? Do we need to maintain an array of size n to solve the problem?
Look closely at the line inside the for-loop:
dp[i] = max(arr[i] + dp[i + 2], dp[i + 1])
At any point of time, all we need to populate dp[i] is the next two elements in dp — at indices i +1 and i + 2. There’s no reason to maintain all of our results. We just need to keep track of the last two iterations.
Let’s use three variables here. Let’s name them i_0, i_1 and i_2 for make it easier to relate between them.
dp[i] --> i_0dp[i+1] --> i_1dp[i+2] --> i_2
Notice that in the next iteration of our loop, our loop counter i, becomes i + 1, since we’re decrementing i in each iteration. dp[i +1] would be the next dp[i +2], dp[i] would be the next dp[i +1] and dp[i+2] — which we wouldn’t need since dp[i +3] isn’t required — can be reused as the next dp[i].
Replacing this with our three new variables, the code inside our loop becomes:
i_0 := max(arr[i] + i_2, i_1)i_2 := i_1i_1 := i_0
We initialize these variables just like our array implementation.
dp[n-1] = arr[n-1] --> i_1 = arr[n-1]dp[n] = 2 --> i_2 = 0
One last thing to keep in mind: what if the input array has only a single element? Our loop, which runs from n-2 to 0, wouldn’t run even once.
Hence, we initialize i_0 with the value of i_1. So if the loop never runs — the input array has only one element — returning i_0 would return the value of i_1, which is the arrays only element.
Finally, we return i_0 instead of dp[0].
return dp[0] --> return i_0
Thus, our final algorithm would look something like this.
Just like the previous dynamic programming approach, this function would be called by simply passing in an array or a reference to one.
array := [1, 5, 2, 4, ...]return f(array)
For an array of any length, all we need is three variables. Thus, the space complexity of our algorithm is now O(1) — constant.
Summarizing our results,
Comparing the recursive approach with our top-down approach, it's clear that we are trading space complexity for better time complexity. Of course, since both are recursive, they have the additional space required for the recursive call stack.
In a similar vein, the lowest two rows are the results of our bottom-up approaches. They are iterative, so they don’t require storing function records recursively on the stack. And since they’re essentially the same algorithm as the top-down approach, they have the same linear time complexity.
The best case is the bottom up approach requiring O(1) space — meaning that the space our dp algorithm is using doesn’t change with the input size n.
Let's implement our final algorithm of constant space bottom-up dynamic programming in C++. The variable and function names are the same as before.
Note: the final space complexity optimization step is slightly harder to look for, but drastically improves your space usage as we just saw. See if you can spot a similar relation for the bottom-up approach for the nth Fibonacci term.
Dynamic Programming is not often very intuitive or straightforward. Then again, most complex things aren’t. But things do get easier with practice. There are tonnes of dynamic programming practise problems online, which should help you get better at knowing when to apply dynamic programming, and how to apply it better. Hopefully, this post served as a good starting point. | [
{
"code": null,
"e": 411,
"s": 171,
"text": "Dynamic programming, or DP, is an optimization technique. It is used in several fields, though this article focuses on its applications in the field of algorithms and computer programming. Its a topic often asked in algorithmic interviews."
},
{
"code": null,
"e": 653,
"s": 411,
"text": "Since DP isn’t very intuitive, most people (myself included!) often find it tricky to model a problem as a dynamic programming model. In this post, we’ll discuss when we use DP, followed by its types and then finally work through an example."
},
{
"code": null,
"e": 935,
"s": 653,
"text": "When is DP used? - Overlapping Sub-problems - Optimal SubstructureThe Two kinds of DP - The top-down approach - The bottom-up approachAn example - The Problem - The analysis - A recursive Solution - The base case - A dynamic programming approach - Improving the Algorithm"
},
{
"code": null,
"e": 1009,
"s": 935,
"text": "There are two necessary conditions a problem must satisfy for DP to work."
},
{
"code": null,
"e": 1034,
"s": 1009,
"text": "Overlapping Sub-problems"
},
{
"code": null,
"e": 1055,
"s": 1034,
"text": "Optimal substructure"
},
{
"code": null,
"e": 1100,
"s": 1055,
"text": "Let's go over these in a little more detail."
},
{
"code": null,
"e": 1237,
"s": 1100,
"text": "This property is exactly what it sounds like: repeating sub-problems. But for this to make sense, we need to know what a sub-problem is."
},
{
"code": null,
"e": 1408,
"s": 1237,
"text": "A sub-problem is simply a smaller version of the problem at hand. In most cases, this would mean smaller parameter values which you would pass to your recursive function."
},
{
"code": null,
"e": 1598,
"s": 1408,
"text": "If you’re looking for a particular page in a book, what would you do? You’d open the book to a particular page and compare the page number you’re on with the page number you’re looking for."
},
{
"code": null,
"e": 1852,
"s": 1598,
"text": "If the current page is smaller than the required page, you’d start looking in between the current page and the last page. On the other hand, if the current page number is greater, you’d start searching between the start of the book and the current page."
},
{
"code": null,
"e": 1898,
"s": 1852,
"text": "You’d continue this until you found the page."
},
{
"code": null,
"e": 2002,
"s": 1898,
"text": "If you had to model this as a recursive function, what would that look like? Maybe something like this."
},
{
"code": null,
"e": 2096,
"s": 2002,
"text": "Note: The following snippets have been written in a form of pseudocode to improve readability"
},
{
"code": null,
"e": 2308,
"s": 2096,
"text": "Pretty straightforward. There’s a getpage function which returns the page (target_page, here) we’re looking for. The function looks at the middle page between from_page and to_page and checks if we have a match."
},
{
"code": null,
"e": 2411,
"s": 2308,
"text": "If not, the function looks at either the left half or the right half of the section we are looking at."
},
{
"code": null,
"e": 2688,
"s": 2411,
"text": "But what do those two recursive calls to getpage represent? You’ll notice that at each recursive call, we are reducing our search space by half. What we’re doing is solving the same problem, that is, looking for a specific page, in a smaller space. We’re solving sub-problems."
},
{
"code": null,
"e": 3140,
"s": 2688,
"text": "Divide and Conquer, or DAC algorithms work through the principle of sub-problems. The “divide” part refers to splitting a problem into sub-problems. Sorting algorithms like mergesort and quicksort are great examples. Note that binary search isn’t exactly a DAC algorithm for the simple reason that it doesn’t have a “combine” step, whereas an actual divide and conquer algorithm would combine the results of its sub-problems to get the final solution."
},
{
"code": null,
"e": 3250,
"s": 3140,
"text": "Now that we have answered the question of what a sub-problem is, we move on to the other word: “overlapping”."
},
{
"code": null,
"e": 3415,
"s": 3250,
"text": "When these sub-problems have to be solved more than once, they are said to be overlapping. Look at the call graph for computing the value of the nth Fibonacci term."
},
{
"code": null,
"e": 3443,
"s": 3415,
"text": "The recurrence relation is:"
},
{
"code": null,
"e": 3509,
"s": 3443,
"text": "the relationf(n) = f(n - 1) + f(n-2)the base casef(0) = 0f(1) = 1"
},
{
"code": null,
"e": 3664,
"s": 3509,
"text": "The calls have been shaded to represent overlapping subproblems. Compare this with something like binary search, where the subproblems aren’t overlapping."
},
{
"code": null,
"e": 3863,
"s": 3664,
"text": "The optimal substructure property is slightly more intricate: it refers to the scenario where optimal solutions to sub-problems can directly be considered when computed the overall optimal solution."
},
{
"code": null,
"e": 4018,
"s": 3863,
"text": "A quick example? Say you want to find the shortest path from A to B. Let X be an intermediate point between A and B with a single edge connecting it to A."
},
{
"code": null,
"e": 4200,
"s": 4018,
"text": "To solve this, we can find the shortest path from all intermediate nodes (X) to B, and then find the path from A to X plus the shortest path from X to B which is shortest for all X."
},
{
"code": null,
"e": 4272,
"s": 4200,
"text": "shortest(A, B) = min(AX + shortest(X, B)) for all intermediate nodes X."
},
{
"code": null,
"e": 4461,
"s": 4272,
"text": "What we’re doing here is using an optimal intermediate solution (shortest(X, B)) and use that (as opposed to considering every solution for a sub-problem) to find the final optimal answer."
},
{
"code": null,
"e": 4741,
"s": 4461,
"text": "In a top-down approach, we start from the highest level of our problem. In this approach, we initially check if have already solved the current sub-problem. If we have, we just return that value. If not, we solve that sub-problem. We use recursive calls to solve our sub-problem."
},
{
"code": null,
"e": 4936,
"s": 4741,
"text": "Since those calls require solving smaller sub-problems which we haven’t seen before, we continue this way, until we encounter a sub-problem we have either solved or know the answer to trivially."
},
{
"code": null,
"e": 5154,
"s": 4936,
"text": "In this approach, we start at the very bottom and then work our way to the top. Since we start from the “base case”, and use our recurrence relation, we don’t really need recursion, and so, this approach is iterative."
},
{
"code": null,
"e": 5514,
"s": 5154,
"text": "The main difference between the two approaches is that bottom-up calculates all solutions, while top-down computes only those that are required. For example, to find the shortest path between source and destination, using the top-down approach, we only compute the distances with intermediate points near the shortest path, choosing the minimum at each stage."
},
{
"code": null,
"e": 5721,
"s": 5514,
"text": "On the other hand, in a bottom-up approach, we end up calculating the shortest distance between each point on the grid and the destination, finally returning the shortest distance from the start to the end."
},
{
"code": null,
"e": 5832,
"s": 5721,
"text": "As a comparison, let's look at a possible top-down and bottom-up function that returns the nth Fibonacci term."
},
{
"code": null,
"e": 6055,
"s": 5832,
"text": "While both approaches have the same asymptotic time complexities, the recursive calls in a top-down implementation may lead to a stack overflow, which is a non-issue owing to the iterative nature of the bottom-up approach."
},
{
"code": null,
"e": 6237,
"s": 6055,
"text": "Remember that though we implement the latter iteratively, your logic would still use the recurrence relation from the very basic recursive approach, as we shall see in this example."
},
{
"code": null,
"e": 6325,
"s": 6237,
"text": "Let's go over a problem which we’ll solve using both approaches to dynamic programming."
},
{
"code": null,
"e": 6463,
"s": 6325,
"text": "Find the maximum sum of elements in an array ensuring that no adjacent elements are included. Let’s assume that no elements are negative."
},
{
"code": null,
"e": 6565,
"s": 6463,
"text": "example 1:[1, 2, 3] => 1 + 3 = 4example 2:[1, 1, 1, 1] => 1 + 1 = 2example 3:[2, 5, 2] => 5 = 5"
},
{
"code": null,
"e": 6601,
"s": 6565,
"text": "First, let's try a greedy approach."
},
{
"code": null,
"e": 6969,
"s": 6601,
"text": "Since our goal is to maximize the sum of the elements we choose, we could hope to accomplish this by choosing the biggest elements, ignoring its neighbours, and then continuing this way. Here, we’re ensuring that at each step of the way, we have a maximum sum. But this would be correct only in a local context, while we are, of course, looking for a global solution."
},
{
"code": null,
"e": 7012,
"s": 6969,
"text": "This approach could work in certain cases."
},
{
"code": null,
"e": 7035,
"s": 7012,
"text": "[1, 5, 1, 10, 1, 5, 1]"
},
{
"code": null,
"e": 7215,
"s": 7035,
"text": "Here, we first choose 10, since it’s the biggest element. We then ignore its neighbours, so that we don’t violate the condition that we aren’t allowed to choose adjacent elements."
},
{
"code": null,
"e": 7445,
"s": 7215,
"text": "Next, we choose both the 5’s, since they’re the next biggest elements, and then ignore their neighbours. Our algorithm ends here since there aren’t any elements left. The result we get — 10 + 5 + 5 — is in fact, the right answer."
},
{
"code": null,
"e": 7501,
"s": 7445,
"text": "But this won’t always work. Take the following example:"
},
{
"code": null,
"e": 7524,
"s": 7501,
"text": "[1, 1, 9, 10, 9, 1, 1]"
},
{
"code": null,
"e": 7783,
"s": 7524,
"text": "At every step, if you chose the maximum element, ignored its neighbours and continued that way, you’d end up choosing 10, then 1 and then 1 again after ignoring both the 9's, which would add up to 12, but the right answer would be 1 + 9 + 9 + 1, which is 20."
},
{
"code": null,
"e": 7926,
"s": 7783,
"text": "Its clear this approach isn’t the right one. Let’s start from a basic recursive solution and work up to one that uses dynamic programming one."
},
{
"code": null,
"e": 8308,
"s": 7926,
"text": "This is the difference between the greedy and dynamic programming approaches. While a greedy approach focuses on doing its best to reach the goal at every step, DP looks at the overall picture. With a greedy approach, there’s no guarantee you’ll even end up with an optimal solution, unlike DP. Greedy algorithms often get trapped in local maxima, leading to sub-optimal solutions."
},
{
"code": null,
"e": 8453,
"s": 8308,
"text": "After thinking for a bit, you can probably see that we have a condition to keep in mind: no adjacent elements. You can probably figure out that:"
},
{
"code": null,
"e": 8521,
"s": 8453,
"text": "we can choose to either consider an element in our sum or ignore it"
},
{
"code": null,
"e": 8584,
"s": 8521,
"text": "if we consider it, we will have to ignore its adjacent element"
},
{
"code": null,
"e": 8781,
"s": 8584,
"text": "For the sake of brevity, let f(a..b) represent a call to f our array from index a to index b (both inclusive). That function f would represent our recursive function which would solve the problem."
},
{
"code": null,
"e": 8849,
"s": 8781,
"text": "So f(0..4) would mean running the function from index 0 to index 4."
},
{
"code": null,
"e": 9029,
"s": 8849,
"text": "The two arrows pointing from a cell represent our choices of subsequent function calls. Since this is a maximization problem, we’d have to choose the maximum out of these options."
},
{
"code": null,
"e": 9059,
"s": 9029,
"text": "Let’s come back to our array."
},
{
"code": null,
"e": 9079,
"s": 9059,
"text": "[5, 10, 100, 10, 5]"
},
{
"code": null,
"e": 9176,
"s": 9079,
"text": "Keeping the conditions discussed above in mind let’s actually write down what we would be doing."
},
{
"code": null,
"e": 9264,
"s": 9176,
"text": "Our first call would be on the entire array, which is of length 5 as can be seen above."
},
{
"code": null,
"e": 9272,
"s": 9264,
"text": "f(0..4)"
},
{
"code": null,
"e": 9354,
"s": 9272,
"text": "For the element at index 0 (which happens to be 5 here), we can either choose to:"
},
{
"code": null,
"e": 9568,
"s": 9354,
"text": "include it in our sum: our current sum would then be 5 + the maximum sum of the rest of the array, but excluding the next element (index 1). Thus, our sum becomes 5 + f(2..4). Or to generalize it, arr[0] + f(2..4)"
},
{
"code": null,
"e": 9910,
"s": 9568,
"text": "exclude it: our current sum would then just be equal to the maximum sum of the remaining array. This can be written as: 0 + f(1..4). Notice that our next call is from index 1 and not 2 as in the previous case. Since we aren’t considering the element at index 0, we are free to consider the element at index 1 — we aren’t forced to ignore it."
},
{
"code": null,
"e": 10061,
"s": 9910,
"text": "The graph here visually explains this. As mentioned earlier, all arrows at a given level represent our choices, from which we choose the greatest one."
},
{
"code": null,
"e": 10091,
"s": 10061,
"text": "So our final answer would be:"
},
{
"code": null,
"e": 10132,
"s": 10091,
"text": "f(0..4) = max(arr[0] + f(2..4), f(1..4))"
},
{
"code": null,
"e": 10174,
"s": 10132,
"text": "Let’s expand this for the next iteration."
},
{
"code": null,
"e": 10408,
"s": 10174,
"text": "First, we’ll do it for the left tree, which is f(2..4). This is just like what we did for the first call to f. Remember that the arr[0] + part is still there. It will be added to the value of f(2..4) on our way back up the call tree."
},
{
"code": null,
"e": 10421,
"s": 10408,
"text": "Our choices:"
},
{
"code": null,
"e": 10611,
"s": 10421,
"text": "consider arr[2] in our sum: our sum at this stage becomes arr[2] + f(4..4). Remember that since we’re considering the element at index 2, we would have to ignore the next element — index 3."
},
{
"code": null,
"e": 10763,
"s": 10611,
"text": "ignore arr[2]: our sum here is the same as the maximum result of the remaining array without having to ignore the adjacent element. So, that's f(3..4)."
},
{
"code": null,
"e": 10843,
"s": 10763,
"text": "Just like before, the value of f(2..4) would be the maximum of our two choices."
},
{
"code": null,
"e": 10884,
"s": 10843,
"text": "f(2..4) = max(arr[2] + f(4..4), f(3..4))"
},
{
"code": null,
"e": 11151,
"s": 10884,
"text": "What do you think f(4..4) would evaluate to? Following our notation, it is the result of our function call on the array from index 4 to ... well, index 4. That means that we are calling the function on a single element. The maximum sum of a single element is itself."
},
{
"code": null,
"e": 11408,
"s": 11151,
"text": "Another thing to keep in mind: in f(a..b), a should never be greater than b. Since this call represents starting from index a and going up to index b, we would have to return 0 if a ever gets bigger than b. There is no maximum sum if there are no elements."
},
{
"code": null,
"e": 11641,
"s": 11408,
"text": "We have our base case here. Our function f, when called on a single element, would return that element directly and returns 0 if we are not in a valid range. There are no further recursive calls. That’s why its called the base case."
},
{
"code": null,
"e": 11772,
"s": 11641,
"text": "In our case, our call to f(3..4) leads to an invalid call to f(5..4), which we handle by returning 0. We’ll generalize this later."
},
{
"code": null,
"e": 11800,
"s": 11772,
"text": "f(4..4) = arr[4]f(5..4) = 0"
},
{
"code": null,
"e": 11840,
"s": 11800,
"text": "Let’s have another look at our results."
},
{
"code": null,
"e": 11985,
"s": 11840,
"text": "first call:f(0..4) = max(arr[0] + f(2..4), f(1..4))second call:f(2..4) = max(arr[2] + f(4..4), f(3..4))the base case:f(4..4) = arr[4]f(5..4) = 0"
},
{
"code": null,
"e": 12060,
"s": 11985,
"text": "Notice a pattern in the first two results? If we generalize these, we get:"
},
{
"code": null,
"e": 12107,
"s": 12060,
"text": "f(a..b) = max(arr[a] + f(a+2 .. b), f(a+1, b))"
},
{
"code": null,
"e": 12274,
"s": 12107,
"text": "This still isn’t the most simplified version of our relation. Notice the occurrences of b here. In fact, go back and look at our specific calls in the previous block."
},
{
"code": null,
"e": 12460,
"s": 12274,
"text": "They don’t change. There’s no b + 1 or b + 2. It’s always b. And what’s the value of b in our first call? The last index. Since b is constant throughout our algorithm, we can remove it."
},
{
"code": null,
"e": 12493,
"s": 12460,
"text": "Our recurrence relation becomes:"
},
{
"code": null,
"e": 12529,
"s": 12493,
"text": "f(a) = max(arr[a] + f(a+2), f(a+1))"
},
{
"code": null,
"e": 12585,
"s": 12529,
"text": "where f(a) is a call on the array from index a onwards."
},
{
"code": null,
"e": 12814,
"s": 12585,
"text": "Another thing to realize is that similar to how we removed b since it was always equal to the last index in the array, the base case, which refers to a single element, would only happen if that element was the last in the array."
},
{
"code": null,
"e": 12857,
"s": 12814,
"text": "A generalized version of our base case is:"
},
{
"code": null,
"e": 12959,
"s": 12857,
"text": "f(n-1) = arr[n-1] where n is the size of the arrayf(a) = 0 if a >= n where n is the size of the array"
},
{
"code": null,
"e": 12987,
"s": 12959,
"text": "Thus, we have our relation:"
},
{
"code": null,
"e": 13124,
"s": 12987,
"text": "f(a) = max(arr[a] + f(a+2), f(a+1))f(n-1) = arr[n-1] where n is the size of the arrayf(a) = 0 if a >= n where n is the size of the array"
},
{
"code": null,
"e": 13187,
"s": 13124,
"text": "Let’s implement the recursive approach based on this relation."
},
{
"code": null,
"e": 13226,
"s": 13187,
"text": "This function would be called like so:"
},
{
"code": null,
"e": 13271,
"s": 13226,
"text": "array := [1, 5, 2, 4, ...]return f(array, 0)"
},
{
"code": null,
"e": 13309,
"s": 13271,
"text": "What would be the complexity of this?"
},
{
"code": null,
"e": 13434,
"s": 13309,
"text": "If we were to approximate the complexity based on the size of the array (n) we are operating on, we get something like this:"
},
{
"code": null,
"e": 13475,
"s": 13434,
"text": "T(n) = T(n-2) + T(n-1) + O(1)T(0) = O(1)"
},
{
"code": null,
"e": 13670,
"s": 13475,
"text": "Intuitively, every call to f on an array of size n — represented as T(n) — leads to two calls on f on arrays of size n-2 and n-1. That is, at each stage, we’re doubling the number of calls to f."
},
{
"code": null,
"e": 13758,
"s": 13670,
"text": "The asymptotic time complexity is exponential. With the above reasoning, we get O(2^n)."
},
{
"code": null,
"e": 14075,
"s": 13758,
"text": "This is a loose estimate on the upper bound, since the n-2 tree is bound to end before the n-1 tree, and so we are doing slightly less than doubling the calls. The actual complexity is O(phi^n) — phi is the golden ratio — or O(1.618^n), which is slightly lesser than our original estimate, but let's stick to O(2^n)."
},
{
"code": null,
"e": 14228,
"s": 14075,
"text": "Another thing to notice is that the recurrence relation above is similar to that of the nth Fibonacci term, which would hence give a similar complexity."
},
{
"code": null,
"e": 14285,
"s": 14228,
"text": "Here’s where dynamic programming comes into the picture."
},
{
"code": null,
"e": 14377,
"s": 14285,
"text": "If you look closely, you’ll see the overlapping sub-problems we were talking about earlier."
},
{
"code": null,
"e": 14560,
"s": 14377,
"text": "Now comes the important part — converting this recursive implementation to a dynamic programming approach. What if we stored the values of the function calls that are being repeated?"
},
{
"code": null,
"e": 14700,
"s": 14560,
"text": "Let’s maintain an array where the ith element is the value of f(i), which in turn, is the maximum sum of the array from index i to the end."
},
{
"code": null,
"e": 14723,
"s": 14700,
"text": "dp[i] = f(i..n) = f(i)"
},
{
"code": null,
"e": 14768,
"s": 14723,
"text": "And since we already have a result for f(i),"
},
{
"code": null,
"e": 14809,
"s": 14768,
"text": "dp[i] = max(arr[i] + f(i + 2), f(i + 1))"
},
{
"code": null,
"e": 15027,
"s": 14809,
"text": "Now that we have this relation, we can go two different ways. Either we go the top-down route, where our function is still recursive, like our result above, or we remove all recursive calls and go the bottom-up route."
},
{
"code": null,
"e": 15104,
"s": 15027,
"text": "We’ll focus on the bottom-up route, but let's discuss the top-down approach."
},
{
"code": null,
"e": 15133,
"s": 15104,
"text": "Look at our previous result."
},
{
"code": null,
"e": 15174,
"s": 15133,
"text": "dp[i] = max(arr[i] + f(i + 2), f(i + 1))"
},
{
"code": null,
"e": 15383,
"s": 15174,
"text": "That’s all we need to implement the top-down approach. For any call to f, we’ll first check in our array dp if we have already made that call earlier, and if we have, we use the pre-calculated value directly."
},
{
"code": null,
"e": 15626,
"s": 15383,
"text": "On the other hand, if the call we are making has never been done before, we have to compute the entire thing. In that case, once we arrive at a value, we make sure to store it in our array dp so that we won’t have to repeat the whole process."
},
{
"code": null,
"e": 15673,
"s": 15626,
"text": "The call tree should look something like this:"
},
{
"code": null,
"e": 15705,
"s": 15673,
"text": "Let’s implement this algorithm."
},
{
"code": null,
"e": 15972,
"s": 15705,
"text": "The additional space required to store the results of our sub-problems grows linearly with the size of the input array. Hence, apart from the O(n) space required due to the recursive stack, we have an O(n) space for the dp array, n being the size of the input array."
},
{
"code": null,
"e": 16289,
"s": 15972,
"text": "The time complexity, though harder to compute, is linear to the input size. This is because we are storing the answers to the sub-problems we have already solved, and so, we have O(n) unique sub-problems that we have to solve. This result can also be verified with the complexity we get using the bottom-up approach."
},
{
"code": null,
"e": 16468,
"s": 16289,
"text": "Recall that in this approach, we seek to eliminate all recursive calls by following an iterative approach, where we start from the base case, or the “bottom” and make our way up."
},
{
"code": null,
"e": 16534,
"s": 16468,
"text": "Let’s replace the other calls to f with accessing elements of dp."
},
{
"code": null,
"e": 16577,
"s": 16534,
"text": "dp[i] = max(arr[i] + dp[i + 2], dp[i + 1])"
},
{
"code": null,
"e": 16670,
"s": 16577,
"text": "What about the base case, f(n-1) = arr[n-1]? This would be the last element of the array dp."
},
{
"code": null,
"e": 16689,
"s": 16670,
"text": "dp[n-1] = arr[n-1]"
},
{
"code": null,
"e": 16759,
"s": 16689,
"text": "And just like that, we have our solution for a bottom-up dp approach!"
},
{
"code": null,
"e": 16826,
"s": 16759,
"text": "Let’s implement this, just like we did for the recursive approach."
},
{
"code": null,
"e": 16865,
"s": 16826,
"text": "This function would be called like so:"
},
{
"code": null,
"e": 16908,
"s": 16865,
"text": "array := [1, 5, 2, 4, ...]output(f(array))"
},
{
"code": null,
"e": 16968,
"s": 16908,
"text": "The complexity here would be linear in both space and time."
},
{
"code": null,
"e": 16973,
"s": 16968,
"text": "Why?"
},
{
"code": null,
"e": 17111,
"s": 16973,
"text": "We are running a single for-loop n-1 times, and in each iteration, we are performing constant time operations — a linear time complexity."
},
{
"code": null,
"e": 17252,
"s": 17111,
"text": "Since the size of the array dp depends on the size of the input array — which, of course, is variable — our space complexity is also linear."
},
{
"code": null,
"e": 17285,
"s": 17252,
"text": "But can we do better? Let’s see."
},
{
"code": null,
"e": 17450,
"s": 17285,
"text": "In terms of asymptotic time complexity, we can’t do better. To find the answer, we have to check every element of the array. So we can’t do better than linear time."
},
{
"code": null,
"e": 17547,
"s": 17450,
"text": "But what about space complexity? Do we need to maintain an array of size n to solve the problem?"
},
{
"code": null,
"e": 17593,
"s": 17547,
"text": "Look closely at the line inside the for-loop:"
},
{
"code": null,
"e": 17636,
"s": 17593,
"text": "dp[i] = max(arr[i] + dp[i + 2], dp[i + 1])"
},
{
"code": null,
"e": 17853,
"s": 17636,
"text": "At any point of time, all we need to populate dp[i] is the next two elements in dp — at indices i +1 and i + 2. There’s no reason to maintain all of our results. We just need to keep track of the last two iterations."
},
{
"code": null,
"e": 17961,
"s": 17853,
"text": "Let’s use three variables here. Let’s name them i_0, i_1 and i_2 for make it easier to relate between them."
},
{
"code": null,
"e": 18007,
"s": 17961,
"text": "dp[i] --> i_0dp[i+1] --> i_1dp[i+2] --> i_2"
},
{
"code": null,
"e": 18307,
"s": 18007,
"text": "Notice that in the next iteration of our loop, our loop counter i, becomes i + 1, since we’re decrementing i in each iteration. dp[i +1] would be the next dp[i +2], dp[i] would be the next dp[i +1] and dp[i+2] — which we wouldn’t need since dp[i +3] isn’t required — can be reused as the next dp[i]."
},
{
"code": null,
"e": 18386,
"s": 18307,
"text": "Replacing this with our three new variables, the code inside our loop becomes:"
},
{
"code": null,
"e": 18436,
"s": 18386,
"text": "i_0 := max(arr[i] + i_2, i_1)i_2 := i_1i_1 := i_0"
},
{
"code": null,
"e": 18502,
"s": 18436,
"text": "We initialize these variables just like our array implementation."
},
{
"code": null,
"e": 18570,
"s": 18502,
"text": "dp[n-1] = arr[n-1] --> i_1 = arr[n-1]dp[n] = 2 --> i_2 = 0"
},
{
"code": null,
"e": 18713,
"s": 18570,
"text": "One last thing to keep in mind: what if the input array has only a single element? Our loop, which runs from n-2 to 0, wouldn’t run even once."
},
{
"code": null,
"e": 18907,
"s": 18713,
"text": "Hence, we initialize i_0 with the value of i_1. So if the loop never runs — the input array has only one element — returning i_0 would return the value of i_1, which is the arrays only element."
},
{
"code": null,
"e": 18948,
"s": 18907,
"text": "Finally, we return i_0 instead of dp[0]."
},
{
"code": null,
"e": 18976,
"s": 18948,
"text": "return dp[0] --> return i_0"
},
{
"code": null,
"e": 19034,
"s": 18976,
"text": "Thus, our final algorithm would look something like this."
},
{
"code": null,
"e": 19170,
"s": 19034,
"text": "Just like the previous dynamic programming approach, this function would be called by simply passing in an array or a reference to one."
},
{
"code": null,
"e": 19212,
"s": 19170,
"text": "array := [1, 5, 2, 4, ...]return f(array)"
},
{
"code": null,
"e": 19340,
"s": 19212,
"text": "For an array of any length, all we need is three variables. Thus, the space complexity of our algorithm is now O(1) — constant."
},
{
"code": null,
"e": 19365,
"s": 19340,
"text": "Summarizing our results,"
},
{
"code": null,
"e": 19609,
"s": 19365,
"text": "Comparing the recursive approach with our top-down approach, it's clear that we are trading space complexity for better time complexity. Of course, since both are recursive, they have the additional space required for the recursive call stack."
},
{
"code": null,
"e": 19904,
"s": 19609,
"text": "In a similar vein, the lowest two rows are the results of our bottom-up approaches. They are iterative, so they don’t require storing function records recursively on the stack. And since they’re essentially the same algorithm as the top-down approach, they have the same linear time complexity."
},
{
"code": null,
"e": 20054,
"s": 19904,
"text": "The best case is the bottom up approach requiring O(1) space — meaning that the space our dp algorithm is using doesn’t change with the input size n."
},
{
"code": null,
"e": 20202,
"s": 20054,
"text": "Let's implement our final algorithm of constant space bottom-up dynamic programming in C++. The variable and function names are the same as before."
},
{
"code": null,
"e": 20437,
"s": 20202,
"text": "Note: the final space complexity optimization step is slightly harder to look for, but drastically improves your space usage as we just saw. See if you can spot a similar relation for the bottom-up approach for the nth Fibonacci term."
}
] |
Data Augmentation library for text | by Edward Ma | Towards Data Science | In the previous story, you understand different approaches to generate more training data for your NLP task model. In this story, we will learn how can you do it with just a few line codes.
In natural language processing (NLP) field, it is hard to augmenting text due to high complexity of language. Not every word we can replace it by others such as a, an, the. Also, not every word has synonym. Even changing a word, the context will be totally difference. On the other hand, generating augmented image in computer vision area is relative easier. Even introducing noise or cropping out portion of image, model can still classify the image.
After used imgaug in computer vision project, I am thinking whether we can have a similar library to generate synthetic data. Therefore, I re-implement those research papers by using the existing library and pre-trained model. Basic elements of nlpaug includes:
Character: OCR Augmenter, QWERTY Augmenter and Random Character Augmenter
Word: WordNet Augmenter, word2vec Augmenter, GloVe Augmenter, fasttext Augmenter, BERT Augmenter, Random Word Character
Flow: Sequential Augmenter, Sometimes Augmenter
Intuitively, Character Augmenters and Word Augmenters are focusing on character level and word level manipulation respectively. Flow works as an orchestra the control augmentation flow. You can access github for the library.
Augmenting data in character level. Possible scenarios include image to text and chatbot. During recognizing text from image, we need to optical character recognition (OCR) model to achieve it but OCR introduces some errors such as recognizing “o” and “0”. In chatbot, we still have typo even though most of the application comes with word correction. To overcome this problem, you may let your model “see” those possible outcomes before online prediction.
When working on NLP problem, OCR results may be one of the inputs of your NLP problem. For example, “0” may be recognized as “o” or “O”. If you are using bag-of-words or classic word embeddings as a feature, you will get trouble as out-of-vocabulary (OOV) around you today and always. If you use state-of-the-art models such as BERT and GPT, the OOV issue seems resolved as word will be split to subword. However, some information is lost.
OCRAug is designed to simulate OCR error. It will replace the target character by pre-defined mapping table.
Example of augmentation
Original:The quick brown fox jumps over the lazy dogAugmented Text:The quick brown fox jumps over the lazy d0g
Another project you may involve is chatbot or other messaging channels such as email. Although spell checking will be performed, some misspelled still exist. It may hurt your NLP model as mentioned before.
QWERTYAug is designed to simulate keyword distance error. It will replace the target character by 1 keyword distance. You can config whether include number or special character or not.
Example of augmentation
Original:The quick brown fox jumps over the lazy dogAugmented Text:Tne 2uick hrown Gox jumpQ ovdr tNe <azy d8g
From different research, noise injection may help to generalized your NLP model sometimes. We may add some noise to your word such as adding or deleting one character from your word.
RandomCharAug is designed to inject noise into your data. Unlike OCRAug and QWERTYAug, it supports insertion, substitution, and insertion.
Example of insert augmentation
Original:The quick brown fox jumps over the lazy dogAugmented Text:T(he quicdk browTn Ffox jumpvs 7over kthe clazy 9dog
Besides character augmentation, word level is important as well. We make use of word2vec (Mikolov et al., 2013), GloVe (Pennington et al., 2014), fasttext (Joulin et al., 2016), BERT(Devlin et al., 2018) and wordnet to insert and substitute similar word. Word2vecAug, GloVeAug and FasttextAug use word embeddings to find the most similar group of words to replace the original word. On the other hand, BertAug use language models to predict possible target words. WordNetAug use statistics way to find a similar group of words.
Classic embeddings use a static vector to present a word. Ideally, the meaning of the word is similar if vectors are near each other. Actually, it depends on the training data. For example, “rabbit” is similar to “fox” in word2vec while “nbc” is similar to “fox” in GloVe.
Sometimes, you want to replace words by similar words such that NLP model does not rely on a single word.Word2vecAug, GloVeAug andFasttextAug are designed to provide a “similar” word based on pre-trained vectors.
Besides substitution, insertion helps to inject noise into your data. It picks words from vocabulary randomly.
Example of insert augmentation
Original:The quick brown fox jumps over the lazy dogAugmented Text:The quick Bergen-Belsen brown fox jumps over Tiko the lazy dog
Example of substitute augmentation
Original:The quick brown fox jumps over the lazy dogAugmented Text:The quick gray fox jumps over to lazy dog
Since classic word embeddings use a static vector to represent the same word. It may not fit some scenarios. For “Fox” can represent as animal and broadcasting company. To overcome this problem, contextualized word embeddings is introduced to consider surrounding words to generate a vector under a different context.
BertAug is designed to provide this feature to perform insertion and substitution. Different from previous word embeddings, insertion is predicted by BERT language model rather than pick one word randomly. Substitution use surrounding words as a feature to predict the target word.
Example of insert augmentation
Original:The quick brown fox jumps over the lazy dogAugmented Text:the lazy quick brown fox always jumps over the lazy dog
Example of substitute augmentation
Original:The quick brown fox jumps over the lazy dogAugmented Text:the quick thinking fox jumps over the lazy dog
Besides the neural network approach, a thesaurus can achieve similar objectives. The limitation of synonym is that some words may not have similar words. WordNet from an awesome NLTK library helps to find the synonym words.
WordNetAug provides a substitution feature to replace the target word. Instead of finding synonyms purely, some preliminary checking makes sure that the target word can be replaced. Those rules are:
Do not pick determiner (e.g. a, an, the)
Do not pick a word that does not has a synonym.
Example of augmentation
Original:The quick brown fox jumps over the lazy dogAugmented Text:The quick brown fox parachute over the lazy blackguard
So far we do not introduce deletion in word level. RandomWordAug can help to remove a word randomly.
Example of augmentation
Original:The quick brown fox jumps over the lazy dogAugmented Text:The fox jumps over the lazy dog
Up to here, the above augmenters can be invoked alone. What if you want to combine multiple augmenters together? To make use of multiple augmentations, sequential and sometimes pipelines are introduced to connect augmenters. A single text can go though different augmenters to generate diversity of data.
You can add as much as augmenter you want to this flow and Sequential executes them one by one. For example, you can combine RandomCharAug and RandomWordAug together.
If you do not want to execute the same set of augmenters all the time, sometimes will pick some of the augmenters every time.
The above approach is designed to solve problems that authors are facing in their problems. If you understand your data, you should tailor made augmentation approach it. Remember that the golden rule in data science is garbage in garbage out.
In general, you can try the thesaurus approach without quite understanding your data. It may not boost up a lot due to the aforementioned thesaurus approach limitation.
I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. Feel free to connect with me on LinkedIn or following me on Medium or Github.
Image augmentation library (imgaug)
Text augmentation library (nlpaug)
Data Augmentation in NLP
Data Augmentation for Audio
Data Augmentation for Spectrogram
Does your NLP model able to prevent an adversarial attacks?
Data Augmentation in NLP: Best Practices From a Kaggle Master
X. Zhang, J. Zhao and Y. LeCun. Character-level Convolutional Networks for Text Classification. 2015
W. Y. Wang and D. Yang. That’s So Annoying!!!: A Lexical and Frame-Semantic Embedding Based Data Augmentation Approach to Automatic Categorization of Annoying Behaviors using #petpeeve Tweets. 2015
S. Kobayashi. Contextual Augmentation: Data Augmentation by Words with Paradigmatic Relation. 2018
C. Coulombe. Text Data Augmentation Made Simple By Leveraging NLP Cloud APIs. 2018 | [
{
"code": null,
"e": 237,
"s": 47,
"text": "In the previous story, you understand different approaches to generate more training data for your NLP task model. In this story, we will learn how can you do it with just a few line codes."
},
{
"code": null,
"e": 689,
"s": 237,
"text": "In natural language processing (NLP) field, it is hard to augmenting text due to high complexity of language. Not every word we can replace it by others such as a, an, the. Also, not every word has synonym. Even changing a word, the context will be totally difference. On the other hand, generating augmented image in computer vision area is relative easier. Even introducing noise or cropping out portion of image, model can still classify the image."
},
{
"code": null,
"e": 951,
"s": 689,
"text": "After used imgaug in computer vision project, I am thinking whether we can have a similar library to generate synthetic data. Therefore, I re-implement those research papers by using the existing library and pre-trained model. Basic elements of nlpaug includes:"
},
{
"code": null,
"e": 1025,
"s": 951,
"text": "Character: OCR Augmenter, QWERTY Augmenter and Random Character Augmenter"
},
{
"code": null,
"e": 1145,
"s": 1025,
"text": "Word: WordNet Augmenter, word2vec Augmenter, GloVe Augmenter, fasttext Augmenter, BERT Augmenter, Random Word Character"
},
{
"code": null,
"e": 1193,
"s": 1145,
"text": "Flow: Sequential Augmenter, Sometimes Augmenter"
},
{
"code": null,
"e": 1418,
"s": 1193,
"text": "Intuitively, Character Augmenters and Word Augmenters are focusing on character level and word level manipulation respectively. Flow works as an orchestra the control augmentation flow. You can access github for the library."
},
{
"code": null,
"e": 1875,
"s": 1418,
"text": "Augmenting data in character level. Possible scenarios include image to text and chatbot. During recognizing text from image, we need to optical character recognition (OCR) model to achieve it but OCR introduces some errors such as recognizing “o” and “0”. In chatbot, we still have typo even though most of the application comes with word correction. To overcome this problem, you may let your model “see” those possible outcomes before online prediction."
},
{
"code": null,
"e": 2315,
"s": 1875,
"text": "When working on NLP problem, OCR results may be one of the inputs of your NLP problem. For example, “0” may be recognized as “o” or “O”. If you are using bag-of-words or classic word embeddings as a feature, you will get trouble as out-of-vocabulary (OOV) around you today and always. If you use state-of-the-art models such as BERT and GPT, the OOV issue seems resolved as word will be split to subword. However, some information is lost."
},
{
"code": null,
"e": 2424,
"s": 2315,
"text": "OCRAug is designed to simulate OCR error. It will replace the target character by pre-defined mapping table."
},
{
"code": null,
"e": 2448,
"s": 2424,
"text": "Example of augmentation"
},
{
"code": null,
"e": 2559,
"s": 2448,
"text": "Original:The quick brown fox jumps over the lazy dogAugmented Text:The quick brown fox jumps over the lazy d0g"
},
{
"code": null,
"e": 2765,
"s": 2559,
"text": "Another project you may involve is chatbot or other messaging channels such as email. Although spell checking will be performed, some misspelled still exist. It may hurt your NLP model as mentioned before."
},
{
"code": null,
"e": 2950,
"s": 2765,
"text": "QWERTYAug is designed to simulate keyword distance error. It will replace the target character by 1 keyword distance. You can config whether include number or special character or not."
},
{
"code": null,
"e": 2974,
"s": 2950,
"text": "Example of augmentation"
},
{
"code": null,
"e": 3085,
"s": 2974,
"text": "Original:The quick brown fox jumps over the lazy dogAugmented Text:Tne 2uick hrown Gox jumpQ ovdr tNe <azy d8g"
},
{
"code": null,
"e": 3268,
"s": 3085,
"text": "From different research, noise injection may help to generalized your NLP model sometimes. We may add some noise to your word such as adding or deleting one character from your word."
},
{
"code": null,
"e": 3407,
"s": 3268,
"text": "RandomCharAug is designed to inject noise into your data. Unlike OCRAug and QWERTYAug, it supports insertion, substitution, and insertion."
},
{
"code": null,
"e": 3438,
"s": 3407,
"text": "Example of insert augmentation"
},
{
"code": null,
"e": 3558,
"s": 3438,
"text": "Original:The quick brown fox jumps over the lazy dogAugmented Text:T(he quicdk browTn Ffox jumpvs 7over kthe clazy 9dog"
},
{
"code": null,
"e": 4086,
"s": 3558,
"text": "Besides character augmentation, word level is important as well. We make use of word2vec (Mikolov et al., 2013), GloVe (Pennington et al., 2014), fasttext (Joulin et al., 2016), BERT(Devlin et al., 2018) and wordnet to insert and substitute similar word. Word2vecAug, GloVeAug and FasttextAug use word embeddings to find the most similar group of words to replace the original word. On the other hand, BertAug use language models to predict possible target words. WordNetAug use statistics way to find a similar group of words."
},
{
"code": null,
"e": 4359,
"s": 4086,
"text": "Classic embeddings use a static vector to present a word. Ideally, the meaning of the word is similar if vectors are near each other. Actually, it depends on the training data. For example, “rabbit” is similar to “fox” in word2vec while “nbc” is similar to “fox” in GloVe."
},
{
"code": null,
"e": 4572,
"s": 4359,
"text": "Sometimes, you want to replace words by similar words such that NLP model does not rely on a single word.Word2vecAug, GloVeAug andFasttextAug are designed to provide a “similar” word based on pre-trained vectors."
},
{
"code": null,
"e": 4683,
"s": 4572,
"text": "Besides substitution, insertion helps to inject noise into your data. It picks words from vocabulary randomly."
},
{
"code": null,
"e": 4714,
"s": 4683,
"text": "Example of insert augmentation"
},
{
"code": null,
"e": 4844,
"s": 4714,
"text": "Original:The quick brown fox jumps over the lazy dogAugmented Text:The quick Bergen-Belsen brown fox jumps over Tiko the lazy dog"
},
{
"code": null,
"e": 4879,
"s": 4844,
"text": "Example of substitute augmentation"
},
{
"code": null,
"e": 4988,
"s": 4879,
"text": "Original:The quick brown fox jumps over the lazy dogAugmented Text:The quick gray fox jumps over to lazy dog"
},
{
"code": null,
"e": 5306,
"s": 4988,
"text": "Since classic word embeddings use a static vector to represent the same word. It may not fit some scenarios. For “Fox” can represent as animal and broadcasting company. To overcome this problem, contextualized word embeddings is introduced to consider surrounding words to generate a vector under a different context."
},
{
"code": null,
"e": 5588,
"s": 5306,
"text": "BertAug is designed to provide this feature to perform insertion and substitution. Different from previous word embeddings, insertion is predicted by BERT language model rather than pick one word randomly. Substitution use surrounding words as a feature to predict the target word."
},
{
"code": null,
"e": 5619,
"s": 5588,
"text": "Example of insert augmentation"
},
{
"code": null,
"e": 5742,
"s": 5619,
"text": "Original:The quick brown fox jumps over the lazy dogAugmented Text:the lazy quick brown fox always jumps over the lazy dog"
},
{
"code": null,
"e": 5777,
"s": 5742,
"text": "Example of substitute augmentation"
},
{
"code": null,
"e": 5891,
"s": 5777,
"text": "Original:The quick brown fox jumps over the lazy dogAugmented Text:the quick thinking fox jumps over the lazy dog"
},
{
"code": null,
"e": 6115,
"s": 5891,
"text": "Besides the neural network approach, a thesaurus can achieve similar objectives. The limitation of synonym is that some words may not have similar words. WordNet from an awesome NLTK library helps to find the synonym words."
},
{
"code": null,
"e": 6314,
"s": 6115,
"text": "WordNetAug provides a substitution feature to replace the target word. Instead of finding synonyms purely, some preliminary checking makes sure that the target word can be replaced. Those rules are:"
},
{
"code": null,
"e": 6355,
"s": 6314,
"text": "Do not pick determiner (e.g. a, an, the)"
},
{
"code": null,
"e": 6403,
"s": 6355,
"text": "Do not pick a word that does not has a synonym."
},
{
"code": null,
"e": 6427,
"s": 6403,
"text": "Example of augmentation"
},
{
"code": null,
"e": 6549,
"s": 6427,
"text": "Original:The quick brown fox jumps over the lazy dogAugmented Text:The quick brown fox parachute over the lazy blackguard"
},
{
"code": null,
"e": 6650,
"s": 6549,
"text": "So far we do not introduce deletion in word level. RandomWordAug can help to remove a word randomly."
},
{
"code": null,
"e": 6674,
"s": 6650,
"text": "Example of augmentation"
},
{
"code": null,
"e": 6773,
"s": 6674,
"text": "Original:The quick brown fox jumps over the lazy dogAugmented Text:The fox jumps over the lazy dog"
},
{
"code": null,
"e": 7078,
"s": 6773,
"text": "Up to here, the above augmenters can be invoked alone. What if you want to combine multiple augmenters together? To make use of multiple augmentations, sequential and sometimes pipelines are introduced to connect augmenters. A single text can go though different augmenters to generate diversity of data."
},
{
"code": null,
"e": 7245,
"s": 7078,
"text": "You can add as much as augmenter you want to this flow and Sequential executes them one by one. For example, you can combine RandomCharAug and RandomWordAug together."
},
{
"code": null,
"e": 7371,
"s": 7245,
"text": "If you do not want to execute the same set of augmenters all the time, sometimes will pick some of the augmenters every time."
},
{
"code": null,
"e": 7614,
"s": 7371,
"text": "The above approach is designed to solve problems that authors are facing in their problems. If you understand your data, you should tailor made augmentation approach it. Remember that the golden rule in data science is garbage in garbage out."
},
{
"code": null,
"e": 7783,
"s": 7614,
"text": "In general, you can try the thesaurus approach without quite understanding your data. It may not boost up a lot due to the aforementioned thesaurus approach limitation."
},
{
"code": null,
"e": 8006,
"s": 7783,
"text": "I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. Feel free to connect with me on LinkedIn or following me on Medium or Github."
},
{
"code": null,
"e": 8042,
"s": 8006,
"text": "Image augmentation library (imgaug)"
},
{
"code": null,
"e": 8077,
"s": 8042,
"text": "Text augmentation library (nlpaug)"
},
{
"code": null,
"e": 8102,
"s": 8077,
"text": "Data Augmentation in NLP"
},
{
"code": null,
"e": 8130,
"s": 8102,
"text": "Data Augmentation for Audio"
},
{
"code": null,
"e": 8164,
"s": 8130,
"text": "Data Augmentation for Spectrogram"
},
{
"code": null,
"e": 8224,
"s": 8164,
"text": "Does your NLP model able to prevent an adversarial attacks?"
},
{
"code": null,
"e": 8286,
"s": 8224,
"text": "Data Augmentation in NLP: Best Practices From a Kaggle Master"
},
{
"code": null,
"e": 8387,
"s": 8286,
"text": "X. Zhang, J. Zhao and Y. LeCun. Character-level Convolutional Networks for Text Classification. 2015"
},
{
"code": null,
"e": 8585,
"s": 8387,
"text": "W. Y. Wang and D. Yang. That’s So Annoying!!!: A Lexical and Frame-Semantic Embedding Based Data Augmentation Approach to Automatic Categorization of Annoying Behaviors using #petpeeve Tweets. 2015"
},
{
"code": null,
"e": 8684,
"s": 8585,
"text": "S. Kobayashi. Contextual Augmentation: Data Augmentation by Words with Paradigmatic Relation. 2018"
}
] |
How to Adjust Number of Ticks in Seaborn Plots? - GeeksforGeeks | 19 Dec, 2021
In this article, we will discuss how to adjust the number of ticks in Seaborn Plots. Ticks are the values that are used to show some specific points on the X-Y coordinate, It can be a string or a number. We will see how we can choose an optimal or expand the number of ticks to display on both the x-axis and y-axis.
The Axes.set_xticks() and Axes.set_yticks() functions in axes module of matplotlib library are used to Set the ticks with a list of ticks on X-axis and Y-axis respectively.
Syntax:
For xticks:
Axes.set_xticks(self, ticks, minor=False)
For yticks:
Axes.set_yticks(self, ticks, minor=False)
Parameters:
ticks: This parameter is the list of x-axis/y-axis tick locations.
minor: This parameter is used whether set major ticks or to set minor ticks
Return value:
This method does not returns any value.
In this example, we are setting a number of xticks to the length of data present in dataframe.
Python3
import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt sns.set(style="darkgrid") # create DataFramedf = pd.DataFrame({'a': np.random.rand(8), 'b': np.random.rand(8)}) # create lineplotg = sns.lineplot(data=df) # set the ticks firstg.set_xticks(range(8)) # set the labelsg.set_xticklabels(['2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018'])
Output:
In this example, we are setting a number of yticks to the length of data present in dataframe.
Python3
import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt sns.set(style="darkgrid") # create DataFramedf = pd.DataFrame({'a': np.random.rand(8), 'b': np.random.rand(8)}) # create lineplotg = sns.lineplot(data=df) # set the ticks firstg.set_yticks(range(len(df)-5)) # set the labelsg.set_xticklabels(['2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018'])
Output:
In this example, we are setting the number of specific positions of ticks on x-axis and y-axis
Python3
import pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # create DataFramedf = pd.DataFrame({'var1': [25, 12, 15, 14, 19, 23, 25, 29], 'var2': [5, 7, 7, 9, 12, 9, 9, 4]}) # create scatterplotsns.scatterplot(data=df, x='var1', y='var2') # specify positions of ticks on x-axis and y-axisplt.xticks([15, 20, 25], ['A', 'B', 'C'])plt.yticks([4, 8, 12], ['Low', 'Medium', 'High'])
Output:
Picked
Python-Seaborn
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()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 24218,
"s": 23901,
"text": "In this article, we will discuss how to adjust the number of ticks in Seaborn Plots. Ticks are the values that are used to show some specific points on the X-Y coordinate, It can be a string or a number. We will see how we can choose an optimal or expand the number of ticks to display on both the x-axis and y-axis."
},
{
"code": null,
"e": 24391,
"s": 24218,
"text": "The Axes.set_xticks() and Axes.set_yticks() functions in axes module of matplotlib library are used to Set the ticks with a list of ticks on X-axis and Y-axis respectively."
},
{
"code": null,
"e": 24399,
"s": 24391,
"text": "Syntax:"
},
{
"code": null,
"e": 24412,
"s": 24399,
"text": "For xticks:"
},
{
"code": null,
"e": 24455,
"s": 24412,
"text": " Axes.set_xticks(self, ticks, minor=False)"
},
{
"code": null,
"e": 24468,
"s": 24455,
"text": "For yticks:"
},
{
"code": null,
"e": 24510,
"s": 24468,
"text": "Axes.set_yticks(self, ticks, minor=False)"
},
{
"code": null,
"e": 24522,
"s": 24510,
"text": "Parameters:"
},
{
"code": null,
"e": 24589,
"s": 24522,
"text": "ticks: This parameter is the list of x-axis/y-axis tick locations."
},
{
"code": null,
"e": 24665,
"s": 24589,
"text": "minor: This parameter is used whether set major ticks or to set minor ticks"
},
{
"code": null,
"e": 24680,
"s": 24665,
"text": "Return value: "
},
{
"code": null,
"e": 24720,
"s": 24680,
"text": "This method does not returns any value."
},
{
"code": null,
"e": 24815,
"s": 24720,
"text": "In this example, we are setting a number of xticks to the length of data present in dataframe."
},
{
"code": null,
"e": 24823,
"s": 24815,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt sns.set(style=\"darkgrid\") # create DataFramedf = pd.DataFrame({'a': np.random.rand(8), 'b': np.random.rand(8)}) # create lineplotg = sns.lineplot(data=df) # set the ticks firstg.set_xticks(range(8)) # set the labelsg.set_xticklabels(['2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018'])",
"e": 25235,
"s": 24823,
"text": null
},
{
"code": null,
"e": 25243,
"s": 25235,
"text": "Output:"
},
{
"code": null,
"e": 25338,
"s": 25243,
"text": "In this example, we are setting a number of yticks to the length of data present in dataframe."
},
{
"code": null,
"e": 25346,
"s": 25338,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt sns.set(style=\"darkgrid\") # create DataFramedf = pd.DataFrame({'a': np.random.rand(8), 'b': np.random.rand(8)}) # create lineplotg = sns.lineplot(data=df) # set the ticks firstg.set_yticks(range(len(df)-5)) # set the labelsg.set_xticklabels(['2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018'])",
"e": 25767,
"s": 25346,
"text": null
},
{
"code": null,
"e": 25775,
"s": 25767,
"text": "Output:"
},
{
"code": null,
"e": 25870,
"s": 25775,
"text": "In this example, we are setting the number of specific positions of ticks on x-axis and y-axis"
},
{
"code": null,
"e": 25878,
"s": 25870,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # create DataFramedf = pd.DataFrame({'var1': [25, 12, 15, 14, 19, 23, 25, 29], 'var2': [5, 7, 7, 9, 12, 9, 9, 4]}) # create scatterplotsns.scatterplot(data=df, x='var1', y='var2') # specify positions of ticks on x-axis and y-axisplt.xticks([15, 20, 25], ['A', 'B', 'C'])plt.yticks([4, 8, 12], ['Low', 'Medium', 'High'])",
"e": 26291,
"s": 25878,
"text": null
},
{
"code": null,
"e": 26299,
"s": 26291,
"text": "Output:"
},
{
"code": null,
"e": 26306,
"s": 26299,
"text": "Picked"
},
{
"code": null,
"e": 26321,
"s": 26306,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 26328,
"s": 26321,
"text": "Python"
},
{
"code": null,
"e": 26426,
"s": 26328,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26435,
"s": 26426,
"text": "Comments"
},
{
"code": null,
"e": 26448,
"s": 26435,
"text": "Old Comments"
},
{
"code": null,
"e": 26480,
"s": 26448,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26536,
"s": 26480,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26578,
"s": 26536,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26620,
"s": 26578,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26656,
"s": 26620,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26678,
"s": 26656,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26717,
"s": 26678,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26744,
"s": 26717,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26775,
"s": 26744,
"text": "Python | os.path.join() method"
}
] |
PHP – Get the string length using mb_strlen() | In PHP, multibyte string length (mb_strlen) function is used to get the total string length of a specified string. This function is supported in PHP 4.6.0 or higher versions.
int mb_strlen(str $string, str $encoding)
mb_strlen() accepts two parameters: $string and $encoding.
$string− It is used to check the string length
$string− It is used to check the string length
$encoding− This parameter is used for character encoding. If it is omitted or null, then the internal character encoding value will be used.
$encoding− This parameter is used for character encoding. If it is omitted or null, then the internal character encoding value will be used.
mb_strlen() returns the number of characters present in the given string. One is counted as a multi-byte character.
If the encoding is not known, then it will generate the level E_warning.
Live Demo
<?php
// It will return total number of character
$result = mb_strlen("Hello World","UTF-8");
echo "Total number of characters: ", $result;
?>
Total number of characters: 11
Note: that it counts the space too in the given string. | [
{
"code": null,
"e": 1237,
"s": 1062,
"text": "In PHP, multibyte string length (mb_strlen) function is used to get the total string length of a specified string. This function is supported in PHP 4.6.0 or higher versions."
},
{
"code": null,
"e": 1279,
"s": 1237,
"text": "int mb_strlen(str $string, str $encoding)"
},
{
"code": null,
"e": 1338,
"s": 1279,
"text": "mb_strlen() accepts two parameters: $string and $encoding."
},
{
"code": null,
"e": 1385,
"s": 1338,
"text": "$string− It is used to check the string length"
},
{
"code": null,
"e": 1432,
"s": 1385,
"text": "$string− It is used to check the string length"
},
{
"code": null,
"e": 1573,
"s": 1432,
"text": "$encoding− This parameter is used for character encoding. If it is omitted or null, then the internal character encoding value will be used."
},
{
"code": null,
"e": 1714,
"s": 1573,
"text": "$encoding− This parameter is used for character encoding. If it is omitted or null, then the internal character encoding value will be used."
},
{
"code": null,
"e": 1830,
"s": 1714,
"text": "mb_strlen() returns the number of characters present in the given string. One is counted as a multi-byte character."
},
{
"code": null,
"e": 1903,
"s": 1830,
"text": "If the encoding is not known, then it will generate the level E_warning."
},
{
"code": null,
"e": 1914,
"s": 1903,
"text": " Live Demo"
},
{
"code": null,
"e": 2066,
"s": 1914,
"text": "<?php\n // It will return total number of character\n $result = mb_strlen(\"Hello World\",\"UTF-8\");\n echo \"Total number of characters: \", $result;\n?>"
},
{
"code": null,
"e": 2097,
"s": 2066,
"text": "Total number of characters: 11"
},
{
"code": null,
"e": 2153,
"s": 2097,
"text": "Note: that it counts the space too in the given string."
}
] |
accept() - Unix, Linux System Call | Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
accept - accept a connection on a socket
#include <sys/types.h>
#include <sys/socket.h>
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
The accept() system call is used with connection-based socket types (SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection request on the queue of pending connections, creates a new connected socket, and returns a new file
descriptor referring to that socket. The newly created socket is not in the listening state. The original socket sockfd is unaffected by this call.
The argument sockfd is a socket that has been created with socket(2), bound to a local address with bind(2), and is listening for connections after a listen(2).
The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address of the peer socket, as known to the communications layer. The exact format of the address returnedaddr is determined by the socket’s address family (see socket(2) and the respective protocol man pages).
The addrlen argument is a value-result argument: it should initially contain the size of the structure pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. When addr is NULL nothing is filled in.
If no pending connections are present on the queue, and the socket is not marked as non-blocking, accept() blocks the caller until a connection is present. If the socket is marked non-blocking and no pending connections are present on the queue,
accept() fails with the error EAGAIN.
In order to be notified of incoming connections on a socket, you can use select(2) or poll(2). A readable event will be delivered when a new connection is attempted and you may then call accept() to get a socket for that connection. Alternatively, you can set the socket to deliver SIGIO when activity occurs on a socket; see socket(7) for details.
For certain protocols which require an explicit confirmation, such as DECNet, accept() can be thought of as merely dequeuing the next connection request and not implying confirmation. Confirmation can be implied by a normal read or write on the new file descriptor, and rejection can be implied by closing the new socket. Currently only DECNet has these semantics on Linux.
There may not always be a connection waiting after a SIGIO is delivered or select(2) or poll(2) return a readability event because the connection might have been removed by an asynchronous network error or another thread before accept() is called. If this happens then the call will block waiting for the next connection to arrive.
To ensure that accept() never blocks, the passed socket sockfd needs to have the O_NONBLOCK flag set (see socket(7)).
On success, accept() returns a non-negative integer that is a descriptor for the accepted socket. On error, -1 is returned, and errno is set appropriately.
Linux accept() passes already-pending network errors on the new socket as an error code from accept(). This behaviour differs from other BSD socket implementations. For reliable operation the application should detect
the network errors defined for the protocol after accept() and treat them like EAGAIN by retrying. In case of TCP/IP these are ENETDOWN, EPROTO, ENOPROTOOPT, EHOSTDOWN, ENONET, EHOSTUNREACH, EOPNOTSUPP, and ENETUNREACH.
accept() shall fail if:
accept() may fail if:
Linux accept() may fail if:
In addition, network errors for the new socket and as defined for the protocol may be returned. Various Linux kernels can return other errors such as ENOSR, ESOCKTNOSUPPORT, EPROTONOSUPPORT, ETIMEDOUT. The value
ERESTARTSYS may be seen during a trace.
SVr4, 4.4BSD (accept() first appeared in 4.2BSD).
The third argument of accept() was originally declared as an ‘int *’ (and is that under libc4 and libc5 and on many other systems like 4.x BSD, SunOS 4, SGI); a POSIX.1g draft
standard wanted to change it into a ‘size_t *’, and that is what it is for SunOS 5. Later POSIX drafts have ‘socklen_t *’, and so do the Single Unix Specification and glibc2.
bind (2)
bind (2)
connect (2)
connect (2)
listen (2)
listen (2)
select (2)
select (2)
socket (2)
socket (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2360,
"s": 2319,
"text": "accept - accept a connection on a socket"
},
{
"code": null,
"e": 2476,
"s": 2360,
"text": "#include <sys/types.h>\n#include <sys/socket.h> \nint accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);\n"
},
{
"code": null,
"e": 2543,
"s": 2476,
"text": "int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);"
},
{
"code": null,
"e": 2923,
"s": 2543,
"text": "The accept() system call is used with connection-based socket types (SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection request on the queue of pending connections, creates a new connected socket, and returns a new file\ndescriptor referring to that socket. The newly created socket is not in the listening state. The original socket sockfd is unaffected by this call."
},
{
"code": null,
"e": 3084,
"s": 2923,
"text": "The argument sockfd is a socket that has been created with socket(2), bound to a local address with bind(2), and is listening for connections after a listen(2)."
},
{
"code": null,
"e": 3388,
"s": 3084,
"text": "The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address of the peer socket, as known to the communications layer. The exact format of the address returnedaddr is determined by the socket’s address family (see socket(2) and the respective protocol man pages)."
},
{
"code": null,
"e": 3631,
"s": 3388,
"text": "The addrlen argument is a value-result argument: it should initially contain the size of the structure pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. When addr is NULL nothing is filled in."
},
{
"code": null,
"e": 3916,
"s": 3631,
"text": "If no pending connections are present on the queue, and the socket is not marked as non-blocking, accept() blocks the caller until a connection is present. If the socket is marked non-blocking and no pending connections are present on the queue,\naccept() fails with the error EAGAIN."
},
{
"code": null,
"e": 4266,
"s": 3916,
"text": "In order to be notified of incoming connections on a socket, you can use select(2) or poll(2). A readable event will be delivered when a new connection is attempted and you may then call accept() to get a socket for that connection. Alternatively, you can set the socket to deliver SIGIO when activity occurs on a socket; see socket(7) for details."
},
{
"code": null,
"e": 4641,
"s": 4266,
"text": "For certain protocols which require an explicit confirmation, such as DECNet, accept() can be thought of as merely dequeuing the next connection request and not implying confirmation. Confirmation can be implied by a normal read or write on the new file descriptor, and rejection can be implied by closing the new socket. Currently only DECNet has these semantics on Linux."
},
{
"code": null,
"e": 4973,
"s": 4641,
"text": "There may not always be a connection waiting after a SIGIO is delivered or select(2) or poll(2) return a readability event because the connection might have been removed by an asynchronous network error or another thread before accept() is called. If this happens then the call will block waiting for the next connection to arrive."
},
{
"code": null,
"e": 5091,
"s": 4973,
"text": "To ensure that accept() never blocks, the passed socket sockfd needs to have the O_NONBLOCK flag set (see socket(7))."
},
{
"code": null,
"e": 5247,
"s": 5091,
"text": "On success, accept() returns a non-negative integer that is a descriptor for the accepted socket. On error, -1 is returned, and errno is set appropriately."
},
{
"code": null,
"e": 5685,
"s": 5247,
"text": "Linux accept() passes already-pending network errors on the new socket as an error code from accept(). This behaviour differs from other BSD socket implementations. For reliable operation the application should detect\nthe network errors defined for the protocol after accept() and treat them like EAGAIN by retrying. In case of TCP/IP these are ENETDOWN, EPROTO, ENOPROTOOPT, EHOSTDOWN, ENONET, EHOSTUNREACH, EOPNOTSUPP, and ENETUNREACH."
},
{
"code": null,
"e": 5710,
"s": 5685,
"text": "accept() shall fail if: "
},
{
"code": null,
"e": 5732,
"s": 5710,
"text": "accept() may fail if:"
},
{
"code": null,
"e": 5761,
"s": 5732,
"text": "Linux accept() may fail if: "
},
{
"code": null,
"e": 6014,
"s": 5761,
"text": "In addition, network errors for the new socket and as defined for the protocol may be returned. Various Linux kernels can return other errors such as ENOSR, ESOCKTNOSUPPORT, EPROTONOSUPPORT, ETIMEDOUT. The value\nERESTARTSYS may be seen during a trace. "
},
{
"code": null,
"e": 6064,
"s": 6014,
"text": "SVr4, 4.4BSD (accept() first appeared in 4.2BSD)."
},
{
"code": null,
"e": 6415,
"s": 6064,
"text": "The third argument of accept() was originally declared as an ‘int *’ (and is that under libc4 and libc5 and on many other systems like 4.x BSD, SunOS 4, SGI); a POSIX.1g draft\nstandard wanted to change it into a ‘size_t *’, and that is what it is for SunOS 5. Later POSIX drafts have ‘socklen_t *’, and so do the Single Unix Specification and glibc2."
},
{
"code": null,
"e": 6424,
"s": 6415,
"text": "bind (2)"
},
{
"code": null,
"e": 6433,
"s": 6424,
"text": "bind (2)"
},
{
"code": null,
"e": 6445,
"s": 6433,
"text": "connect (2)"
},
{
"code": null,
"e": 6457,
"s": 6445,
"text": "connect (2)"
},
{
"code": null,
"e": 6468,
"s": 6457,
"text": "listen (2)"
},
{
"code": null,
"e": 6479,
"s": 6468,
"text": "listen (2)"
},
{
"code": null,
"e": 6490,
"s": 6479,
"text": "select (2)"
},
{
"code": null,
"e": 6501,
"s": 6490,
"text": "select (2)"
},
{
"code": null,
"e": 6512,
"s": 6501,
"text": "socket (2)"
},
{
"code": null,
"e": 6523,
"s": 6512,
"text": "socket (2)"
},
{
"code": null,
"e": 6540,
"s": 6523,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 6575,
"s": 6540,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 6603,
"s": 6575,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6637,
"s": 6603,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6654,
"s": 6637,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6687,
"s": 6654,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6698,
"s": 6687,
"text": " Pradeep D"
},
{
"code": null,
"e": 6733,
"s": 6698,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6749,
"s": 6733,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 6782,
"s": 6749,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6794,
"s": 6782,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 6826,
"s": 6794,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6834,
"s": 6826,
"text": " Uplatz"
},
{
"code": null,
"e": 6841,
"s": 6834,
"text": " Print"
},
{
"code": null,
"e": 6852,
"s": 6841,
"text": " Add Notes"
}
] |
Using Python To Compile Julia Code Natively | by Emmett Boudreau | Towards Data Science | I frequently discuss the benefits of using Julia, as there are many of them. Julia is a scalable, high-performance, and high-level language that is easy to learn and can get nearly any job done. This is especially true for Data Scientists, as Julia’s center of mass is statistical computing and functional program. At the heart of Julia, it was a language created for scientists doing statistics with data, and this direct intent makes it really great at that particular thing.
Although I could talk for years about how Julia is faster, has better floating point accuracy, and is really simple to type, that is not the reason I’m here today. Though I’ve voiced my concerns and likely over-voiced what I love about Julia, there is one big topic I haven’t covered with Julia:
Versatility
One enormous benefit of using the language Python is that Python is universal. If you don’t want to use a web request, there’s probably a wrapper for it, if you want to convert time stamps from Unix to UTC, there’s a library for it. This is a great benefit because it means that your language will always support your tools. I’ve already mentioned that Julia’s packages are its biggest flaw, but with that being said Julia was originally released in 2012, just 8 years ago. Julia counters this by being:
translatable.
Firstly, we have the amazing package PyCall.jl, which allows the calling of Python packages, even within a virtual environment. Being able to call on millions of Python packages is a pretty big deal in the data science space.
The real fruit in the pudding is that the inverse is also possible. That’s right, it is incredibly easy to run Julia natively from Python. This is huge, because as we all know Python can be rather slow at times. For most situations, I can admit, Python is fantastic, but when Python fails you, it can really leave you high and dry without a clue what to do next.
PyJulia, or julia.py allows you to send lines of code like SQL queries, and identify a return variable for the actual return. So in a nutshell, you can run Julia from Python by sending strings to a Julia compiler. The first step is, of course, to grab Julia from your package manager, I’ll be using APT.
sudo apt-get install julia
Now it’s as simple as entering the Julia REPL, then installing PyCall with either ] or using Pkg.
juliajulia> using Pkg; Pkg.add("PyCall")(or)julia> ]pkg> add "PyCall"
For some Julia packages, including PyCall, I recommend building the code:
julia> ]pkg> build "PyCall"
Now, get out of Pkg with backspace and press ctrl/command+D to exit the Julia REPL. We can now install our Python package with pip, I’ll be using pip3.
sudo pip3 install julia
Now that all of our dependencies are met, we can pop into a notebook and try it out! The first step is to use the install method from the Julia library:
import julia as jljl.install()
And now we can import the Julia executable, and run string code with it!
from julia import Juliajl = Julia()average = jl.run("using Lathe.stats: mean; array = [1,5,4,5,6]; m = mean(array); return(m)")
So... Cool!
But what does this mean? Well, any package developed in Julia will be usable in Python. Not only that, the package can also be used in R with JuliaCall.R. I’ve started work on wrappers for the Lathe machine-learning module for Julia that will be usable under native Julia with both Python and R. I’m really excited for the Julia code to both be faster, and make the package universal in the most popular statistical languages simultaneously. This is a big plus for Julia developers because we don’t have to rewrite code in order to maintain a Python and R version. And of course with that comes the actual benefits of using Julia rather than Python at compile time.
Nothing can ever be this simple in computing, so with this awesome method for translating code, there are also some unfortunate issues. Though slim, I’ll admit that having to install Julia and the PyCall dependency is a little tedious, especially for an end-user of a Python package who has never before used Julia. Additionally, Julia versioning and compatibility have caused a huge issue with this package, it can be rough to get PyJulia up and running. The issue that I ran into was primarily in Unix ownership, where compilers were inside of my non-owned directories (owned by root), and I would get exit status 1 because of denied permissions.
This was of course fixed by using chown on my Python location and doing the same for the Julia situation.
Besides that issue, there is also the way that it’s written, which is a little tedious. Sending single lines of code through strings isn’t really optimal in all honesty, and if you’re going to be using quotations in your code, and playing with strings, it’s going to be awful difficult to navigate between “, “””, and ‘ in Python. Not a big deal, but definitely something to be aware of.
To conclude, versatility is a major benefit to Julia. Julia code is not only fast, and extremely scalable, but can also be written into other languages. This is a big plus because your run of the mill Julia package can be run within a wrapper easily, and consistently updated with the original Julia package as it’s updated on the local system, so... Cool! I greatly anticipate getting Lathe figured out for both R and Python so more people can use Lathe and hopefully come to enjoy it. | [
{
"code": null,
"e": 649,
"s": 171,
"text": "I frequently discuss the benefits of using Julia, as there are many of them. Julia is a scalable, high-performance, and high-level language that is easy to learn and can get nearly any job done. This is especially true for Data Scientists, as Julia’s center of mass is statistical computing and functional program. At the heart of Julia, it was a language created for scientists doing statistics with data, and this direct intent makes it really great at that particular thing."
},
{
"code": null,
"e": 945,
"s": 649,
"text": "Although I could talk for years about how Julia is faster, has better floating point accuracy, and is really simple to type, that is not the reason I’m here today. Though I’ve voiced my concerns and likely over-voiced what I love about Julia, there is one big topic I haven’t covered with Julia:"
},
{
"code": null,
"e": 957,
"s": 945,
"text": "Versatility"
},
{
"code": null,
"e": 1461,
"s": 957,
"text": "One enormous benefit of using the language Python is that Python is universal. If you don’t want to use a web request, there’s probably a wrapper for it, if you want to convert time stamps from Unix to UTC, there’s a library for it. This is a great benefit because it means that your language will always support your tools. I’ve already mentioned that Julia’s packages are its biggest flaw, but with that being said Julia was originally released in 2012, just 8 years ago. Julia counters this by being:"
},
{
"code": null,
"e": 1475,
"s": 1461,
"text": "translatable."
},
{
"code": null,
"e": 1701,
"s": 1475,
"text": "Firstly, we have the amazing package PyCall.jl, which allows the calling of Python packages, even within a virtual environment. Being able to call on millions of Python packages is a pretty big deal in the data science space."
},
{
"code": null,
"e": 2064,
"s": 1701,
"text": "The real fruit in the pudding is that the inverse is also possible. That’s right, it is incredibly easy to run Julia natively from Python. This is huge, because as we all know Python can be rather slow at times. For most situations, I can admit, Python is fantastic, but when Python fails you, it can really leave you high and dry without a clue what to do next."
},
{
"code": null,
"e": 2368,
"s": 2064,
"text": "PyJulia, or julia.py allows you to send lines of code like SQL queries, and identify a return variable for the actual return. So in a nutshell, you can run Julia from Python by sending strings to a Julia compiler. The first step is, of course, to grab Julia from your package manager, I’ll be using APT."
},
{
"code": null,
"e": 2395,
"s": 2368,
"text": "sudo apt-get install julia"
},
{
"code": null,
"e": 2493,
"s": 2395,
"text": "Now it’s as simple as entering the Julia REPL, then installing PyCall with either ] or using Pkg."
},
{
"code": null,
"e": 2563,
"s": 2493,
"text": "juliajulia> using Pkg; Pkg.add(\"PyCall\")(or)julia> ]pkg> add \"PyCall\""
},
{
"code": null,
"e": 2637,
"s": 2563,
"text": "For some Julia packages, including PyCall, I recommend building the code:"
},
{
"code": null,
"e": 2665,
"s": 2637,
"text": "julia> ]pkg> build \"PyCall\""
},
{
"code": null,
"e": 2817,
"s": 2665,
"text": "Now, get out of Pkg with backspace and press ctrl/command+D to exit the Julia REPL. We can now install our Python package with pip, I’ll be using pip3."
},
{
"code": null,
"e": 2841,
"s": 2817,
"text": "sudo pip3 install julia"
},
{
"code": null,
"e": 2994,
"s": 2841,
"text": "Now that all of our dependencies are met, we can pop into a notebook and try it out! The first step is to use the install method from the Julia library:"
},
{
"code": null,
"e": 3025,
"s": 2994,
"text": "import julia as jljl.install()"
},
{
"code": null,
"e": 3098,
"s": 3025,
"text": "And now we can import the Julia executable, and run string code with it!"
},
{
"code": null,
"e": 3226,
"s": 3098,
"text": "from julia import Juliajl = Julia()average = jl.run(\"using Lathe.stats: mean; array = [1,5,4,5,6]; m = mean(array); return(m)\")"
},
{
"code": null,
"e": 3238,
"s": 3226,
"text": "So... Cool!"
},
{
"code": null,
"e": 3904,
"s": 3238,
"text": "But what does this mean? Well, any package developed in Julia will be usable in Python. Not only that, the package can also be used in R with JuliaCall.R. I’ve started work on wrappers for the Lathe machine-learning module for Julia that will be usable under native Julia with both Python and R. I’m really excited for the Julia code to both be faster, and make the package universal in the most popular statistical languages simultaneously. This is a big plus for Julia developers because we don’t have to rewrite code in order to maintain a Python and R version. And of course with that comes the actual benefits of using Julia rather than Python at compile time."
},
{
"code": null,
"e": 4553,
"s": 3904,
"text": "Nothing can ever be this simple in computing, so with this awesome method for translating code, there are also some unfortunate issues. Though slim, I’ll admit that having to install Julia and the PyCall dependency is a little tedious, especially for an end-user of a Python package who has never before used Julia. Additionally, Julia versioning and compatibility have caused a huge issue with this package, it can be rough to get PyJulia up and running. The issue that I ran into was primarily in Unix ownership, where compilers were inside of my non-owned directories (owned by root), and I would get exit status 1 because of denied permissions."
},
{
"code": null,
"e": 4659,
"s": 4553,
"text": "This was of course fixed by using chown on my Python location and doing the same for the Julia situation."
},
{
"code": null,
"e": 5047,
"s": 4659,
"text": "Besides that issue, there is also the way that it’s written, which is a little tedious. Sending single lines of code through strings isn’t really optimal in all honesty, and if you’re going to be using quotations in your code, and playing with strings, it’s going to be awful difficult to navigate between “, “””, and ‘ in Python. Not a big deal, but definitely something to be aware of."
}
] |
Getting the list of keys of a SortedList object in C# | To get the list of keys of a SortedList object, the code is as follows −
Live Demo
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList list1 = new SortedList();
list1.Add("One", 1);
list1.Add("Two ", 2);
list1.Add("Three ", 3);
list1.Add("Four", 4);
list1.Add("Five", 5);
list1.Add("Six", 6);
list1.Add("Seven ", 7);
list1.Add("Eight ", 8);
list1.Add("Nine", 9);
list1.Add("Ten", 10);
Console.WriteLine("SortedList1 elements...");
foreach(DictionaryEntry d in list1) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nList of keys...SortedList1");
IList list = list1.GetKeyList();
foreach(string res in list)
Console.WriteLine(res);
SortedList list2 = new SortedList();
list2.Add("A", "Accessories");
list2.Add("B", "Books");
list2.Add("C", "Smart Wearable Tech");
list2.Add("D", "Home Appliances");
Console.WriteLine("\nSortedList2 elements...");
foreach(DictionaryEntry d in list2) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nList of keys...SortedList2");
list = list2.GetKeyList();
foreach(string res in list)
Console.WriteLine(res);
}
}
This will produce the following output −
SortedList1 elements...
Eight 8
Five 5
Four 4
Nine 9
One 1
Seven 7
Six 6
Ten 10
Three 3
Two 2
List of keys...SortedList1
Eight
Five
Four
Nine
One
Seven
Six
Ten
Three
Two
SortedList2 elements...
A Accessories
B Books
C Smart Wearable Tech
D Home Appliances
List of keys...SortedList2
A
B
C
D
Let us see another example −
Live Demo
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList list = new SortedList();
list.Add("One", 1);
list.Add("Two ", 2);
list.Add("Three ", 3);
list.Add("Four", 4);
list.Add("Five", 5);
Console.WriteLine("SortedList elements...");
foreach(DictionaryEntry d in list) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nList of keys...SortedList");
IList col = list.GetKeyList();
foreach(string res in col)
Console.WriteLine(res);
}
}
This will produce the following output −
SortedList elements...
Five 5
Four 4
One 1
Three 3
Two 2
List of keys...SortedList
Five
Four
One
Three
Two | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To get the list of keys of a SortedList object, the code is as follows −"
},
{
"code": null,
"e": 1146,
"s": 1135,
"text": " Live Demo"
},
{
"code": null,
"e": 2410,
"s": 1146,
"text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main(String[] args) {\n SortedList list1 = new SortedList();\n list1.Add(\"One\", 1);\n list1.Add(\"Two \", 2);\n list1.Add(\"Three \", 3);\n list1.Add(\"Four\", 4);\n list1.Add(\"Five\", 5);\n list1.Add(\"Six\", 6);\n list1.Add(\"Seven \", 7);\n list1.Add(\"Eight \", 8);\n list1.Add(\"Nine\", 9);\n list1.Add(\"Ten\", 10);\n Console.WriteLine(\"SortedList1 elements...\");\n foreach(DictionaryEntry d in list1) {\n Console.WriteLine(d.Key + \" \" + d.Value);\n }\n Console.WriteLine(\"\\nList of keys...SortedList1\");\n IList list = list1.GetKeyList();\n foreach(string res in list)\n Console.WriteLine(res);\n SortedList list2 = new SortedList();\n list2.Add(\"A\", \"Accessories\");\n list2.Add(\"B\", \"Books\");\n list2.Add(\"C\", \"Smart Wearable Tech\");\n list2.Add(\"D\", \"Home Appliances\");\n Console.WriteLine(\"\\nSortedList2 elements...\");\n foreach(DictionaryEntry d in list2) {\n Console.WriteLine(d.Key + \" \" + d.Value);\n }\n Console.WriteLine(\"\\nList of keys...SortedList2\");\n list = list2.GetKeyList();\n foreach(string res in list)\n Console.WriteLine(res);\n }\n}"
},
{
"code": null,
"e": 2451,
"s": 2410,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2746,
"s": 2451,
"text": "SortedList1 elements...\nEight 8\nFive 5\nFour 4\nNine 9\nOne 1\nSeven 7\nSix 6\nTen 10\nThree 3\nTwo 2\nList of keys...SortedList1\nEight\nFive\nFour\nNine\nOne\nSeven\nSix\nTen\nThree\nTwo\nSortedList2 elements...\nA Accessories\nB Books\nC Smart Wearable Tech\nD Home Appliances\nList of keys...SortedList2\nA\nB\nC\nD"
},
{
"code": null,
"e": 2775,
"s": 2746,
"text": "Let us see another example −"
},
{
"code": null,
"e": 2786,
"s": 2775,
"text": " Live Demo"
},
{
"code": null,
"e": 3389,
"s": 2786,
"text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main(String[] args) {\n SortedList list = new SortedList(); \n list.Add(\"One\", 1);\n list.Add(\"Two \", 2);\n list.Add(\"Three \", 3);\n list.Add(\"Four\", 4);\n list.Add(\"Five\", 5);\n Console.WriteLine(\"SortedList elements...\");\n foreach(DictionaryEntry d in list) {\n Console.WriteLine(d.Key + \" \" + d.Value);\n }\n Console.WriteLine(\"\\nList of keys...SortedList\");\n IList col = list.GetKeyList();\n foreach(string res in col)\n Console.WriteLine(res);\n }\n}"
},
{
"code": null,
"e": 3430,
"s": 3389,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3539,
"s": 3430,
"text": "SortedList elements...\nFive 5\nFour 4\nOne 1\nThree 3\nTwo 2\nList of keys...SortedList\nFive\nFour\nOne\nThree\nTwo"
}
] |
How to Make Oblique Lines with CSS / Bootstrap 3 ? - GeeksforGeeks | 16 Nov, 2020
In order to make oblique lines with CSS, there are two main approaches. The first approach involves the clip-path property of CSS and in the second approach, we use transform property with skew() of CSS.
Approach 1: Using clip-path property: The clip-path property is generally used to clip an element to a basic shape. But it can also be used to create oblique lines with tweaking property of polygon shape of clip-path. The main disadvantage of this property is its implementation and since many changes are needed to be observed and changed for converting it into oblique lines.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Oblique Lines in CSS</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style> body{ background-color: burlywood; margin:0; } div.polygon{ height: 100vh; width: 100vw; background: aliceblue; clip-path: polygon(0 60%, 100% 3%, 100% 100%, 0 75%); display:flex; } .content{ height: 50%; width: 100%; padding-top: 10px; margin: auto; color: green; } </style></head> <body> <div class="content"> <h2>GeeksForGeeks</h2> <p> This is a example of creating oblique lines with content using clip-path property of CSS. </p> </div> <div class="polygon"></div></body> </html>
Output:
The output image contains two oblique lines this is the zoomed output of the above part.
Using clip-path property and polygon as shape
Approach 2: Using transform property: The transform skew property of CSS helps in rotating the division along x and y-axis. The skewX() and skewY() takes degrees of rotation as input. This property implementation is simple as compared to clip-path. Also, if you don’t want to rotate the content then we need to rotate in the reverse direction of division.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Oblique line using CSS</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style> body { background-color: aliceblue; } .maintransform { margin-right: 1px; margin-left: 0px; background-color: burlywood; position: absolute; top: 33px; left: 0px; right: 0px; height: 250px; color: green; font-family: Arial, Helvetica, sans-serif; -ms-transform: skewY(5deg); -webkit-transform: skewY(5deg); transform: skewY(5deg); } .content { -ms-transform: skewY(5deg); -webkit-transform: skewY(5deg); transform: skewY(-5deg); padding-left: 0px; } </style></head> <body> <div class="maintransform"> <h2 class="content">GeeksForGeeks</h2> <p class="content"> This is a example of creating oblique lines with content using transform property of CSS. In this example the skewY() is set to +5degrees. You can change the angle according to your need. </p> </div></body> </html>
Output:
Here the rotation is around the y-axis and skew angle is +5(deg) whereas the text angle is at -5(deg) to make the text straight.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Bootstrap-Misc
CSS-Misc
HTML-Misc
Bootstrap
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to keep gap between columns using Bootstrap?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form | [
{
"code": null,
"e": 25596,
"s": 25568,
"text": "\n16 Nov, 2020"
},
{
"code": null,
"e": 25800,
"s": 25596,
"text": "In order to make oblique lines with CSS, there are two main approaches. The first approach involves the clip-path property of CSS and in the second approach, we use transform property with skew() of CSS."
},
{
"code": null,
"e": 26179,
"s": 25800,
"text": "Approach 1: Using clip-path property: The clip-path property is generally used to clip an element to a basic shape. But it can also be used to create oblique lines with tweaking property of polygon shape of clip-path. The main disadvantage of this property is its implementation and since many changes are needed to be observed and changed for converting it into oblique lines. "
},
{
"code": null,
"e": 26184,
"s": 26179,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Oblique Lines in CSS</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\"> <style> body{ background-color: burlywood; margin:0; } div.polygon{ height: 100vh; width: 100vw; background: aliceblue; clip-path: polygon(0 60%, 100% 3%, 100% 100%, 0 75%); display:flex; } .content{ height: 50%; width: 100%; padding-top: 10px; margin: auto; color: green; } </style></head> <body> <div class=\"content\"> <h2>GeeksForGeeks</h2> <p> This is a example of creating oblique lines with content using clip-path property of CSS. </p> </div> <div class=\"polygon\"></div></body> </html>",
"e": 27393,
"s": 26184,
"text": null
},
{
"code": null,
"e": 27401,
"s": 27393,
"text": "Output:"
},
{
"code": null,
"e": 27490,
"s": 27401,
"text": "The output image contains two oblique lines this is the zoomed output of the above part."
},
{
"code": null,
"e": 27536,
"s": 27490,
"text": "Using clip-path property and polygon as shape"
},
{
"code": null,
"e": 27894,
"s": 27536,
"text": "Approach 2: Using transform property: The transform skew property of CSS helps in rotating the division along x and y-axis. The skewX() and skewY() takes degrees of rotation as input. This property implementation is simple as compared to clip-path. Also, if you don’t want to rotate the content then we need to rotate in the reverse direction of division. "
},
{
"code": null,
"e": 27899,
"s": 27894,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Oblique line using CSS</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\"> <style> body { background-color: aliceblue; } .maintransform { margin-right: 1px; margin-left: 0px; background-color: burlywood; position: absolute; top: 33px; left: 0px; right: 0px; height: 250px; color: green; font-family: Arial, Helvetica, sans-serif; -ms-transform: skewY(5deg); -webkit-transform: skewY(5deg); transform: skewY(5deg); } .content { -ms-transform: skewY(5deg); -webkit-transform: skewY(5deg); transform: skewY(-5deg); padding-left: 0px; } </style></head> <body> <div class=\"maintransform\"> <h2 class=\"content\">GeeksForGeeks</h2> <p class=\"content\"> This is a example of creating oblique lines with content using transform property of CSS. In this example the skewY() is set to +5degrees. You can change the angle according to your need. </p> </div></body> </html>",
"e": 29457,
"s": 27899,
"text": null
},
{
"code": null,
"e": 29465,
"s": 29457,
"text": "Output:"
},
{
"code": null,
"e": 29594,
"s": 29465,
"text": "Here the rotation is around the y-axis and skew angle is +5(deg) whereas the text angle is at -5(deg) to make the text straight."
},
{
"code": null,
"e": 29731,
"s": 29594,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29746,
"s": 29731,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 29755,
"s": 29746,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29765,
"s": 29755,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29775,
"s": 29765,
"text": "Bootstrap"
},
{
"code": null,
"e": 29779,
"s": 29775,
"text": "CSS"
},
{
"code": null,
"e": 29784,
"s": 29779,
"text": "HTML"
},
{
"code": null,
"e": 29801,
"s": 29784,
"text": "Web Technologies"
},
{
"code": null,
"e": 29806,
"s": 29801,
"text": "HTML"
},
{
"code": null,
"e": 29904,
"s": 29806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29945,
"s": 29904,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 30008,
"s": 29945,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 30041,
"s": 30008,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 30067,
"s": 30041,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 30116,
"s": 30067,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 30166,
"s": 30116,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 30228,
"s": 30166,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30286,
"s": 30228,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 30334,
"s": 30286,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Shell Script to Enhance the Calendar to Accept MM, MMM, YYYY - GeeksforGeeks | 20 Sep, 2021
We are going to write a shell script to enhance the calendar to accept any month as MM or MMM or only year as YYYY or both month and year. Our shell script will accept at least one argument which will be either month or year. Maximum 2 arguments will be used which will be month and year. An enhanced calendar will be displayed using the specified arguments. We are going to use the cal and ncal command in Linux to display calendars.
If a user wants a quick view of the calendar in the Linux terminal, cal is the command for you. By default, the cal command shows the current month calendar as output.
The cal command in Linux is used to view the calendar for a specific month or for the entire year. A single argument in the cal command defines the four-digit year (1-9999) to be shown. Month (1-12) and Year(1 – 9999) is represented by two parameters. If no arguments are given, then the current month is shown.
We can use the following command to know more about cal utility in Linux:
man cal
For example:
StartCheck whether arguments are passed or notIf no arguments are passed then display “Invalid arguments and exit program”If 2 arguments are passed thencheck whether 1st arguments are greater than 12 and the second argument is greater than 2021 (current year).If it is greater, then display”invalid year or month” and go to step 12Else if only one argument is passed then check whether it is greater than 12.If it is greater than 12 then it is considered a year.Then display a calendar of the specified year.else if the argument is smaller than 12 then the passed argument is a month.Display calendar of the specified month of the current year.Exit.
Start
Check whether arguments are passed or not
If no arguments are passed then display “Invalid arguments and exit program”
If 2 arguments are passed then
check whether 1st arguments are greater than 12 and the second argument is greater than 2021 (current year).
If it is greater, then display”invalid year or month” and go to step 12
Else if only one argument is passed then check whether it is greater than 12.
If it is greater than 12 then it is considered a year.
Then display a calendar of the specified year.
else if the argument is smaller than 12 then the passed argument is a month.
Display calendar of the specified month of the current year.
Exit.
Below is the implementation using cal command:-
# Shell Script to Enhance the Calendar to Accept
# MM, MMM, YYYY using cal command
# check whether arguments are passed or not
if [ $# -eq 0 ]
then
# if arguments are not passed then display this
echo "Invalid Arguments"
# exit the program
exit
fi
# if 2 arguments are passed
if [ $# -eq 2 ]
then
# if argument 1 is greater than 12 or argument 2
# is greater than 2021
if [ $1 -gt 12 -o $2 -gt 2021 ]
then
# then display invalid month or year
echo "invalid Year or month"
# else display calendar of the specified month
# and year
else
ncal $1 $2
fi
# if only one argument is passed then
else if [ $# -eq 1 ]
then
# if argument is greater than 12
if [ $1 -gt 12 ]
then
cal $1 # display calendar of specified year
# else display calendar of specified month
else
case $1 in #start switch case
01) m = jan;;
02) m = feb;;
03) m = mar;;
04) m = apr;;
05) m = may;;
06) m = jun;;
07) m = jul;;
08) m = aug;;
09) m = sep;;
10) m = oct;;
11) m = nov;;
12) m = dec;;
esac # end switch case
echo \" Calander for $1 Month : \"
# display calendar of specified month using -m
cal -m $1
fi
fi
fi
Output:
The ncal command can also be used to display the calendar. The ncal command has the same functionality as cal, except it may show the calendar vertically with weeks in columns instead of horizontally. We can use the following command to know more about cal utility in Linux:
man ncal
For example:
In the above examples, In the cal or ncal command, if the user types the “cal 2” command in the terminal then, it will display the whole calendar of year 0002. But to enhance the calendar, if the user enters 2 as an argument then the second month of the current year should be displayed. We will use the cal/ncal utility to Enhance the Calendar to Accept MM, MMM, YYYY.
Below is the implementation using ncal command:-
# Shell Script to Enhance the Calendar to Accept MM, MMM, YYYY
# using ncal command
# check whether arguments are passed or not
if [ $# -eq 0 ]
then
# if arguments are not passed then display this
echo "Invalid Arguments"
# exit the program
exit
fi
if [ $# -eq 2 ] # if 2 arguments are passed
then
# if argument 1 is greater than 12 or argument 2 is
# greater than 2021
if [ $1 -gt 12 -o $2 -gt 2021 ]
then
# then display invalid month or year
echo "invalid Year or month"
# else display calendar of the specified month and year
else
ncal $1 $2
fi
else if [ $# -eq 1 ] # if only one argument is passed then
then
if [ $1 -gt 12 ] # if argument is greater than 12
then
cal $1 # display calendar of specified year
else # else display calendar of specified month
case $1 in #start switch case
01) m = jan;;
02) m = feb;;
03) m = mar;;
04) m = apr;;
05) m = may;;
06) m = jun;;
07) m = jul;;
08) m = aug;;
09) m = sep;;
10) m = oct;;
11) m = nov;;
12) m = dec;;
esac # end switch case
echo \" Calander for $1 Month : \"
ncal -m $1 # display calendar of specified month using -m
fi
fi
fi
#end if
Output:
ncal command will display a calendar in a more enhanced way.
In the script, if the user enters one argument then we will check whether it is greater than 12, if it is greater than 12 then the argument will be considered as a year else argument will be considered as a month. If no argument is given, then “Invalid arguments is displayed.”. If 2 arguments are given then it will denote a month and a year.
To run the shell script use:
./cal.sh <argument 1> <argument 2>
Example:
./cal.sh 4
./cal.sh 8 2021
./cal.sh 1999
Give execution permission to shell script using:
chmod +x cal.sh
Hence the above Shell Script will Enhance the Calendar to Accept MM, MMM, YYYY.
kapoorsagar226
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
mv command in Linux with examples
nohup Command in Linux with Examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples | [
{
"code": null,
"e": 24041,
"s": 24013,
"text": "\n20 Sep, 2021"
},
{
"code": null,
"e": 24477,
"s": 24041,
"text": " We are going to write a shell script to enhance the calendar to accept any month as MM or MMM or only year as YYYY or both month and year. Our shell script will accept at least one argument which will be either month or year. Maximum 2 arguments will be used which will be month and year. An enhanced calendar will be displayed using the specified arguments. We are going to use the cal and ncal command in Linux to display calendars."
},
{
"code": null,
"e": 24645,
"s": 24477,
"text": "If a user wants a quick view of the calendar in the Linux terminal, cal is the command for you. By default, the cal command shows the current month calendar as output."
},
{
"code": null,
"e": 24958,
"s": 24645,
"text": "The cal command in Linux is used to view the calendar for a specific month or for the entire year. A single argument in the cal command defines the four-digit year (1-9999) to be shown. Month (1-12) and Year(1 – 9999) is represented by two parameters. If no arguments are given, then the current month is shown. "
},
{
"code": null,
"e": 25032,
"s": 24958,
"text": "We can use the following command to know more about cal utility in Linux:"
},
{
"code": null,
"e": 25040,
"s": 25032,
"text": "man cal"
},
{
"code": null,
"e": 25053,
"s": 25040,
"text": "For example:"
},
{
"code": null,
"e": 25703,
"s": 25053,
"text": "StartCheck whether arguments are passed or notIf no arguments are passed then display “Invalid arguments and exit program”If 2 arguments are passed thencheck whether 1st arguments are greater than 12 and the second argument is greater than 2021 (current year).If it is greater, then display”invalid year or month” and go to step 12Else if only one argument is passed then check whether it is greater than 12.If it is greater than 12 then it is considered a year.Then display a calendar of the specified year.else if the argument is smaller than 12 then the passed argument is a month.Display calendar of the specified month of the current year.Exit."
},
{
"code": null,
"e": 25709,
"s": 25703,
"text": "Start"
},
{
"code": null,
"e": 25751,
"s": 25709,
"text": "Check whether arguments are passed or not"
},
{
"code": null,
"e": 25828,
"s": 25751,
"text": "If no arguments are passed then display “Invalid arguments and exit program”"
},
{
"code": null,
"e": 25859,
"s": 25828,
"text": "If 2 arguments are passed then"
},
{
"code": null,
"e": 25968,
"s": 25859,
"text": "check whether 1st arguments are greater than 12 and the second argument is greater than 2021 (current year)."
},
{
"code": null,
"e": 26040,
"s": 25968,
"text": "If it is greater, then display”invalid year or month” and go to step 12"
},
{
"code": null,
"e": 26118,
"s": 26040,
"text": "Else if only one argument is passed then check whether it is greater than 12."
},
{
"code": null,
"e": 26173,
"s": 26118,
"text": "If it is greater than 12 then it is considered a year."
},
{
"code": null,
"e": 26220,
"s": 26173,
"text": "Then display a calendar of the specified year."
},
{
"code": null,
"e": 26297,
"s": 26220,
"text": "else if the argument is smaller than 12 then the passed argument is a month."
},
{
"code": null,
"e": 26358,
"s": 26297,
"text": "Display calendar of the specified month of the current year."
},
{
"code": null,
"e": 26364,
"s": 26358,
"text": "Exit."
},
{
"code": null,
"e": 26412,
"s": 26364,
"text": "Below is the implementation using cal command:-"
},
{
"code": null,
"e": 27864,
"s": 26412,
"text": "# Shell Script to Enhance the Calendar to Accept \n# MM, MMM, YYYY using cal command\n\n# check whether arguments are passed or not\nif [ $# -eq 0 ]\nthen\n\n # if arguments are not passed then display this\n echo \"Invalid Arguments\"\n \n # exit the program\n exit \nfi \n\n# if 2 arguments are passed\nif [ $# -eq 2 ] \nthen\n\n # if argument 1 is greater than 12 or argument 2 \n # is greater than 2021\n if [ $1 -gt 12 -o $2 -gt 2021 ]\n then\n \n # then display invalid month or year\n echo \"invalid Year or month\"\n \n # else display calendar of the specified month \n # and year\n else\n ncal $1 $2 \n fi\n \n# if only one argument is passed then\nelse if [ $# -eq 1 ]\nthen\n\n # if argument is greater than 12\n if [ $1 -gt 12 ]\n then\n cal $1 # display calendar of specified year\n \n # else display calendar of specified month\n else\n case $1 in #start switch case\n 01) m = jan;;\n 02) m = feb;;\n 03) m = mar;;\n 04) m = apr;;\n 05) m = may;;\n 06) m = jun;;\n 07) m = jul;;\n 08) m = aug;;\n 09) m = sep;;\n 10) m = oct;;\n 11) m = nov;;\n 12) m = dec;;\n esac # end switch case\n echo \\\" Calander for $1 Month : \\\"\n \n # display calendar of specified month using -m\n cal -m $1\n\n fi\nfi\nfi"
},
{
"code": null,
"e": 27872,
"s": 27864,
"text": "Output:"
},
{
"code": null,
"e": 28147,
"s": 27872,
"text": "The ncal command can also be used to display the calendar. The ncal command has the same functionality as cal, except it may show the calendar vertically with weeks in columns instead of horizontally. We can use the following command to know more about cal utility in Linux:"
},
{
"code": null,
"e": 28156,
"s": 28147,
"text": "man ncal"
},
{
"code": null,
"e": 28169,
"s": 28156,
"text": "For example:"
},
{
"code": null,
"e": 28540,
"s": 28169,
"text": "In the above examples, In the cal or ncal command, if the user types the “cal 2” command in the terminal then, it will display the whole calendar of year 0002. But to enhance the calendar, if the user enters 2 as an argument then the second month of the current year should be displayed. We will use the cal/ncal utility to Enhance the Calendar to Accept MM, MMM, YYYY. "
},
{
"code": null,
"e": 28589,
"s": 28540,
"text": "Below is the implementation using ncal command:-"
},
{
"code": null,
"e": 30024,
"s": 28589,
"text": "# Shell Script to Enhance the Calendar to Accept MM, MMM, YYYY\n# using ncal command\n\n# check whether arguments are passed or not\nif [ $# -eq 0 ]\nthen\n\n # if arguments are not passed then display this\n echo \"Invalid Arguments\" \n \n # exit the program\n exit \nfi \n\nif [ $# -eq 2 ] # if 2 arguments are passed\nthen\n\n # if argument 1 is greater than 12 or argument 2 is \n # greater than 2021\n if [ $1 -gt 12 -o $2 -gt 2021 ] \n then\n \n # then display invalid month or year\n echo \"invalid Year or month\" \n \n # else display calendar of the specified month and year \n else\n ncal $1 $2 \n fi\nelse if [ $# -eq 1 ] # if only one argument is passed then\nthen\n if [ $1 -gt 12 ] # if argument is greater than 12\n then\n cal $1 # display calendar of specified year\n else # else display calendar of specified month\n case $1 in #start switch case\n 01) m = jan;;\n 02) m = feb;;\n 03) m = mar;;\n 04) m = apr;;\n 05) m = may;;\n 06) m = jun;;\n 07) m = jul;;\n 08) m = aug;;\n 09) m = sep;;\n 10) m = oct;;\n 11) m = nov;;\n 12) m = dec;;\n esac # end switch case\n echo \\\" Calander for $1 Month : \\\"\n ncal -m $1 # display calendar of specified month using -m\n\n fi\nfi\nfi\n#end if"
},
{
"code": null,
"e": 30032,
"s": 30024,
"text": "Output:"
},
{
"code": null,
"e": 30093,
"s": 30032,
"text": "ncal command will display a calendar in a more enhanced way."
},
{
"code": null,
"e": 30438,
"s": 30093,
"text": "In the script, if the user enters one argument then we will check whether it is greater than 12, if it is greater than 12 then the argument will be considered as a year else argument will be considered as a month. If no argument is given, then “Invalid arguments is displayed.”. If 2 arguments are given then it will denote a month and a year. "
},
{
"code": null,
"e": 30467,
"s": 30438,
"text": "To run the shell script use:"
},
{
"code": null,
"e": 30502,
"s": 30467,
"text": "./cal.sh <argument 1> <argument 2>"
},
{
"code": null,
"e": 30511,
"s": 30502,
"text": "Example:"
},
{
"code": null,
"e": 30552,
"s": 30511,
"text": "./cal.sh 4\n./cal.sh 8 2021\n./cal.sh 1999"
},
{
"code": null,
"e": 30601,
"s": 30552,
"text": "Give execution permission to shell script using:"
},
{
"code": null,
"e": 30617,
"s": 30601,
"text": "chmod +x cal.sh"
},
{
"code": null,
"e": 30697,
"s": 30617,
"text": "Hence the above Shell Script will Enhance the Calendar to Accept MM, MMM, YYYY."
},
{
"code": null,
"e": 30712,
"s": 30697,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 30719,
"s": 30712,
"text": "Picked"
},
{
"code": null,
"e": 30732,
"s": 30719,
"text": "Shell Script"
},
{
"code": null,
"e": 30743,
"s": 30732,
"text": "Linux-Unix"
},
{
"code": null,
"e": 30841,
"s": 30743,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30850,
"s": 30841,
"text": "Comments"
},
{
"code": null,
"e": 30863,
"s": 30850,
"text": "Old Comments"
},
{
"code": null,
"e": 30889,
"s": 30863,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 30923,
"s": 30889,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 30960,
"s": 30923,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 30995,
"s": 30960,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 31021,
"s": 30995,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 31058,
"s": 31021,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 31098,
"s": 31058,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 31127,
"s": 31098,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 31169,
"s": 31127,
"text": "Named Pipe or FIFO with example C program"
}
] |
C++ program to find union and intersection of two unsorted arrays | In this article, we will be discussing a program to find the union and intersection of two given unsorted arrays.
Let us denote the two arrays with ‘A’ and ‘B’. Then union of those arrays is denoted by A ∪ B which is basically an array of all the elements in both the given arrays; provided that each element repeats only once.
To find this, we will create a separate array and copy down all the elements from the first array. Then we will traverse through the elements of the second array and check if it is already present in the union array. If it isn’t, then we will add it to the union array.
Similarly, intersection of two arrays will be denoted by A ∩ B. It is an array of the elements that are present in both the given arrays.
For this, we will traverse through the elements of the first array one by one. Simultaneously we will be checking if that element is present in the second array or not. If the element is present in both the arrays, then we will add it to an intersection array.
Live Demo
#include <iostream>
using namespace std;
int main() {
int len1 = 4, len2 = 3, flag1 = 0, flag2 = 0;
int array1[len1] = {1,2,3,4}, array2[len2] = {5,3,4};
int uni[len1+len2] = {1,2,3,4}, inter[len1];
for(int k = 0; k < len2 ; k++) {
flag1 = len1;
for(int m = 0; m < len1; m++) {
//eliminating common elements among the given arrays
if(array2[k] == uni[m])
break;
else if(m == len1-1) {
uni[flag1] = array2[k];
flag1 = flag1+1;
}
}
}
for(int q = 0; q < len1; q++) {
for(int w = 0; w < len2; w++) {
//checking if both arrays contain a particular element
if(array1[q] == array2[w]) {
inter[flag2] = array1[q];
flag2 = flag2+1;
break;
}
}
}
cout << "Union :" <<endl;
for(int u = 0; u < flag1; u++) {
cout << uni[u] << " ";
}
cout << "\nIntersection :" <<endl;
for(int i = 0; i < flag2; i++) {
cout << inter[i] << " ";
}
return 0;
}
Union :
1 2 3 4
Intersection :
3 4 | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "In this article, we will be discussing a program to find the union and intersection of two given unsorted arrays."
},
{
"code": null,
"e": 1390,
"s": 1176,
"text": "Let us denote the two arrays with ‘A’ and ‘B’. Then union of those arrays is denoted by A ∪ B which is basically an array of all the elements in both the given arrays; provided that each element repeats only once."
},
{
"code": null,
"e": 1660,
"s": 1390,
"text": "To find this, we will create a separate array and copy down all the elements from the first array. Then we will traverse through the elements of the second array and check if it is already present in the union array. If it isn’t, then we will add it to the union array."
},
{
"code": null,
"e": 1798,
"s": 1660,
"text": "Similarly, intersection of two arrays will be denoted by A ∩ B. It is an array of the elements that are present in both the given arrays."
},
{
"code": null,
"e": 2059,
"s": 1798,
"text": "For this, we will traverse through the elements of the first array one by one. Simultaneously we will be checking if that element is present in the second array or not. If the element is present in both the arrays, then we will add it to an intersection array."
},
{
"code": null,
"e": 2070,
"s": 2059,
"text": " Live Demo"
},
{
"code": null,
"e": 3116,
"s": 2070,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int len1 = 4, len2 = 3, flag1 = 0, flag2 = 0;\n int array1[len1] = {1,2,3,4}, array2[len2] = {5,3,4};\n int uni[len1+len2] = {1,2,3,4}, inter[len1];\n for(int k = 0; k < len2 ; k++) {\n flag1 = len1;\n for(int m = 0; m < len1; m++) {\n //eliminating common elements among the given arrays\n if(array2[k] == uni[m])\n break;\n else if(m == len1-1) {\n uni[flag1] = array2[k];\n flag1 = flag1+1;\n }\n }\n }\n for(int q = 0; q < len1; q++) {\n for(int w = 0; w < len2; w++) {\n //checking if both arrays contain a particular element\n if(array1[q] == array2[w]) {\n inter[flag2] = array1[q];\n flag2 = flag2+1;\n break;\n }\n }\n }\n cout << \"Union :\" <<endl;\n for(int u = 0; u < flag1; u++) {\n cout << uni[u] << \" \";\n }\n cout << \"\\nIntersection :\" <<endl;\n for(int i = 0; i < flag2; i++) {\n cout << inter[i] << \" \";\n }\n return 0;\n}"
},
{
"code": null,
"e": 3151,
"s": 3116,
"text": "Union :\n1 2 3 4\nIntersection :\n3 4"
}
] |
Data Visualization using Python for Machine Learning and Data science : | by Sanat | Towards Data Science | Good day Folks,
Myself is Sanat currently working in IBM and I’m basically a Data Scientist, who loves to make my hand dirty on playing with a huge amount of data. Let me cut short my boring intro here :P and move towards the topic of the day “Data Visualization”.
Note : This blog was made keeping in mind that the person reading is just aware of very basics on data visualizations and some topics may be too naive. So please skip the topics that you knew already and enjoy the rest. I am open to all your comments regarding the blog.
As we all knew that there is a huge buzz going over the term data, like Big data, Data science, Data Analysts, Data Warehouse,Data mining etc. which emphasize that, In the current era data plays a major role in influencing day to day activities of the mankind. Everyday we are generating more than 2.5 quintillion( 1018) bytes of data(Link) ranging from our Text messages, Images, emails, till data from autonomous cars, IOT devices etc. With such huge amount of data being available on hand, leveraging useful information from this data can help each and every organization very much, for getting a clear insight on several areas like, what can bring a boost for their organization’s revenue, which field needs more focus, how to seek more customer’s attention etc. Machine learning(ML), Data science are some of the interrelated areas of Artificial Intelligence(AI) where this task of learning from data is done in a huge extent on these recent days.
From above intro, now you may be fascinated with the term “Data” and will be planning to make use of these available data much effectively, to get as much useful information as possible. Do you think it is very easy to interpret these collected data? May be No :( . The data will be in raw format and there are several steps that needs to be performed to convert this raw data to an useful information, just like how a goldsmith prepares an ornament by doing several preprocessing steps on raw gold. This is where a Data scientist comes in handy, You throw him/her a raw data, they can narrate you a great story from that, which would not be as easy for others when provided with same data. There will be several stages when those data scientists write their story ( I mean working with the data :P ) like Data acquisition, Data cleaning, Data Visualization, building a model that can be used to predict the future information etc. Among them one key stage is Data Visualization. This is the first and foremost step where they will get a high level statistical overview on how the data is. and some of its attributes like the underlying distribution, presence of outliers, and several more useful features.
“Data is the new oil? No, data is the new soil.” — David McCandless
Do you think giving you the data of lets say 1 Million points in a table/Database file and asking you to provide your inferences by just seeing the data on that table is feasible? Unless you’re a super human its not possible. This is when we make use of Data visualization, wherein all the data will be transformed into some form of plots and analyzed further from that. As being a human, we are more used to grasp a lot of info from diagrammatic representation than the counterparts.
Kids should learn how to read and create graphics from a very young age. Most kids are natural-born artists, as we humans are a visual species. We should take advantage of that, as graphics and illustrations can be such a powerful weapon for understanding and communicating — Prof. Alberto Cairo,
Okay ! So since it is said that we need to convert the data from a boring table into an interesting pictorial form like a scatter plot or Bar chart, You may wonder, How can I do it? Do I need to write my own code for that ? NO! Actually we can make use of very good packages from some popular programming languages which are readily available and can make the work pretty much simple with just a single line of code. That’s the power of modern programming :D !
As a human, we can just visualize anything in either in 2-d or 3-d. But trust me almost of the data that you obtain in real world won’t be this way. As a Machine learning engineer, working with more than 1000-dimensional data is very common. So what can we do in such cases where data is more than 3D ? There are some Dimensionality Reduction(DR) techniques like PCA, TSNE , LDA etc which helps you to convert data from a higher dimension to a 2D or 3D data in order to visualize them. There may be some loss of information with each DR techniques, but only they can help us visualize very high dimensional data on a 2d plot. TSNE is one of the state of the art DR technique employed for visualization of high dimensional data.
From perspective of building models , By visualizing the data we can find the hidden patterns, Explore if there are any clusters within data and we can find if they are linearly separable/too much overlapped etc. From this initial analysis we can easily rule out the models that won’t be suitable for such a data and we will implement only the models that are suitable, without wasting our valuable time and the computational resources.
This part of data visualization is a predominant one in initial Exploratory Data Analysis (EDA) on the field of Data science/ML.
There may be several languages on which we can perform the Data Visualization, but the ones that are much widely used in the field of Data Science are Python & R. So your next question may be, Which one to learn and which one has a better scope ?. The answer is simple! It’s purely your choice but I would recommend Python ;) . ‘R’ is way more statistical language and has several great packages for Data science applications, whereas Python on the other hand is widely used in general purpose programming as well as for Data science and ML related applications. I am pretty comfortable with python and so I will continue the rest of the blog with python codes and also it has several good packages like Scikit,Matplotlib,seaborn etc which helps us a lot. A special thanks to those developers who made our work simple.
As mentioned above, Python has several good packages to plot the data and among them Matplotlib is the most prominent one. Seaborn is also a great package which offers a lot more appealing plot and even it uses matplotlib as its base layer. There are also many similar type of plots available in Pandas when the entire data is stored in a pandas dataframe, we also have a library called plotly and etc. In this blog we are going to discuss about the different types of plots that are under the 2 packages mentioned at the start and let us explore them in detail.
There are overall 3 different layers in the architecture of matplotlib as follows.
) Backend layer.) Artist layer.) Scripting layer.
) Backend layer.
) Artist layer.
) Scripting layer.
Backend layer:
This is the bottom most layer of a figure which contains implementation of several functions that are required for plotting. There are 3 main classes from the backend layer FigureCanvas ( the layer/Surface on which the figure will be drawn), Renderer (the classn that takes care of the drawing on the surface ) and Event ( to handle the mouse and keyboard events). We don’t work much with the Backend layer as compared to the counterparts.
Artist Layer:
This is the second/middle most layer in the architecture. It is what does most of the duty on plotting the various functions, like axis which coordinates on how to use the renderer on the Figure canvas. To put it simple, lets consider Paper as the Figure Canvas and Sketch pen as renderer. Then the hand of the painter is the Artist layer which has certain functions, knows how to sketch to get the exact figure. There are several classes available on artist layer and a few important ones are Figure, Axes and Axis.
The 2 images above explain the hierarchy between various classes in the artist layer. Figure is the topmost one and a figure can contain multiple number of axes upon which the plot is done. Moving on, under each axes we can add multiple plots. This provides a lot more additional functionality to improve the plots and this is the place where most of the heavy lifting works takes place.
Scripting layer:
This is the topmost layer on which majority of our codes will play around. For day to day exploratory works, we almost rely on this scripting layer of matplotlib. Pyplot is the scripting layer that provides almost simlar functionality as that of Matlab in python. The methods in scripting layer, almost automatically takes care of the other layers and all we need to care about is the current state(figure & Subplot). Hence it is also called as stateful interface.
Please visit the link for reference.
Here lets have a short glance on some of the commonly used terms in data visualization using Matplotlib.
P.S: Wherever plt.(Some function) is used, it means that I imported matplotlib.pyplot as plt in my program and sns means that i imported seaborn just for the ease of coding.
import matplotlib.pyplot as pltimport seaborn as sns
If you don’t have the packages already installed in your system. Please install Python 3 and use the below code on your command prompt.
pip3 install matplotlibpip3 install seaborn
Axes:
Axes is the entire area of a single plot in the figure. It is the class that contains several attributes needed to draw a plot such as like adding title, giving labels, selecting bin values for different types of plots on each axes etc.
We can have multiple axes in a single plot, by which we can combine multiple plots into a single figure. For e.g: If we want both PDF and CDF curves in a same figure we can create 2 axes and draw each of them in different axes. Then we can combine them into a single figure.
Link
Grid:
When grid is enabled in a plot, a set of horizontal and vertical lines will be added at the background layer of the plot.This can be enabled using plt.grid(). It can be useful for a rough estimation of value at a particular coordinate, just by looking at the plot.
Ref: Link
Legend:
Legends are nothing but labeled representation of the different plots available in a figure. i.e when there are multiple plots in a single image(e.g : Iris dataset), Legends will help us to identify the correct name of the different colored plots in a single figure.
Ref: Link
Subplots:
When we want 2 or more plots in a single image, we can make use of Subplot in Matplotlib, plt.subplot (xyz). xyz is a 3 digit integer where x-No of rows, y =No of columns, z= index number of that plot. This is one of the most useful feature when we need to compare two or more plots hand to hand instead of having them in separate images.
plt.figure(1,figsize=(30,8))plt.subplot(131) #Code for fig1.plt.subplot(132)#code for fig2plt.subplot(133)#code for fig3.plt.show()
In addition to Subplot try using gridspec , which can help us split the plots in subplot more effectively and easier.
Ref: Link
Title:
We can set a title to a plot using plt.title()
xlabel:
plt.xlabel() is the command to set the label for x axis
ylabel:
plt.ylabel() is the command to set the label for y axis
The below image very well explains each and every parts in visualizing data as a figure.
There are different types of analysis as mentioned below.
Univariate : In univariate analysis we will be using a single feature to analyze almost of its properties.Bivariate : When we compare the data between exactly 2 features then its called bivariate analysis.Multivariate: Comparing more than 2 variables is called as Multivariate analysis.
Univariate : In univariate analysis we will be using a single feature to analyze almost of its properties.
Bivariate : When we compare the data between exactly 2 features then its called bivariate analysis.
Multivariate: Comparing more than 2 variables is called as Multivariate analysis.
In the below blog, for each plot I will mark them as (U),(B) & (M) to represent them as Univariate, Bivariate and Multivariate plots correspondingly.
The below are the list of plots that I am going to explain in the subsequent topics.
i) Scatter plot (B)
ii) Pair plot (M)
iii) Box plot (U)
iv) Violin plot(U)
v) Distribution plot (U)
vi) Joint plot(U) & (B)
vii) Bar chart (B)
viii) Line plot(B)
As far as Machine learning/Data Science is concerned, one of the most commonly used plot for simple data visualization is scatter plots. This plot gives us a representation of where each points in the entire dataset are present with respect to any 2/3 features(Columns). Scatter plots are available in 2D as well as 3D . The 2D scatter plot is the important/common one, where we will primarily find patterns/Clusters and separability of the data. The code snippet for using a scatter plot is as shown below.
plt.scatter(x,y)
When we use scatter from Matplotlib directly we will get a plot similar to the one below. I used Iris dataset to explain simple scatter plot.
plt.scatter(iris['sepal_length'],iris['sepal_width'])plt.xlabel('Sepal length')plt.ylabel('Sepal width')plt.title('Scatter plot on Iris dataset')
Here we can see that all the points are marked on their corresponding position with respective to their values of x and y. Lets tweak around to see if we can get points with different colours.
plt.scatter(iris['sepal_length'],iris['sepal_width'],color=['r','b','g'])plt.xlabel('Sepal length')plt.ylabel('Sepal width')plt.title('Scatter plot on Iris dataset')
This one seems fine! but the colors are assigned to points on basis of how they were present in dataset. Now how it would be if we can color the points as per their class label. Here the class labels are Setosa, Virginica and Veriscolor. This is where Seaborn pops up, with its effective visualization stuffs.
sns.set_style("whitegrid")sns.FacetGrid(iris, hue="species", size=4) \ .map(plt.scatter, "sepal_length", "sepal_width") \ .add_legend()plt.show()
Hurray!! The plot seems a lot cooler now, just simply by visualizing it, we can conclude like setosa flowers are well separated from the other 2 classes and also there are some overlaps between virginica and versicolor. The parameter hue, in the facetGrid decides the color of each datapoints. Here we used Species column(dependent feature/Class) in hue, so that we got this plot colored in this manner.
This makes seaborn a bit more superior than Matplotlib when it comes to visualization. But not to forget that still we are using plt.scatter from Matplotlib, on the map function in seaborn. So seaborn is just making the visual more appealing. For 3d scatter plots, we can use plot.ly to achieve that. But there is a hack that we can try like plotting points between 2 variables and setting the size of points with respective to the third variable where we did analysis of 3 features.
Documentation link of Scatterplot.
Datset used : Iris dataset
We can use scatter plots for 2d with Matplotlib and even for 3D, we can use it from plot.ly. What to do when we have 4d or more than that? This is when Pair plot from seaborn package comes into play.
Lets say we have n number of features in a data, Pair plot will create us a (n x n) figure where the diagonal plots will be histogram plot of the feature corresponding to that row and rest of the plots are the combination of feature from each row in y axis and feature from each column in x axis.
The code snippet for pair plot implemented for Iris dataset is provided below.
sns.set_style("whitegrid");sns.pairplot(iris, hue="species", size=3);plt.show()
By getting a high level overview of plots from pair plot, we can see which two features can well explain/separate the data and then we can use scatter plot between those 2 features to explore further. From the above plot we can conclude like, Petal length and petal width are the 2 features which can separate the data very well.
Since we will be getting n x n plots for n features, pairplot may become complex when we have more number of feature say like 10 or so on. So in such cases, the best bet will be using a dimensionality reduction technique to map data into 2d plane and visualizing it using a 2d scatter plot.
Documentation link of Pairplots.
Datset used : Iris dataset
This is the type of plot that can be used to obtain more of the statistical details about the data. The straight lines at the maximum and minimum are also called as whiskers. Points outside of whiskers will be inferred as an outliers. The box plot gives us a representation of 25th, 50th ,75th quartiles.From box plot we can also see the Interquartile range(IQR) where maximum details of the data will be present. It also gives us a clear overview of outlier points in the data.
Boxplot is available in seaborn library. Lets jump on to the code part. Here x is the variable to be predicted and y is the independent feature. These box plots comes under univariate analysis, which means that we are exploring data only with one variable i.e here we are just checking influence of feature axil_nodes on the class Survival status and not between any two independent features.
sns.boxplot(x='SurvStat',y='axil_nodes',data=hb)
Using the box plot, as mentioned above we can see how much of data is present in 1st quartile and how much points are outliers etc. From the above plot for the class 1 we can see that there are very few/no data is present between median and the 1st quartile. Also there are more number of outlier points for class 1 in feature axil_nodes. Such details about outliers and so on will help us to well prepare the data before sending it to a model, as outlier impacts a lot of Machine learning models.
Documentation link for box plots.
Dataset used: Haberman Dataset.
The violin plots can be inferred as a combination of Box plot at the middle and distribution plots(Kernel Density Estimation ) on both side of the data. This can give us the details of distribution like whether the distribution is mutimodal, Skewness etc. It also give us the useful info like 95% confidence interval. The below image help us grasp some important parts from a violin plot.
Violin plot is also from seaborn package. The code is simple and as follows.
sns.violinplot(x='SurvStat',y='op_yr',data=hb,size=6)
From the above violin plot we can infer that median of both the classes are around 63 and also the maximum number of persons with class 2 has op_yr value as 65 whereas for persons in class1, the maximum value is around 60.The 3rd quartile to median has lesser points than the median to 1st quartile and so on.
Documentation link for violin plot.
Dataset used: Haberman Dataset.
This is one of the best univariate plot to know about the distribution of data. When analyzing effect on dependent variable(output) with respective to a single feature(input), we use distribution plots a lot. It is also readily available in seaborn package. This plot gives us a combination of pdf and histogram in a single figure.
sns.FacetGrid(hb,hue='SurvStat',size=5).map(sns.distplot,'age').add_legend()
From the above plot, we can see that we created a distribution plot on the feature ‘Age’(input feature) and we used different colors for the Survival status(dependent variable/output) as it is the class to be predicted and we can see there is a huge overlap between their PDFs. The sharp block like structures are histograms and the smoothened curve is called Probability density function(PDF). The pdf of a curve can help us to identify the underlying distribution of that feature which is one major takeaway from Data visualization/EDA.
Documentation link for distplot.
Dataset used: Haberman Dataset.
It’s one of my favourite and the great thing about joint plots is, in a single figure we can do both univariate as well as bivariate analysis. The main plot will give us a bivariate analysis, whereas on the top and right side we will get univariate plots of both the variables that were considered. There are variety of option you can choose from, which can be tuned using kind parameter in seaborn’s jointplot function. The one shown below is of kind as KDE( Kernel Density Estimation) and it is represented in a contour diagram, All points with same boundary will have the same value and the colour at a point depends on number of datapoints i.e it will be light color when very few points had that value and will be darker with more points. This is why at center it is darker and will be pale/lighter at the ends for this dataset.
The 2 most important plots we use will be scatter plot for bivariate and distribution plot for univariate and since we are getting both in a single plot as shown below, it will make our work a lot easier.
Documentation Link
Datset used : Iris dataset
This is one of the widely used plot, that we would have saw multiple times not just in data analysis, but wherever there is a trend analysis in many fields. Though it may seem simple it is powerful in analyzing data like sales figure every week, revenue from a product, Number of visitors to a site on each day of a week etc.
The code is pretty straight forward, We will be using bar function from Matplotlib to achieve it. The below code will give you a bar plot, where the position of bars are mentioned by values in x and length/height of the bar as values in y.
plt.bar(x,y)
I will show you a chart that I created as a part of my current work, where as a lead member in projecting retrospective details to my management, I need to specify the alert trend analysis which was done earlier with a simple tabular data. Then by using bar plots for the same was more presentable and easily interpretable by my audience.
a=np.arange(6)w=0.15fig,ax=plt.subplots(figsize=(12,7),edgecolor='k')p1=ax.bar(a,d,w,color='b')p2=ax.bar(a-w,c,w,color='g')p3=ax.bar(a+w,e,w,color='y')ax.set_xticks(a)ax.set_xticklabels(('Apr','May','June','July','Aug','Sep'))ax.set_title('Alert trend')ax.legend((p1[0],p2[0],p3[0]),('A','B','C'))plt.xlabel('Month')plt.ylabel('No of alerts received')#plt.grid()plt.show()
So this way, We can view the data in a cool plot and can convey the details straight forward to others. This plot may be simple and clear but its not much frequently used in Data science applications. I will provide the documentation of Bar plot below, please play around with the several parameters to get plot of your desire.
Documentation Link for Bar plot.
This is the plot that you can see in nook and corners of any sort of analysis between 2 variables. The line plots are nothing but the values on series of datapoints will be connected with straight lines. The plot may seem very simple but it has more number of applications not only in machine learning but in many other areas.
The code is pretty much simple and the plot function in matplotlib does the duty of line graphs pretty well.
plt.plot(x,y)
We call plot multiple lines inside a single figure as shown below where you need to add mutliple plt.plot() commands with each line represening a different color parameter.
The line charts are used right from performing distribution comparision using QQplots till CV tuning using elbow method and analysing performance of a model using AUC curve.
Documentation link
So far we saw some widely employed methods that are used to extract useful information/insight from the data.
We can also use some visualization tools to convey our final information/inference in form of plots to the audience. Lets see a few commonly used ones among them.
Heatmap is one good visualization technique used to compare any 2 variables/features with respective to the values. The heatmap from seaborn library will create a grid like plot along with an optional color bar. We provide a 2D input matrix with certain values on each element to the heatmap and it exactly reproduces the output plot in the same shape as that of input matrix and each tile are colored based on the values provided in each elements of matrix to their corresponding tile.
This can be much useful in cases where there will be a bigger matrix and we want to find which value is higher, lower and so on by simply looking at the different colour tones used. For eg. Weekly performance chart of different companies can be plotted using heatmaps
In Machine learning applications, it can be used in representing Confusion matrix of a model, used in hyperparameter tuning to plot error values between 2 different hyperparameters etc.
seaborn documentation link
Wordcloud is nothing but creating an image that contains all the words in a passage/string with different size, as per the frequency of occurrence in that passage. The word will appear bigger and bolder if it occurs more number of times in a given passage.
Enter the below line in your command prompt to install wordcloud.
pip3 install wordcloud
This is recently used in many place, where by seeing the wordcloud we can conclude like what’s discussed in a paragraph without reading it much. The most repeating word will appear bold and bigger than the least occuring ones.
It can be used a lot with text data analysis like, finding the common topics in a cluster while performing sentiment analysis and SEO optimizations etc.
Documentation link
The Decision tree algorithms are one of the popular non linear model. It build a tree where the condition/feature on each splits will be selected on the basis of information gain or Gini impurity value.
If you want to view a linear model like linear regression you can do it simply using matplotlib/seaborn, whereas to visualize trees, we use a special tool called Graphviz. U can install it using below command as how we install other python packages.
pip3 install graphviz
The Sklearn has a good implementation of a function called export_graphviz which can help us to convert the decision tree model into dot format, which is supported by graphviz tool.
Reference : Sklearn link
This is the method used to visualize the clusters formed when using the hierarchical clustering technique like Agglomerative Clustering.
Here each chain/link between points, means that they fall under same cluster. The dendogram structure may be too much complex when the number of datapoints are large.
Reference : Link on procedure to plot dendogram
Think it is enough for this single blog and there are variety of visualization methods discussed. If there is something which I feel missing, I will try to edit or create a part 2 if there is a need..
Thanks you very much if you read my blog until this conclusion and I am really sorry if I took too much of your precious time!! . Show your love on claps if you found it useful. If you still have 2 more minutes, please leave me a feedback that I can use to improve myself in the upcoming days. This is my first blog ever on Internet and as mentioned earlier all your constructive feedbacks are most welcomed.
“I think it’s very important to have a feedback loop, where you’re constantly thinking about what you’ve done and how you could be doing it better.”– Elon Musk ( My inspiration ;) )
Have a great day, Happy Coding :) !!!
- Sanat
Email ID : [email protected]
Linked In : www.linkedin.com/in/sanatmpa
Edit : Thanks much Applied AI Team for selecting my blog as one of the top 20 special mentioned blog from overall 118 blogs submitted. Link
These below ones helped me a lot for the above blog and would like to honour them by providing reference.
1.) https://dev.to/skotaro/artist-in-matplotlib---something-i-wanted-to-know-before-spending-tremendous-hours-on-googling-how-tos--31oo
2.) https://www.aosabook.org/en/matplotlib.html
3.) https://www.fusioncharts.com/resources/chart-primers/heat-map-chart
4.) Sklearn library.
5.) AppliedAICourse.
6.) Wikipedia.
7.) Imgflip.com for creating meme images. | [
{
"code": null,
"e": 188,
"s": 172,
"text": "Good day Folks,"
},
{
"code": null,
"e": 437,
"s": 188,
"text": "Myself is Sanat currently working in IBM and I’m basically a Data Scientist, who loves to make my hand dirty on playing with a huge amount of data. Let me cut short my boring intro here :P and move towards the topic of the day “Data Visualization”."
},
{
"code": null,
"e": 708,
"s": 437,
"text": "Note : This blog was made keeping in mind that the person reading is just aware of very basics on data visualizations and some topics may be too naive. So please skip the topics that you knew already and enjoy the rest. I am open to all your comments regarding the blog."
},
{
"code": null,
"e": 1661,
"s": 708,
"text": "As we all knew that there is a huge buzz going over the term data, like Big data, Data science, Data Analysts, Data Warehouse,Data mining etc. which emphasize that, In the current era data plays a major role in influencing day to day activities of the mankind. Everyday we are generating more than 2.5 quintillion( 1018) bytes of data(Link) ranging from our Text messages, Images, emails, till data from autonomous cars, IOT devices etc. With such huge amount of data being available on hand, leveraging useful information from this data can help each and every organization very much, for getting a clear insight on several areas like, what can bring a boost for their organization’s revenue, which field needs more focus, how to seek more customer’s attention etc. Machine learning(ML), Data science are some of the interrelated areas of Artificial Intelligence(AI) where this task of learning from data is done in a huge extent on these recent days."
},
{
"code": null,
"e": 2868,
"s": 1661,
"text": "From above intro, now you may be fascinated with the term “Data” and will be planning to make use of these available data much effectively, to get as much useful information as possible. Do you think it is very easy to interpret these collected data? May be No :( . The data will be in raw format and there are several steps that needs to be performed to convert this raw data to an useful information, just like how a goldsmith prepares an ornament by doing several preprocessing steps on raw gold. This is where a Data scientist comes in handy, You throw him/her a raw data, they can narrate you a great story from that, which would not be as easy for others when provided with same data. There will be several stages when those data scientists write their story ( I mean working with the data :P ) like Data acquisition, Data cleaning, Data Visualization, building a model that can be used to predict the future information etc. Among them one key stage is Data Visualization. This is the first and foremost step where they will get a high level statistical overview on how the data is. and some of its attributes like the underlying distribution, presence of outliers, and several more useful features."
},
{
"code": null,
"e": 2936,
"s": 2868,
"text": "“Data is the new oil? No, data is the new soil.” — David McCandless"
},
{
"code": null,
"e": 3421,
"s": 2936,
"text": "Do you think giving you the data of lets say 1 Million points in a table/Database file and asking you to provide your inferences by just seeing the data on that table is feasible? Unless you’re a super human its not possible. This is when we make use of Data visualization, wherein all the data will be transformed into some form of plots and analyzed further from that. As being a human, we are more used to grasp a lot of info from diagrammatic representation than the counterparts."
},
{
"code": null,
"e": 3718,
"s": 3421,
"text": "Kids should learn how to read and create graphics from a very young age. Most kids are natural-born artists, as we humans are a visual species. We should take advantage of that, as graphics and illustrations can be such a powerful weapon for understanding and communicating — Prof. Alberto Cairo,"
},
{
"code": null,
"e": 4179,
"s": 3718,
"text": "Okay ! So since it is said that we need to convert the data from a boring table into an interesting pictorial form like a scatter plot or Bar chart, You may wonder, How can I do it? Do I need to write my own code for that ? NO! Actually we can make use of very good packages from some popular programming languages which are readily available and can make the work pretty much simple with just a single line of code. That’s the power of modern programming :D !"
},
{
"code": null,
"e": 4907,
"s": 4179,
"text": "As a human, we can just visualize anything in either in 2-d or 3-d. But trust me almost of the data that you obtain in real world won’t be this way. As a Machine learning engineer, working with more than 1000-dimensional data is very common. So what can we do in such cases where data is more than 3D ? There are some Dimensionality Reduction(DR) techniques like PCA, TSNE , LDA etc which helps you to convert data from a higher dimension to a 2D or 3D data in order to visualize them. There may be some loss of information with each DR techniques, but only they can help us visualize very high dimensional data on a 2d plot. TSNE is one of the state of the art DR technique employed for visualization of high dimensional data."
},
{
"code": null,
"e": 5344,
"s": 4907,
"text": "From perspective of building models , By visualizing the data we can find the hidden patterns, Explore if there are any clusters within data and we can find if they are linearly separable/too much overlapped etc. From this initial analysis we can easily rule out the models that won’t be suitable for such a data and we will implement only the models that are suitable, without wasting our valuable time and the computational resources."
},
{
"code": null,
"e": 5473,
"s": 5344,
"text": "This part of data visualization is a predominant one in initial Exploratory Data Analysis (EDA) on the field of Data science/ML."
},
{
"code": null,
"e": 6292,
"s": 5473,
"text": "There may be several languages on which we can perform the Data Visualization, but the ones that are much widely used in the field of Data Science are Python & R. So your next question may be, Which one to learn and which one has a better scope ?. The answer is simple! It’s purely your choice but I would recommend Python ;) . ‘R’ is way more statistical language and has several great packages for Data science applications, whereas Python on the other hand is widely used in general purpose programming as well as for Data science and ML related applications. I am pretty comfortable with python and so I will continue the rest of the blog with python codes and also it has several good packages like Scikit,Matplotlib,seaborn etc which helps us a lot. A special thanks to those developers who made our work simple."
},
{
"code": null,
"e": 6855,
"s": 6292,
"text": "As mentioned above, Python has several good packages to plot the data and among them Matplotlib is the most prominent one. Seaborn is also a great package which offers a lot more appealing plot and even it uses matplotlib as its base layer. There are also many similar type of plots available in Pandas when the entire data is stored in a pandas dataframe, we also have a library called plotly and etc. In this blog we are going to discuss about the different types of plots that are under the 2 packages mentioned at the start and let us explore them in detail."
},
{
"code": null,
"e": 6938,
"s": 6855,
"text": "There are overall 3 different layers in the architecture of matplotlib as follows."
},
{
"code": null,
"e": 6988,
"s": 6938,
"text": ") Backend layer.) Artist layer.) Scripting layer."
},
{
"code": null,
"e": 7005,
"s": 6988,
"text": ") Backend layer."
},
{
"code": null,
"e": 7021,
"s": 7005,
"text": ") Artist layer."
},
{
"code": null,
"e": 7040,
"s": 7021,
"text": ") Scripting layer."
},
{
"code": null,
"e": 7055,
"s": 7040,
"text": "Backend layer:"
},
{
"code": null,
"e": 7495,
"s": 7055,
"text": "This is the bottom most layer of a figure which contains implementation of several functions that are required for plotting. There are 3 main classes from the backend layer FigureCanvas ( the layer/Surface on which the figure will be drawn), Renderer (the classn that takes care of the drawing on the surface ) and Event ( to handle the mouse and keyboard events). We don’t work much with the Backend layer as compared to the counterparts."
},
{
"code": null,
"e": 7509,
"s": 7495,
"text": "Artist Layer:"
},
{
"code": null,
"e": 8026,
"s": 7509,
"text": "This is the second/middle most layer in the architecture. It is what does most of the duty on plotting the various functions, like axis which coordinates on how to use the renderer on the Figure canvas. To put it simple, lets consider Paper as the Figure Canvas and Sketch pen as renderer. Then the hand of the painter is the Artist layer which has certain functions, knows how to sketch to get the exact figure. There are several classes available on artist layer and a few important ones are Figure, Axes and Axis."
},
{
"code": null,
"e": 8414,
"s": 8026,
"text": "The 2 images above explain the hierarchy between various classes in the artist layer. Figure is the topmost one and a figure can contain multiple number of axes upon which the plot is done. Moving on, under each axes we can add multiple plots. This provides a lot more additional functionality to improve the plots and this is the place where most of the heavy lifting works takes place."
},
{
"code": null,
"e": 8431,
"s": 8414,
"text": "Scripting layer:"
},
{
"code": null,
"e": 8896,
"s": 8431,
"text": "This is the topmost layer on which majority of our codes will play around. For day to day exploratory works, we almost rely on this scripting layer of matplotlib. Pyplot is the scripting layer that provides almost simlar functionality as that of Matlab in python. The methods in scripting layer, almost automatically takes care of the other layers and all we need to care about is the current state(figure & Subplot). Hence it is also called as stateful interface."
},
{
"code": null,
"e": 8933,
"s": 8896,
"text": "Please visit the link for reference."
},
{
"code": null,
"e": 9038,
"s": 8933,
"text": "Here lets have a short glance on some of the commonly used terms in data visualization using Matplotlib."
},
{
"code": null,
"e": 9212,
"s": 9038,
"text": "P.S: Wherever plt.(Some function) is used, it means that I imported matplotlib.pyplot as plt in my program and sns means that i imported seaborn just for the ease of coding."
},
{
"code": null,
"e": 9265,
"s": 9212,
"text": "import matplotlib.pyplot as pltimport seaborn as sns"
},
{
"code": null,
"e": 9401,
"s": 9265,
"text": "If you don’t have the packages already installed in your system. Please install Python 3 and use the below code on your command prompt."
},
{
"code": null,
"e": 9445,
"s": 9401,
"text": "pip3 install matplotlibpip3 install seaborn"
},
{
"code": null,
"e": 9451,
"s": 9445,
"text": "Axes:"
},
{
"code": null,
"e": 9688,
"s": 9451,
"text": "Axes is the entire area of a single plot in the figure. It is the class that contains several attributes needed to draw a plot such as like adding title, giving labels, selecting bin values for different types of plots on each axes etc."
},
{
"code": null,
"e": 9963,
"s": 9688,
"text": "We can have multiple axes in a single plot, by which we can combine multiple plots into a single figure. For e.g: If we want both PDF and CDF curves in a same figure we can create 2 axes and draw each of them in different axes. Then we can combine them into a single figure."
},
{
"code": null,
"e": 9968,
"s": 9963,
"text": "Link"
},
{
"code": null,
"e": 9974,
"s": 9968,
"text": "Grid:"
},
{
"code": null,
"e": 10239,
"s": 9974,
"text": "When grid is enabled in a plot, a set of horizontal and vertical lines will be added at the background layer of the plot.This can be enabled using plt.grid(). It can be useful for a rough estimation of value at a particular coordinate, just by looking at the plot."
},
{
"code": null,
"e": 10249,
"s": 10239,
"text": "Ref: Link"
},
{
"code": null,
"e": 10257,
"s": 10249,
"text": "Legend:"
},
{
"code": null,
"e": 10524,
"s": 10257,
"text": "Legends are nothing but labeled representation of the different plots available in a figure. i.e when there are multiple plots in a single image(e.g : Iris dataset), Legends will help us to identify the correct name of the different colored plots in a single figure."
},
{
"code": null,
"e": 10534,
"s": 10524,
"text": "Ref: Link"
},
{
"code": null,
"e": 10544,
"s": 10534,
"text": "Subplots:"
},
{
"code": null,
"e": 10883,
"s": 10544,
"text": "When we want 2 or more plots in a single image, we can make use of Subplot in Matplotlib, plt.subplot (xyz). xyz is a 3 digit integer where x-No of rows, y =No of columns, z= index number of that plot. This is one of the most useful feature when we need to compare two or more plots hand to hand instead of having them in separate images."
},
{
"code": null,
"e": 11015,
"s": 10883,
"text": "plt.figure(1,figsize=(30,8))plt.subplot(131) #Code for fig1.plt.subplot(132)#code for fig2plt.subplot(133)#code for fig3.plt.show()"
},
{
"code": null,
"e": 11133,
"s": 11015,
"text": "In addition to Subplot try using gridspec , which can help us split the plots in subplot more effectively and easier."
},
{
"code": null,
"e": 11143,
"s": 11133,
"text": "Ref: Link"
},
{
"code": null,
"e": 11150,
"s": 11143,
"text": "Title:"
},
{
"code": null,
"e": 11197,
"s": 11150,
"text": "We can set a title to a plot using plt.title()"
},
{
"code": null,
"e": 11205,
"s": 11197,
"text": "xlabel:"
},
{
"code": null,
"e": 11261,
"s": 11205,
"text": "plt.xlabel() is the command to set the label for x axis"
},
{
"code": null,
"e": 11269,
"s": 11261,
"text": "ylabel:"
},
{
"code": null,
"e": 11325,
"s": 11269,
"text": "plt.ylabel() is the command to set the label for y axis"
},
{
"code": null,
"e": 11414,
"s": 11325,
"text": "The below image very well explains each and every parts in visualizing data as a figure."
},
{
"code": null,
"e": 11472,
"s": 11414,
"text": "There are different types of analysis as mentioned below."
},
{
"code": null,
"e": 11759,
"s": 11472,
"text": "Univariate : In univariate analysis we will be using a single feature to analyze almost of its properties.Bivariate : When we compare the data between exactly 2 features then its called bivariate analysis.Multivariate: Comparing more than 2 variables is called as Multivariate analysis."
},
{
"code": null,
"e": 11866,
"s": 11759,
"text": "Univariate : In univariate analysis we will be using a single feature to analyze almost of its properties."
},
{
"code": null,
"e": 11966,
"s": 11866,
"text": "Bivariate : When we compare the data between exactly 2 features then its called bivariate analysis."
},
{
"code": null,
"e": 12048,
"s": 11966,
"text": "Multivariate: Comparing more than 2 variables is called as Multivariate analysis."
},
{
"code": null,
"e": 12198,
"s": 12048,
"text": "In the below blog, for each plot I will mark them as (U),(B) & (M) to represent them as Univariate, Bivariate and Multivariate plots correspondingly."
},
{
"code": null,
"e": 12283,
"s": 12198,
"text": "The below are the list of plots that I am going to explain in the subsequent topics."
},
{
"code": null,
"e": 12303,
"s": 12283,
"text": "i) Scatter plot (B)"
},
{
"code": null,
"e": 12321,
"s": 12303,
"text": "ii) Pair plot (M)"
},
{
"code": null,
"e": 12339,
"s": 12321,
"text": "iii) Box plot (U)"
},
{
"code": null,
"e": 12358,
"s": 12339,
"text": "iv) Violin plot(U)"
},
{
"code": null,
"e": 12383,
"s": 12358,
"text": "v) Distribution plot (U)"
},
{
"code": null,
"e": 12407,
"s": 12383,
"text": "vi) Joint plot(U) & (B)"
},
{
"code": null,
"e": 12426,
"s": 12407,
"text": "vii) Bar chart (B)"
},
{
"code": null,
"e": 12445,
"s": 12426,
"text": "viii) Line plot(B)"
},
{
"code": null,
"e": 12953,
"s": 12445,
"text": "As far as Machine learning/Data Science is concerned, one of the most commonly used plot for simple data visualization is scatter plots. This plot gives us a representation of where each points in the entire dataset are present with respect to any 2/3 features(Columns). Scatter plots are available in 2D as well as 3D . The 2D scatter plot is the important/common one, where we will primarily find patterns/Clusters and separability of the data. The code snippet for using a scatter plot is as shown below."
},
{
"code": null,
"e": 12970,
"s": 12953,
"text": "plt.scatter(x,y)"
},
{
"code": null,
"e": 13112,
"s": 12970,
"text": "When we use scatter from Matplotlib directly we will get a plot similar to the one below. I used Iris dataset to explain simple scatter plot."
},
{
"code": null,
"e": 13258,
"s": 13112,
"text": "plt.scatter(iris['sepal_length'],iris['sepal_width'])plt.xlabel('Sepal length')plt.ylabel('Sepal width')plt.title('Scatter plot on Iris dataset')"
},
{
"code": null,
"e": 13451,
"s": 13258,
"text": "Here we can see that all the points are marked on their corresponding position with respective to their values of x and y. Lets tweak around to see if we can get points with different colours."
},
{
"code": null,
"e": 13617,
"s": 13451,
"text": "plt.scatter(iris['sepal_length'],iris['sepal_width'],color=['r','b','g'])plt.xlabel('Sepal length')plt.ylabel('Sepal width')plt.title('Scatter plot on Iris dataset')"
},
{
"code": null,
"e": 13927,
"s": 13617,
"text": "This one seems fine! but the colors are assigned to points on basis of how they were present in dataset. Now how it would be if we can color the points as per their class label. Here the class labels are Setosa, Virginica and Veriscolor. This is where Seaborn pops up, with its effective visualization stuffs."
},
{
"code": null,
"e": 14077,
"s": 13927,
"text": "sns.set_style(\"whitegrid\")sns.FacetGrid(iris, hue=\"species\", size=4) \\ .map(plt.scatter, \"sepal_length\", \"sepal_width\") \\ .add_legend()plt.show()"
},
{
"code": null,
"e": 14481,
"s": 14077,
"text": "Hurray!! The plot seems a lot cooler now, just simply by visualizing it, we can conclude like setosa flowers are well separated from the other 2 classes and also there are some overlaps between virginica and versicolor. The parameter hue, in the facetGrid decides the color of each datapoints. Here we used Species column(dependent feature/Class) in hue, so that we got this plot colored in this manner."
},
{
"code": null,
"e": 14965,
"s": 14481,
"text": "This makes seaborn a bit more superior than Matplotlib when it comes to visualization. But not to forget that still we are using plt.scatter from Matplotlib, on the map function in seaborn. So seaborn is just making the visual more appealing. For 3d scatter plots, we can use plot.ly to achieve that. But there is a hack that we can try like plotting points between 2 variables and setting the size of points with respective to the third variable where we did analysis of 3 features."
},
{
"code": null,
"e": 15000,
"s": 14965,
"text": "Documentation link of Scatterplot."
},
{
"code": null,
"e": 15027,
"s": 15000,
"text": "Datset used : Iris dataset"
},
{
"code": null,
"e": 15227,
"s": 15027,
"text": "We can use scatter plots for 2d with Matplotlib and even for 3D, we can use it from plot.ly. What to do when we have 4d or more than that? This is when Pair plot from seaborn package comes into play."
},
{
"code": null,
"e": 15524,
"s": 15227,
"text": "Lets say we have n number of features in a data, Pair plot will create us a (n x n) figure where the diagonal plots will be histogram plot of the feature corresponding to that row and rest of the plots are the combination of feature from each row in y axis and feature from each column in x axis."
},
{
"code": null,
"e": 15603,
"s": 15524,
"text": "The code snippet for pair plot implemented for Iris dataset is provided below."
},
{
"code": null,
"e": 15683,
"s": 15603,
"text": "sns.set_style(\"whitegrid\");sns.pairplot(iris, hue=\"species\", size=3);plt.show()"
},
{
"code": null,
"e": 16013,
"s": 15683,
"text": "By getting a high level overview of plots from pair plot, we can see which two features can well explain/separate the data and then we can use scatter plot between those 2 features to explore further. From the above plot we can conclude like, Petal length and petal width are the 2 features which can separate the data very well."
},
{
"code": null,
"e": 16304,
"s": 16013,
"text": "Since we will be getting n x n plots for n features, pairplot may become complex when we have more number of feature say like 10 or so on. So in such cases, the best bet will be using a dimensionality reduction technique to map data into 2d plane and visualizing it using a 2d scatter plot."
},
{
"code": null,
"e": 16337,
"s": 16304,
"text": "Documentation link of Pairplots."
},
{
"code": null,
"e": 16364,
"s": 16337,
"text": "Datset used : Iris dataset"
},
{
"code": null,
"e": 16843,
"s": 16364,
"text": "This is the type of plot that can be used to obtain more of the statistical details about the data. The straight lines at the maximum and minimum are also called as whiskers. Points outside of whiskers will be inferred as an outliers. The box plot gives us a representation of 25th, 50th ,75th quartiles.From box plot we can also see the Interquartile range(IQR) where maximum details of the data will be present. It also gives us a clear overview of outlier points in the data."
},
{
"code": null,
"e": 17236,
"s": 16843,
"text": "Boxplot is available in seaborn library. Lets jump on to the code part. Here x is the variable to be predicted and y is the independent feature. These box plots comes under univariate analysis, which means that we are exploring data only with one variable i.e here we are just checking influence of feature axil_nodes on the class Survival status and not between any two independent features."
},
{
"code": null,
"e": 17285,
"s": 17236,
"text": "sns.boxplot(x='SurvStat',y='axil_nodes',data=hb)"
},
{
"code": null,
"e": 17783,
"s": 17285,
"text": "Using the box plot, as mentioned above we can see how much of data is present in 1st quartile and how much points are outliers etc. From the above plot for the class 1 we can see that there are very few/no data is present between median and the 1st quartile. Also there are more number of outlier points for class 1 in feature axil_nodes. Such details about outliers and so on will help us to well prepare the data before sending it to a model, as outlier impacts a lot of Machine learning models."
},
{
"code": null,
"e": 17817,
"s": 17783,
"text": "Documentation link for box plots."
},
{
"code": null,
"e": 17849,
"s": 17817,
"text": "Dataset used: Haberman Dataset."
},
{
"code": null,
"e": 18238,
"s": 17849,
"text": "The violin plots can be inferred as a combination of Box plot at the middle and distribution plots(Kernel Density Estimation ) on both side of the data. This can give us the details of distribution like whether the distribution is mutimodal, Skewness etc. It also give us the useful info like 95% confidence interval. The below image help us grasp some important parts from a violin plot."
},
{
"code": null,
"e": 18315,
"s": 18238,
"text": "Violin plot is also from seaborn package. The code is simple and as follows."
},
{
"code": null,
"e": 18369,
"s": 18315,
"text": "sns.violinplot(x='SurvStat',y='op_yr',data=hb,size=6)"
},
{
"code": null,
"e": 18679,
"s": 18369,
"text": "From the above violin plot we can infer that median of both the classes are around 63 and also the maximum number of persons with class 2 has op_yr value as 65 whereas for persons in class1, the maximum value is around 60.The 3rd quartile to median has lesser points than the median to 1st quartile and so on."
},
{
"code": null,
"e": 18715,
"s": 18679,
"text": "Documentation link for violin plot."
},
{
"code": null,
"e": 18747,
"s": 18715,
"text": "Dataset used: Haberman Dataset."
},
{
"code": null,
"e": 19079,
"s": 18747,
"text": "This is one of the best univariate plot to know about the distribution of data. When analyzing effect on dependent variable(output) with respective to a single feature(input), we use distribution plots a lot. It is also readily available in seaborn package. This plot gives us a combination of pdf and histogram in a single figure."
},
{
"code": null,
"e": 19156,
"s": 19079,
"text": "sns.FacetGrid(hb,hue='SurvStat',size=5).map(sns.distplot,'age').add_legend()"
},
{
"code": null,
"e": 19695,
"s": 19156,
"text": "From the above plot, we can see that we created a distribution plot on the feature ‘Age’(input feature) and we used different colors for the Survival status(dependent variable/output) as it is the class to be predicted and we can see there is a huge overlap between their PDFs. The sharp block like structures are histograms and the smoothened curve is called Probability density function(PDF). The pdf of a curve can help us to identify the underlying distribution of that feature which is one major takeaway from Data visualization/EDA."
},
{
"code": null,
"e": 19728,
"s": 19695,
"text": "Documentation link for distplot."
},
{
"code": null,
"e": 19760,
"s": 19728,
"text": "Dataset used: Haberman Dataset."
},
{
"code": null,
"e": 20594,
"s": 19760,
"text": "It’s one of my favourite and the great thing about joint plots is, in a single figure we can do both univariate as well as bivariate analysis. The main plot will give us a bivariate analysis, whereas on the top and right side we will get univariate plots of both the variables that were considered. There are variety of option you can choose from, which can be tuned using kind parameter in seaborn’s jointplot function. The one shown below is of kind as KDE( Kernel Density Estimation) and it is represented in a contour diagram, All points with same boundary will have the same value and the colour at a point depends on number of datapoints i.e it will be light color when very few points had that value and will be darker with more points. This is why at center it is darker and will be pale/lighter at the ends for this dataset."
},
{
"code": null,
"e": 20799,
"s": 20594,
"text": "The 2 most important plots we use will be scatter plot for bivariate and distribution plot for univariate and since we are getting both in a single plot as shown below, it will make our work a lot easier."
},
{
"code": null,
"e": 20818,
"s": 20799,
"text": "Documentation Link"
},
{
"code": null,
"e": 20845,
"s": 20818,
"text": "Datset used : Iris dataset"
},
{
"code": null,
"e": 21171,
"s": 20845,
"text": "This is one of the widely used plot, that we would have saw multiple times not just in data analysis, but wherever there is a trend analysis in many fields. Though it may seem simple it is powerful in analyzing data like sales figure every week, revenue from a product, Number of visitors to a site on each day of a week etc."
},
{
"code": null,
"e": 21411,
"s": 21171,
"text": "The code is pretty straight forward, We will be using bar function from Matplotlib to achieve it. The below code will give you a bar plot, where the position of bars are mentioned by values in x and length/height of the bar as values in y."
},
{
"code": null,
"e": 21424,
"s": 21411,
"text": "plt.bar(x,y)"
},
{
"code": null,
"e": 21763,
"s": 21424,
"text": "I will show you a chart that I created as a part of my current work, where as a lead member in projecting retrospective details to my management, I need to specify the alert trend analysis which was done earlier with a simple tabular data. Then by using bar plots for the same was more presentable and easily interpretable by my audience."
},
{
"code": null,
"e": 22136,
"s": 21763,
"text": "a=np.arange(6)w=0.15fig,ax=plt.subplots(figsize=(12,7),edgecolor='k')p1=ax.bar(a,d,w,color='b')p2=ax.bar(a-w,c,w,color='g')p3=ax.bar(a+w,e,w,color='y')ax.set_xticks(a)ax.set_xticklabels(('Apr','May','June','July','Aug','Sep'))ax.set_title('Alert trend')ax.legend((p1[0],p2[0],p3[0]),('A','B','C'))plt.xlabel('Month')plt.ylabel('No of alerts received')#plt.grid()plt.show()"
},
{
"code": null,
"e": 22464,
"s": 22136,
"text": "So this way, We can view the data in a cool plot and can convey the details straight forward to others. This plot may be simple and clear but its not much frequently used in Data science applications. I will provide the documentation of Bar plot below, please play around with the several parameters to get plot of your desire."
},
{
"code": null,
"e": 22497,
"s": 22464,
"text": "Documentation Link for Bar plot."
},
{
"code": null,
"e": 22824,
"s": 22497,
"text": "This is the plot that you can see in nook and corners of any sort of analysis between 2 variables. The line plots are nothing but the values on series of datapoints will be connected with straight lines. The plot may seem very simple but it has more number of applications not only in machine learning but in many other areas."
},
{
"code": null,
"e": 22933,
"s": 22824,
"text": "The code is pretty much simple and the plot function in matplotlib does the duty of line graphs pretty well."
},
{
"code": null,
"e": 22947,
"s": 22933,
"text": "plt.plot(x,y)"
},
{
"code": null,
"e": 23120,
"s": 22947,
"text": "We call plot multiple lines inside a single figure as shown below where you need to add mutliple plt.plot() commands with each line represening a different color parameter."
},
{
"code": null,
"e": 23294,
"s": 23120,
"text": "The line charts are used right from performing distribution comparision using QQplots till CV tuning using elbow method and analysing performance of a model using AUC curve."
},
{
"code": null,
"e": 23313,
"s": 23294,
"text": "Documentation link"
},
{
"code": null,
"e": 23423,
"s": 23313,
"text": "So far we saw some widely employed methods that are used to extract useful information/insight from the data."
},
{
"code": null,
"e": 23586,
"s": 23423,
"text": "We can also use some visualization tools to convey our final information/inference in form of plots to the audience. Lets see a few commonly used ones among them."
},
{
"code": null,
"e": 24073,
"s": 23586,
"text": "Heatmap is one good visualization technique used to compare any 2 variables/features with respective to the values. The heatmap from seaborn library will create a grid like plot along with an optional color bar. We provide a 2D input matrix with certain values on each element to the heatmap and it exactly reproduces the output plot in the same shape as that of input matrix and each tile are colored based on the values provided in each elements of matrix to their corresponding tile."
},
{
"code": null,
"e": 24341,
"s": 24073,
"text": "This can be much useful in cases where there will be a bigger matrix and we want to find which value is higher, lower and so on by simply looking at the different colour tones used. For eg. Weekly performance chart of different companies can be plotted using heatmaps"
},
{
"code": null,
"e": 24527,
"s": 24341,
"text": "In Machine learning applications, it can be used in representing Confusion matrix of a model, used in hyperparameter tuning to plot error values between 2 different hyperparameters etc."
},
{
"code": null,
"e": 24554,
"s": 24527,
"text": "seaborn documentation link"
},
{
"code": null,
"e": 24811,
"s": 24554,
"text": "Wordcloud is nothing but creating an image that contains all the words in a passage/string with different size, as per the frequency of occurrence in that passage. The word will appear bigger and bolder if it occurs more number of times in a given passage."
},
{
"code": null,
"e": 24877,
"s": 24811,
"text": "Enter the below line in your command prompt to install wordcloud."
},
{
"code": null,
"e": 24900,
"s": 24877,
"text": "pip3 install wordcloud"
},
{
"code": null,
"e": 25127,
"s": 24900,
"text": "This is recently used in many place, where by seeing the wordcloud we can conclude like what’s discussed in a paragraph without reading it much. The most repeating word will appear bold and bigger than the least occuring ones."
},
{
"code": null,
"e": 25280,
"s": 25127,
"text": "It can be used a lot with text data analysis like, finding the common topics in a cluster while performing sentiment analysis and SEO optimizations etc."
},
{
"code": null,
"e": 25299,
"s": 25280,
"text": "Documentation link"
},
{
"code": null,
"e": 25502,
"s": 25299,
"text": "The Decision tree algorithms are one of the popular non linear model. It build a tree where the condition/feature on each splits will be selected on the basis of information gain or Gini impurity value."
},
{
"code": null,
"e": 25752,
"s": 25502,
"text": "If you want to view a linear model like linear regression you can do it simply using matplotlib/seaborn, whereas to visualize trees, we use a special tool called Graphviz. U can install it using below command as how we install other python packages."
},
{
"code": null,
"e": 25774,
"s": 25752,
"text": "pip3 install graphviz"
},
{
"code": null,
"e": 25956,
"s": 25774,
"text": "The Sklearn has a good implementation of a function called export_graphviz which can help us to convert the decision tree model into dot format, which is supported by graphviz tool."
},
{
"code": null,
"e": 25981,
"s": 25956,
"text": "Reference : Sklearn link"
},
{
"code": null,
"e": 26118,
"s": 25981,
"text": "This is the method used to visualize the clusters formed when using the hierarchical clustering technique like Agglomerative Clustering."
},
{
"code": null,
"e": 26285,
"s": 26118,
"text": "Here each chain/link between points, means that they fall under same cluster. The dendogram structure may be too much complex when the number of datapoints are large."
},
{
"code": null,
"e": 26333,
"s": 26285,
"text": "Reference : Link on procedure to plot dendogram"
},
{
"code": null,
"e": 26534,
"s": 26333,
"text": "Think it is enough for this single blog and there are variety of visualization methods discussed. If there is something which I feel missing, I will try to edit or create a part 2 if there is a need.."
},
{
"code": null,
"e": 26943,
"s": 26534,
"text": "Thanks you very much if you read my blog until this conclusion and I am really sorry if I took too much of your precious time!! . Show your love on claps if you found it useful. If you still have 2 more minutes, please leave me a feedback that I can use to improve myself in the upcoming days. This is my first blog ever on Internet and as mentioned earlier all your constructive feedbacks are most welcomed."
},
{
"code": null,
"e": 27125,
"s": 26943,
"text": "“I think it’s very important to have a feedback loop, where you’re constantly thinking about what you’ve done and how you could be doing it better.”– Elon Musk ( My inspiration ;) )"
},
{
"code": null,
"e": 27163,
"s": 27125,
"text": "Have a great day, Happy Coding :) !!!"
},
{
"code": null,
"e": 27171,
"s": 27163,
"text": "- Sanat"
},
{
"code": null,
"e": 27205,
"s": 27171,
"text": "Email ID : [email protected]"
},
{
"code": null,
"e": 27246,
"s": 27205,
"text": "Linked In : www.linkedin.com/in/sanatmpa"
},
{
"code": null,
"e": 27386,
"s": 27246,
"text": "Edit : Thanks much Applied AI Team for selecting my blog as one of the top 20 special mentioned blog from overall 118 blogs submitted. Link"
},
{
"code": null,
"e": 27492,
"s": 27386,
"text": "These below ones helped me a lot for the above blog and would like to honour them by providing reference."
},
{
"code": null,
"e": 27628,
"s": 27492,
"text": "1.) https://dev.to/skotaro/artist-in-matplotlib---something-i-wanted-to-know-before-spending-tremendous-hours-on-googling-how-tos--31oo"
},
{
"code": null,
"e": 27676,
"s": 27628,
"text": "2.) https://www.aosabook.org/en/matplotlib.html"
},
{
"code": null,
"e": 27748,
"s": 27676,
"text": "3.) https://www.fusioncharts.com/resources/chart-primers/heat-map-chart"
},
{
"code": null,
"e": 27769,
"s": 27748,
"text": "4.) Sklearn library."
},
{
"code": null,
"e": 27790,
"s": 27769,
"text": "5.) AppliedAICourse."
},
{
"code": null,
"e": 27805,
"s": 27790,
"text": "6.) Wikipedia."
}
] |
AngularJS - Scopes | Scope is a special JavaScript object that connects controller with views. Scope contains model data. In controllers, model data is accessed via $scope object.
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
</script>
The following important points are considered in above example −
The $scope is passed as first argument to controller during its constructor definition.
The $scope is passed as first argument to controller during its constructor definition.
The $scope.message and $scope.type are the models which are used in the HTML page.
The $scope.message and $scope.type are the models which are used in the HTML page.
We assign values to models that are reflected in the application module, whose controller is shapeController.
We assign values to models that are reflected in the application module, whose controller is shapeController.
We can define functions in $scope.
We can define functions in $scope.
Scope is controller-specific. If we define nested controllers, then the child controller inherits the scope of its parent controller.
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller";
});
</script>
The following important points are considered in above example −
We assign values to the models in shapeController.
We assign values to the models in shapeController.
We override message in child controller named circleController. When message is used within the module of controller named circleController, the overridden message is used.
We override message in child controller named circleController. When message is used within the module of controller named circleController, the overridden message is used.
The following example shows use of all the above mentioned directives.
<html>
<head>
<title>Angular JS Forms</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "shapeController">
<p>{{message}} <br/> {{type}} </p>
<div ng-controller = "circleController">
<p>{{message}} <br/> {{type}} </p>
</div>
<div ng-controller = "squareController">
<p>{{message}} <br/> {{type}} </p>
</div>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller";
});
mainApp.controller("squareController", function($scope) {
$scope.message = "In square controller";
$scope.type = "Square";
});
</script>
</body>
</html>
Open the file testAngularJS.htm in a web browser and see the result.
{{message}} {{type}}
{{message}} {{type}}
{{message}} {{type}}
16 Lectures
1.5 hours
Anadi Sharma
40 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2858,
"s": 2699,
"text": "Scope is a special JavaScript object that connects controller with views. Scope contains model data. In controllers, model data is accessed via $scope object."
},
{
"code": null,
"e": 3071,
"s": 2858,
"text": "<script>\n var mainApp = angular.module(\"mainApp\", []);\n \n mainApp.controller(\"shapeController\", function($scope) {\n $scope.message = \"In shape controller\";\n $scope.type = \"Shape\";\n });\n</script>"
},
{
"code": null,
"e": 3136,
"s": 3071,
"text": "The following important points are considered in above example −"
},
{
"code": null,
"e": 3224,
"s": 3136,
"text": "The $scope is passed as first argument to controller during its constructor definition."
},
{
"code": null,
"e": 3312,
"s": 3224,
"text": "The $scope is passed as first argument to controller during its constructor definition."
},
{
"code": null,
"e": 3395,
"s": 3312,
"text": "The $scope.message and $scope.type are the models which are used in the HTML page."
},
{
"code": null,
"e": 3478,
"s": 3395,
"text": "The $scope.message and $scope.type are the models which are used in the HTML page."
},
{
"code": null,
"e": 3588,
"s": 3478,
"text": "We assign values to models that are reflected in the application module, whose controller is shapeController."
},
{
"code": null,
"e": 3698,
"s": 3588,
"text": "We assign values to models that are reflected in the application module, whose controller is shapeController."
},
{
"code": null,
"e": 3733,
"s": 3698,
"text": "We can define functions in $scope."
},
{
"code": null,
"e": 3768,
"s": 3733,
"text": "We can define functions in $scope."
},
{
"code": null,
"e": 3902,
"s": 3768,
"text": "Scope is controller-specific. If we define nested controllers, then the child controller inherits the scope of its parent controller."
},
{
"code": null,
"e": 4232,
"s": 3902,
"text": "<script>\n var mainApp = angular.module(\"mainApp\", []);\n \n mainApp.controller(\"shapeController\", function($scope) {\n $scope.message = \"In shape controller\";\n $scope.type = \"Shape\";\n });\n mainApp.controller(\"circleController\", function($scope) {\n $scope.message = \"In circle controller\";\n });\n\t\n</script>"
},
{
"code": null,
"e": 4297,
"s": 4232,
"text": "The following important points are considered in above example −"
},
{
"code": null,
"e": 4348,
"s": 4297,
"text": "We assign values to the models in shapeController."
},
{
"code": null,
"e": 4399,
"s": 4348,
"text": "We assign values to the models in shapeController."
},
{
"code": null,
"e": 4572,
"s": 4399,
"text": "We override message in child controller named circleController. When message is used within the module of controller named circleController, the overridden message is used."
},
{
"code": null,
"e": 4745,
"s": 4572,
"text": "We override message in child controller named circleController. When message is used within the module of controller named circleController, the overridden message is used."
},
{
"code": null,
"e": 4816,
"s": 4745,
"text": "The following example shows use of all the above mentioned directives."
},
{
"code": null,
"e": 6028,
"s": 4816,
"text": "<html>\n <head>\n <title>Angular JS Forms</title>\n </head>\n \n <body>\n <h2>AngularJS Sample Application</h2>\n \n <div ng-app = \"mainApp\" ng-controller = \"shapeController\">\n <p>{{message}} <br/> {{type}} </p>\n \n <div ng-controller = \"circleController\">\n <p>{{message}} <br/> {{type}} </p>\n </div>\n \n <div ng-controller = \"squareController\">\n <p>{{message}} <br/> {{type}} </p>\n </div>\n\t\t\t\n </div>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\">\n </script>\n \n <script>\n var mainApp = angular.module(\"mainApp\", []);\n \n mainApp.controller(\"shapeController\", function($scope) {\n $scope.message = \"In shape controller\";\n $scope.type = \"Shape\";\n });\n mainApp.controller(\"circleController\", function($scope) {\n $scope.message = \"In circle controller\";\n });\n mainApp.controller(\"squareController\", function($scope) {\n $scope.message = \"In square controller\";\n $scope.type = \"Square\";\n });\n\t\t\t\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 6097,
"s": 6028,
"text": "Open the file testAngularJS.htm in a web browser and see the result."
},
{
"code": null,
"e": 6120,
"s": 6097,
"text": "{{message}} {{type}} "
},
{
"code": null,
"e": 6143,
"s": 6120,
"text": "{{message}} {{type}} "
},
{
"code": null,
"e": 6166,
"s": 6143,
"text": "{{message}} {{type}} "
},
{
"code": null,
"e": 6201,
"s": 6166,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6215,
"s": 6201,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6250,
"s": 6215,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6270,
"s": 6250,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6277,
"s": 6270,
"text": " Print"
},
{
"code": null,
"e": 6288,
"s": 6277,
"text": " Add Notes"
}
] |
How to Crack PDF Files in Python? | Python has a rich collection of libraries that are used for multiple purposes like
creating and developing applications, web development, scientific computation, software testing, machine learning, and many more. Python is also used for testing and developing system applications in terms of information security. There are several other libraries and tools available that contain specific scripts used for creating hashes, information gathering, information retrieval, encryption and decryption, web crawling, spoofing, and many more.
In this article, we will create a program that will decrypt a password protected PDF
document. For decryption, we will use a word list that contains some common
passwords and it will help to decrypt the pdf document.
In order to create a pdf cracker, we will import the pikepdf library. Once downloaded, we can include it in our notebook. For reference, we will use this wordlist as an example that contains 5000 common passwords in it.
import pikepdf
from tqdm import tqdm
#Loading password list
password = [line.strip() for line in open("wordlist.txt")]
#iterate over all the passwords
for paswrd in tqdm(password, "Cracking PDF"):
try:
#open PDF file
with pikepdf.open("protected.pdf", password=paswrd) as pdf:
#If password matches then break the loop and print the output
print("Password found:", paswrd)
break
except pikepdf._qpdf.PasswordError as e:
#If password not found then continue
continue
Running the above code will first find the password and then print it as the output. | [
{
"code": null,
"e": 1598,
"s": 1062,
"text": "Python has a rich collection of libraries that are used for multiple purposes like\ncreating and developing applications, web development, scientific computation, software testing, machine learning, and many more. Python is also used for testing and developing system applications in terms of information security. There are several other libraries and tools available that contain specific scripts used for creating hashes, information gathering, information retrieval, encryption and decryption, web crawling, spoofing, and many more."
},
{
"code": null,
"e": 1815,
"s": 1598,
"text": "In this article, we will create a program that will decrypt a password protected PDF\ndocument. For decryption, we will use a word list that contains some common\npasswords and it will help to decrypt the pdf document."
},
{
"code": null,
"e": 2035,
"s": 1815,
"text": "In order to create a pdf cracker, we will import the pikepdf library. Once downloaded, we can include it in our notebook. For reference, we will use this wordlist as an example that contains 5000 common passwords in it."
},
{
"code": null,
"e": 2550,
"s": 2035,
"text": "import pikepdf\nfrom tqdm import tqdm\n\n#Loading password list\npassword = [line.strip() for line in open(\"wordlist.txt\")]\n\n#iterate over all the passwords\nfor paswrd in tqdm(password, \"Cracking PDF\"):\n try:\n #open PDF file\n with pikepdf.open(\"protected.pdf\", password=paswrd) as pdf:\n#If password matches then break the loop and print the output\n print(\"Password found:\", paswrd)\n break\n except pikepdf._qpdf.PasswordError as e:\n #If password not found then continue\n continue"
},
{
"code": null,
"e": 2635,
"s": 2550,
"text": "Running the above code will first find the password and then print it as the output."
}
] |
VBScript DateDiff Function | It is a function that returns the difference between two specified time intervals.
DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]])
Interval, a Required Parameter. It can take the following values −
d − day of the year.
m − month of the year
y − year of the year
yyyy − year
w − weekday
ww − week
q − quarter
h − hour
n − minute
s − second
Interval, a Required Parameter. It can take the following values −
d − day of the year.
d − day of the year.
m − month of the year
m − month of the year
y − year of the year
y − year of the year
yyyy − year
yyyy − year
w − weekday
w − weekday
ww − week
ww − week
q − quarter
q − quarter
h − hour
h − hour
n − minute
n − minute
s − second
s − second
date1 and date2 are Required parameters.
date1 and date2 are Required parameters.
firstdayofweek is Optional. Specifies the first day of the week. It can take the following values −
0 = vbUseSystemDayOfWeek − Use National Language Support (NLS) API setting
1 = vbSunday − Sunday
2 = vbMonday − Monday
3 = vbTuesday − Tuesday
4 = vbWednesday − Wednesday
5 = vbThursday − Thursday
6 = vbFriday − Friday
7 = vbSaturday − Saturday
firstdayofweek is Optional. Specifies the first day of the week. It can take the following values −
0 = vbUseSystemDayOfWeek − Use National Language Support (NLS) API setting
0 = vbUseSystemDayOfWeek − Use National Language Support (NLS) API setting
1 = vbSunday − Sunday
1 = vbSunday − Sunday
2 = vbMonday − Monday
2 = vbMonday − Monday
3 = vbTuesday − Tuesday
3 = vbTuesday − Tuesday
4 = vbWednesday − Wednesday
4 = vbWednesday − Wednesday
5 = vbThursday − Thursday
5 = vbThursday − Thursday
6 = vbFriday − Friday
6 = vbFriday − Friday
7 = vbSaturday − Saturday
7 = vbSaturday − Saturday
firstdayofyear is Optional. Specifies the first day of the year. It can take the following values −
0 = vbUseSystem − Use National Language Support (NLS) API setting
1 = vbFirstJan1 − Start with the week in which January 1 occurs (default)
2 = vbFirstFourDays − Start with the week that has at least four days in the new year
3 = vbFirstFullWeek − Start with the first full week of the new year
firstdayofyear is Optional. Specifies the first day of the year. It can take the following values −
0 = vbUseSystem − Use National Language Support (NLS) API setting
0 = vbUseSystem − Use National Language Support (NLS) API setting
1 = vbFirstJan1 − Start with the week in which January 1 occurs (default)
1 = vbFirstJan1 − Start with the week in which January 1 occurs (default)
2 = vbFirstFourDays − Start with the week that has at least four days in the new year
2 = vbFirstFourDays − Start with the week that has at least four days in the new year
3 = vbFirstFullWeek − Start with the first full week of the new year
3 = vbFirstFullWeek − Start with the first full week of the new year
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
fromDate = "01-Jan-09 00:00:00"
toDate = "01-Jan-10 23:59:00"
document.write("Line 1 : " &DateDiff("yyyy",fromDate,toDate) & "<br />")
document.write("Line 2 : " &DateDiff("q",fromDate,toDate) & "<br />")
document.write("Line 3 : " &DateDiff("m",fromDate,toDate) & "<br />")
document.write("Line 4 : " &DateDiff("y",fromDate,toDate) & "<br />")
document.write("Line 5 : " &DateDiff("d",fromDate,toDate) & "<br />")
document.write("Line 6 : " &DateDiff("w",fromDate,toDate) & "<br />")
document.write("Line 7 : " &DateDiff("ww",fromDate,toDate)& "<br />")
document.write("Line 8 : " &DateDiff("h",fromDate,toDate) & "<br />")
document.write("Line 9 : " &DateDiff("n",fromDate,toDate) & "<br />")
document.write("Line 10 : "&DateDiff("s",fromDate,toDate) & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 : 1
Line 2 : 4
Line 3 : 12
Line 4 : 365
Line 5 : 365
Line 6 : 52
Line 7 : 52
Line 8 : 8783
Line 9 : 527039
Line 10 : 31622340
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2163,
"s": 2080,
"text": "It is a function that returns the difference between two specified time intervals."
},
{
"code": null,
"e": 2235,
"s": 2163,
"text": "DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]]) \n"
},
{
"code": null,
"e": 2446,
"s": 2235,
"text": "Interval, a Required Parameter. It can take the following values −\n\nd − day of the year.\nm − month of the year\ny − year of the year\nyyyy − year\nw − weekday\nww − week\nq − quarter\nh − hour\nn − minute\ns − second\n\n"
},
{
"code": null,
"e": 2513,
"s": 2446,
"text": "Interval, a Required Parameter. It can take the following values −"
},
{
"code": null,
"e": 2534,
"s": 2513,
"text": "d − day of the year."
},
{
"code": null,
"e": 2555,
"s": 2534,
"text": "d − day of the year."
},
{
"code": null,
"e": 2577,
"s": 2555,
"text": "m − month of the year"
},
{
"code": null,
"e": 2599,
"s": 2577,
"text": "m − month of the year"
},
{
"code": null,
"e": 2620,
"s": 2599,
"text": "y − year of the year"
},
{
"code": null,
"e": 2641,
"s": 2620,
"text": "y − year of the year"
},
{
"code": null,
"e": 2653,
"s": 2641,
"text": "yyyy − year"
},
{
"code": null,
"e": 2665,
"s": 2653,
"text": "yyyy − year"
},
{
"code": null,
"e": 2677,
"s": 2665,
"text": "w − weekday"
},
{
"code": null,
"e": 2689,
"s": 2677,
"text": "w − weekday"
},
{
"code": null,
"e": 2699,
"s": 2689,
"text": "ww − week"
},
{
"code": null,
"e": 2709,
"s": 2699,
"text": "ww − week"
},
{
"code": null,
"e": 2721,
"s": 2709,
"text": "q − quarter"
},
{
"code": null,
"e": 2733,
"s": 2721,
"text": "q − quarter"
},
{
"code": null,
"e": 2742,
"s": 2733,
"text": "h − hour"
},
{
"code": null,
"e": 2751,
"s": 2742,
"text": "h − hour"
},
{
"code": null,
"e": 2762,
"s": 2751,
"text": "n − minute"
},
{
"code": null,
"e": 2773,
"s": 2762,
"text": "n − minute"
},
{
"code": null,
"e": 2784,
"s": 2773,
"text": "s − second"
},
{
"code": null,
"e": 2795,
"s": 2784,
"text": "s − second"
},
{
"code": null,
"e": 2836,
"s": 2795,
"text": "date1 and date2 are Required parameters."
},
{
"code": null,
"e": 2877,
"s": 2836,
"text": "date1 and date2 are Required parameters."
},
{
"code": null,
"e": 3226,
"s": 2877,
"text": "firstdayofweek is Optional. Specifies the first day of the week. It can take the following values −\n\n0 = vbUseSystemDayOfWeek − Use National Language Support (NLS) API setting\n1 = vbSunday − Sunday \n2 = vbMonday − Monday\n3 = vbTuesday − Tuesday\n4 = vbWednesday − Wednesday\n5 = vbThursday − Thursday\n6 = vbFriday − Friday\n7 = vbSaturday − Saturday\n\n"
},
{
"code": null,
"e": 3326,
"s": 3226,
"text": "firstdayofweek is Optional. Specifies the first day of the week. It can take the following values −"
},
{
"code": null,
"e": 3401,
"s": 3326,
"text": "0 = vbUseSystemDayOfWeek − Use National Language Support (NLS) API setting"
},
{
"code": null,
"e": 3476,
"s": 3401,
"text": "0 = vbUseSystemDayOfWeek − Use National Language Support (NLS) API setting"
},
{
"code": null,
"e": 3499,
"s": 3476,
"text": "1 = vbSunday − Sunday "
},
{
"code": null,
"e": 3522,
"s": 3499,
"text": "1 = vbSunday − Sunday "
},
{
"code": null,
"e": 3544,
"s": 3522,
"text": "2 = vbMonday − Monday"
},
{
"code": null,
"e": 3566,
"s": 3544,
"text": "2 = vbMonday − Monday"
},
{
"code": null,
"e": 3590,
"s": 3566,
"text": "3 = vbTuesday − Tuesday"
},
{
"code": null,
"e": 3614,
"s": 3590,
"text": "3 = vbTuesday − Tuesday"
},
{
"code": null,
"e": 3642,
"s": 3614,
"text": "4 = vbWednesday − Wednesday"
},
{
"code": null,
"e": 3670,
"s": 3642,
"text": "4 = vbWednesday − Wednesday"
},
{
"code": null,
"e": 3696,
"s": 3670,
"text": "5 = vbThursday − Thursday"
},
{
"code": null,
"e": 3722,
"s": 3696,
"text": "5 = vbThursday − Thursday"
},
{
"code": null,
"e": 3744,
"s": 3722,
"text": "6 = vbFriday − Friday"
},
{
"code": null,
"e": 3766,
"s": 3744,
"text": "6 = vbFriday − Friday"
},
{
"code": null,
"e": 3792,
"s": 3766,
"text": "7 = vbSaturday − Saturday"
},
{
"code": null,
"e": 3818,
"s": 3792,
"text": "7 = vbSaturday − Saturday"
},
{
"code": null,
"e": 4216,
"s": 3818,
"text": "firstdayofyear is Optional. Specifies the first day of the year. It can take the following values −\n\n0 = vbUseSystem − Use National Language Support (NLS) API setting\n1 = vbFirstJan1 − Start with the week in which January 1 occurs (default)\n2 = vbFirstFourDays − Start with the week that has at least four days in the new year\n3 = vbFirstFullWeek − Start with the first full week of the new year\n\n"
},
{
"code": null,
"e": 4316,
"s": 4216,
"text": "firstdayofyear is Optional. Specifies the first day of the year. It can take the following values −"
},
{
"code": null,
"e": 4382,
"s": 4316,
"text": "0 = vbUseSystem − Use National Language Support (NLS) API setting"
},
{
"code": null,
"e": 4448,
"s": 4382,
"text": "0 = vbUseSystem − Use National Language Support (NLS) API setting"
},
{
"code": null,
"e": 4522,
"s": 4448,
"text": "1 = vbFirstJan1 − Start with the week in which January 1 occurs (default)"
},
{
"code": null,
"e": 4596,
"s": 4522,
"text": "1 = vbFirstJan1 − Start with the week in which January 1 occurs (default)"
},
{
"code": null,
"e": 4682,
"s": 4596,
"text": "2 = vbFirstFourDays − Start with the week that has at least four days in the new year"
},
{
"code": null,
"e": 4768,
"s": 4682,
"text": "2 = vbFirstFourDays − Start with the week that has at least four days in the new year"
},
{
"code": null,
"e": 4837,
"s": 4768,
"text": "3 = vbFirstFullWeek − Start with the first full week of the new year"
},
{
"code": null,
"e": 4906,
"s": 4837,
"text": "3 = vbFirstFullWeek − Start with the first full week of the new year"
},
{
"code": null,
"e": 5948,
"s": 4906,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n fromDate = \"01-Jan-09 00:00:00\"\n toDate = \"01-Jan-10 23:59:00\"\n document.write(\"Line 1 : \" &DateDiff(\"yyyy\",fromDate,toDate) & \"<br />\")\n document.write(\"Line 2 : \" &DateDiff(\"q\",fromDate,toDate) & \"<br />\")\n \n document.write(\"Line 3 : \" &DateDiff(\"m\",fromDate,toDate) & \"<br />\")\n document.write(\"Line 4 : \" &DateDiff(\"y\",fromDate,toDate) & \"<br />\")\n \n document.write(\"Line 5 : \" &DateDiff(\"d\",fromDate,toDate) & \"<br />\")\n document.write(\"Line 6 : \" &DateDiff(\"w\",fromDate,toDate) & \"<br />\")\n \n document.write(\"Line 7 : \" &DateDiff(\"ww\",fromDate,toDate)& \"<br />\")\n document.write(\"Line 8 : \" &DateDiff(\"h\",fromDate,toDate) & \"<br />\")\n \n document.write(\"Line 9 : \" &DateDiff(\"n\",fromDate,toDate) & \"<br />\")\n document.write(\"Line 10 : \"&DateDiff(\"s\",fromDate,toDate) & \"<br />\")\n\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 6069,
"s": 5948,
"text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −"
},
{
"code": null,
"e": 6203,
"s": 6069,
"text": "Line 1 : 1\nLine 2 : 4\nLine 3 : 12\nLine 4 : 365\nLine 5 : 365\nLine 6 : 52\nLine 7 : 52\nLine 8 : 8783\nLine 9 : 527039\nLine 10 : 31622340\n"
},
{
"code": null,
"e": 6236,
"s": 6203,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6253,
"s": 6236,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6260,
"s": 6253,
"text": " Print"
},
{
"code": null,
"e": 6271,
"s": 6260,
"text": " Add Notes"
}
] |
Calculate the sum of all columns in a 2D NumPy array - GeeksforGeeks | 21 Jul, 2021
Let us see how to calculate the sum of all the columns in a 2D NumPy array.Method 1 : Using a nested loop to access the array elements column-wise and then storing their sum in a variable and then printing it.Example 1:
Python3
# importing required librariesimport numpy # explicit function to compute column wise sumdef colsum(arr, n, m): for i in range(n): su = 0; for j in range(m): su += arr[j][i] print(su, end = " ") # creating the 2D ArrayTwoDList = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint("2D Array:")print(TwoDArray) # printing the sum of each columnprint("\nColumn-wise Sum:")colsum(TwoDArray, len(TwoDArray[0]), len(TwoDArray))
Output :
2D Array:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Column-wise Sum:
22 26 30
Example 2 :
Python3
# importing required librariesimport numpy # explicit function to compute column wise sumdef colsum(arr, n, m): for i in range(n): su = 0; for j in range(m): su += arr[j][i] print(su, end = " ") # creating the 2D ArrayTwoDList = [[1.2, 2.3], [3.4, 4.5]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint("2D Array:")print(TwoDArray) # printing the sum of each columnprint("\nColumn-wise Sum:")colsum(TwoDArray, len(TwoDArray[0]), len(TwoDArray))
Output :
2D Array:
[[1.2 2.3]
[3.4 4.5]]
Column-wise Sum:
4.6 6.8
Method 2: Using the sum() function in NumPy, numpy.sum(arr, axis, dtype, out) function returns the sum of array elements over the specified axis. To compute the sum of all columns the axis argument should be 0 in sum() function.Example 1 :
Python3
# importing required librariesimport numpy # creating the 2D ArrayTwoDList = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint("2D Array:")print(TwoDArray) # printing the sum of each columnprint("\nColumn-wise Sum:")print(numpy.sum(TwoDArray, axis = 0))
Output :
2D Array:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Column-wise Sum:
22 26 30
Example 2 :
Python3
# importing required librariesimport numpy # creating the 2D ArrayTwoDList =[[1.2, 2.3], [3.4, 4.5]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint("2D Array:")print(TwoDArray) # printing the sum of each columnprint("\nColumn-wise Sum:")print(*numpy.sum(TwoDArray, axis = 0))
Output :
2D Array:
[[1.2 2.3]
[3.4 4.5]]
Column-wise Sum:
4.6 6.8
adnanirshad158
Python numpy-arrayManipulation
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25681,
"s": 25653,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 25903,
"s": 25681,
"text": "Let us see how to calculate the sum of all the columns in a 2D NumPy array.Method 1 : Using a nested loop to access the array elements column-wise and then storing their sum in a variable and then printing it.Example 1: "
},
{
"code": null,
"e": 25911,
"s": 25903,
"text": "Python3"
},
{
"code": "# importing required librariesimport numpy # explicit function to compute column wise sumdef colsum(arr, n, m): for i in range(n): su = 0; for j in range(m): su += arr[j][i] print(su, end = \" \") # creating the 2D ArrayTwoDList = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint(\"2D Array:\")print(TwoDArray) # printing the sum of each columnprint(\"\\nColumn-wise Sum:\")colsum(TwoDArray, len(TwoDArray[0]), len(TwoDArray))",
"e": 26443,
"s": 25911,
"text": null
},
{
"code": null,
"e": 26454,
"s": 26443,
"text": "Output : "
},
{
"code": null,
"e": 26541,
"s": 26454,
"text": "2D Array:\n[[ 1 2 3]\n [ 4 5 6]\n [ 7 8 9]\n [10 11 12]]\n\nColumn-wise Sum:\n22 26 30 "
},
{
"code": null,
"e": 26555,
"s": 26541,
"text": "Example 2 : "
},
{
"code": null,
"e": 26563,
"s": 26555,
"text": "Python3"
},
{
"code": "# importing required librariesimport numpy # explicit function to compute column wise sumdef colsum(arr, n, m): for i in range(n): su = 0; for j in range(m): su += arr[j][i] print(su, end = \" \") # creating the 2D ArrayTwoDList = [[1.2, 2.3], [3.4, 4.5]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint(\"2D Array:\")print(TwoDArray) # printing the sum of each columnprint(\"\\nColumn-wise Sum:\")colsum(TwoDArray, len(TwoDArray[0]), len(TwoDArray))",
"e": 27061,
"s": 26563,
"text": null
},
{
"code": null,
"e": 27072,
"s": 27061,
"text": "Output : "
},
{
"code": null,
"e": 27132,
"s": 27072,
"text": "2D Array:\n[[1.2 2.3]\n [3.4 4.5]]\n\nColumn-wise Sum:\n4.6 6.8 "
},
{
"code": null,
"e": 27374,
"s": 27132,
"text": "Method 2: Using the sum() function in NumPy, numpy.sum(arr, axis, dtype, out) function returns the sum of array elements over the specified axis. To compute the sum of all columns the axis argument should be 0 in sum() function.Example 1 : "
},
{
"code": null,
"e": 27382,
"s": 27374,
"text": "Python3"
},
{
"code": "# importing required librariesimport numpy # creating the 2D ArrayTwoDList = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint(\"2D Array:\")print(TwoDArray) # printing the sum of each columnprint(\"\\nColumn-wise Sum:\")print(numpy.sum(TwoDArray, axis = 0))",
"e": 27709,
"s": 27382,
"text": null
},
{
"code": null,
"e": 27720,
"s": 27709,
"text": "Output : "
},
{
"code": null,
"e": 27806,
"s": 27720,
"text": "2D Array:\n[[ 1 2 3]\n [ 4 5 6]\n [ 7 8 9]\n [10 11 12]]\n\nColumn-wise Sum:\n22 26 30"
},
{
"code": null,
"e": 27820,
"s": 27806,
"text": "Example 2 : "
},
{
"code": null,
"e": 27828,
"s": 27820,
"text": "Python3"
},
{
"code": "# importing required librariesimport numpy # creating the 2D ArrayTwoDList =[[1.2, 2.3], [3.4, 4.5]]TwoDArray = numpy.array(TwoDList) # displaying the 2D Arrayprint(\"2D Array:\")print(TwoDArray) # printing the sum of each columnprint(\"\\nColumn-wise Sum:\")print(*numpy.sum(TwoDArray, axis = 0))",
"e": 28121,
"s": 27828,
"text": null
},
{
"code": null,
"e": 28132,
"s": 28121,
"text": "Output : "
},
{
"code": null,
"e": 28191,
"s": 28132,
"text": "2D Array:\n[[1.2 2.3]\n [3.4 4.5]]\n\nColumn-wise Sum:\n4.6 6.8"
},
{
"code": null,
"e": 28208,
"s": 28193,
"text": "adnanirshad158"
},
{
"code": null,
"e": 28239,
"s": 28208,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 28274,
"s": 28239,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 28287,
"s": 28274,
"text": "Python-numpy"
},
{
"code": null,
"e": 28294,
"s": 28287,
"text": "Python"
},
{
"code": null,
"e": 28392,
"s": 28294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28410,
"s": 28392,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28445,
"s": 28410,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28477,
"s": 28445,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28499,
"s": 28477,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28541,
"s": 28499,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28571,
"s": 28541,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28597,
"s": 28571,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28641,
"s": 28597,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28670,
"s": 28641,
"text": "*args and **kwargs in Python"
}
] |
Explain the significance of <head> and <body> tag in HTML - GeeksforGeeks | 01 Sep, 2021
The HTML <head> and <body> tags are the two most commonly used tags in HTML. It is very rare to find an industry-level website that does not use the <head> and <body> tag in its pages. In this article, we are going to learn the significance of these two tags in an HTML document.
Significance of HTML <head> tag: The head tag in HTML is used to contain the metadata or information related to the document. It holds some of the most important tags like <title> , <meta> , and <link>.
From browser perspective:
In HTML 5 it is not mandatory to include a <head> tag inside the HTML document but in previous versions(4.0.1) it was mandatory to include it.
The tags like <title>, <meta> or <link> which are generally contained inside head will also work fine without the <head> tag or outside the <head> tag.
From a development perspective:
From the developer’s perspective, it is good to include the <head> tag inside the document because this syntax is widely used and it also gives a good structure to the document. Later this will help us to interact with the DOM elements in a structured way.
Significance of HTML <body> tag: The HTML body tag is the last child of the <html> tag. It is used to contain the main content of the HTML document. It holds everything from the heading, paragraphs to the unique div containers reside inside the <body> tag.
From browser perspective:
In HTML 5 it is not mandatory to include a <body> tag inside the HTML document but in previous versions(4.0.1) it was mandatory to include it.
The tags like <div>, <p> or <a> which are generally contained inside body will also work fine without the <body> tag or outside the <body> tag.
Despite being not mandatory, the <body> tag have some attributes like ‘background’, ‘bgcolor’ , ‘a’ , ‘link’ etc.
From a development perspective: From the developer’s perspective, it is good to include the <body> tag inside the document. This syntax is widely used and it also gives a good structure to the document. Later this will help us to interact with the DOM elements in a structured way.
Example 1: The following code is without the <head> and <body> tag.
HTML
<!DOCTYPE html><html> <p> Significance of 'head' and 'body' tag in HTML : Geeksforgeeks </p> <title>Tutorial</title></html>
Output:
Without head and body tags
Example 2: The following code adds the <head> and <body> tag to the document. The output in the last will be the same even if <head> and<body> tags are included but it gives a better structure to the code and a better perspective of understanding.
HTML
<!DOCTYPE html><html> <head> <title>Tutorial</title></head> <body> <p> Significance of 'head' and 'body' tag in HTML : Geeksforgeeks </p></body> </html>
Output:
With the <head> and <body> tags
As we can see clearly that the output has not changed. But the code became easily understandable for us as the convention is followed properly.
Example 3: The following code uses the attributes of the <body> tag. In this example, we are going to use the ‘bgcolor‘ attribute of the <body> tag. It will change the background color of the entire document. Without the <body> tag, we are going to lose more such attributes like <alink>, <link>, etc.
HTML
<!DOCTYPE html><html> <head> <title>Tutorial</title> <link rel="stylesheet" href="styles.css"></head> <body bgcolor="black"> <h1> Significance of 'head' and 'body' tag in HTML : Geeksforgeeks </h1></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26139,
"s": 26111,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 26419,
"s": 26139,
"text": "The HTML <head> and <body> tags are the two most commonly used tags in HTML. It is very rare to find an industry-level website that does not use the <head> and <body> tag in its pages. In this article, we are going to learn the significance of these two tags in an HTML document."
},
{
"code": null,
"e": 26622,
"s": 26419,
"text": "Significance of HTML <head> tag: The head tag in HTML is used to contain the metadata or information related to the document. It holds some of the most important tags like <title> , <meta> , and <link>."
},
{
"code": null,
"e": 26648,
"s": 26622,
"text": "From browser perspective:"
},
{
"code": null,
"e": 26791,
"s": 26648,
"text": "In HTML 5 it is not mandatory to include a <head> tag inside the HTML document but in previous versions(4.0.1) it was mandatory to include it."
},
{
"code": null,
"e": 26943,
"s": 26791,
"text": "The tags like <title>, <meta> or <link> which are generally contained inside head will also work fine without the <head> tag or outside the <head> tag."
},
{
"code": null,
"e": 26975,
"s": 26943,
"text": "From a development perspective:"
},
{
"code": null,
"e": 27232,
"s": 26975,
"text": "From the developer’s perspective, it is good to include the <head> tag inside the document because this syntax is widely used and it also gives a good structure to the document. Later this will help us to interact with the DOM elements in a structured way."
},
{
"code": null,
"e": 27489,
"s": 27232,
"text": "Significance of HTML <body> tag: The HTML body tag is the last child of the <html> tag. It is used to contain the main content of the HTML document. It holds everything from the heading, paragraphs to the unique div containers reside inside the <body> tag."
},
{
"code": null,
"e": 27515,
"s": 27489,
"text": "From browser perspective:"
},
{
"code": null,
"e": 27658,
"s": 27515,
"text": "In HTML 5 it is not mandatory to include a <body> tag inside the HTML document but in previous versions(4.0.1) it was mandatory to include it."
},
{
"code": null,
"e": 27802,
"s": 27658,
"text": "The tags like <div>, <p> or <a> which are generally contained inside body will also work fine without the <body> tag or outside the <body> tag."
},
{
"code": null,
"e": 27916,
"s": 27802,
"text": "Despite being not mandatory, the <body> tag have some attributes like ‘background’, ‘bgcolor’ , ‘a’ , ‘link’ etc."
},
{
"code": null,
"e": 28198,
"s": 27916,
"text": "From a development perspective: From the developer’s perspective, it is good to include the <body> tag inside the document. This syntax is widely used and it also gives a good structure to the document. Later this will help us to interact with the DOM elements in a structured way."
},
{
"code": null,
"e": 28266,
"s": 28198,
"text": "Example 1: The following code is without the <head> and <body> tag."
},
{
"code": null,
"e": 28271,
"s": 28266,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <p> Significance of 'head' and 'body' tag in HTML : Geeksforgeeks </p> <title>Tutorial</title></html>",
"e": 28421,
"s": 28271,
"text": null
},
{
"code": null,
"e": 28429,
"s": 28421,
"text": "Output:"
},
{
"code": null,
"e": 28456,
"s": 28429,
"text": "Without head and body tags"
},
{
"code": null,
"e": 28705,
"s": 28456,
"text": "Example 2: The following code adds the <head> and <body> tag to the document. The output in the last will be the same even if <head> and<body> tags are included but it gives a better structure to the code and a better perspective of understanding."
},
{
"code": null,
"e": 28710,
"s": 28705,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Tutorial</title></head> <body> <p> Significance of 'head' and 'body' tag in HTML : Geeksforgeeks </p></body> </html>",
"e": 28889,
"s": 28710,
"text": null
},
{
"code": null,
"e": 28897,
"s": 28889,
"text": "Output:"
},
{
"code": null,
"e": 28929,
"s": 28897,
"text": "With the <head> and <body> tags"
},
{
"code": null,
"e": 29073,
"s": 28929,
"text": "As we can see clearly that the output has not changed. But the code became easily understandable for us as the convention is followed properly."
},
{
"code": null,
"e": 29375,
"s": 29073,
"text": "Example 3: The following code uses the attributes of the <body> tag. In this example, we are going to use the ‘bgcolor‘ attribute of the <body> tag. It will change the background color of the entire document. Without the <body> tag, we are going to lose more such attributes like <alink>, <link>, etc."
},
{
"code": null,
"e": 29380,
"s": 29375,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Tutorial</title> <link rel=\"stylesheet\" href=\"styles.css\"></head> <body bgcolor=\"black\"> <h1> Significance of 'head' and 'body' tag in HTML : Geeksforgeeks </h1></body> </html>",
"e": 29623,
"s": 29380,
"text": null
},
{
"code": null,
"e": 29631,
"s": 29623,
"text": "Output:"
},
{
"code": null,
"e": 29768,
"s": 29631,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29783,
"s": 29768,
"text": "HTML-Questions"
},
{
"code": null,
"e": 29793,
"s": 29783,
"text": "HTML-Tags"
},
{
"code": null,
"e": 29800,
"s": 29793,
"text": "Picked"
},
{
"code": null,
"e": 29805,
"s": 29800,
"text": "HTML"
},
{
"code": null,
"e": 29822,
"s": 29805,
"text": "Web Technologies"
},
{
"code": null,
"e": 29827,
"s": 29822,
"text": "HTML"
},
{
"code": null,
"e": 29925,
"s": 29827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29949,
"s": 29925,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29990,
"s": 29949,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 30027,
"s": 29990,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30056,
"s": 30027,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30076,
"s": 30056,
"text": "Angular File Upload"
},
{
"code": null,
"e": 30116,
"s": 30076,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30149,
"s": 30116,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30194,
"s": 30149,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30237,
"s": 30194,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Arithmetic Aptitude 4 - GeeksforGeeks | 16 May, 2019
The required numbers are 27, 36, 45......450.
This is an A.P. with a = 27 and d = 9
Let it has n terms.
Then Tn = 450 = 27 + (n-1) x9
∴ 450 = 27+ 9n - 9
∴ 9n = 432
∴ n = 48
3, 9, 27, 81..............531441 form a G.P.
with a = 3 and r = 9/3 = 3
Let the number of terms be n
Then 3 x 3n-1 = 531441
∴ 3n = 312
∴ n = 12
Given series is a G. P. with a = 7, r = 7 and n = 6
∴ Sn = a(rn-1) / (r-1)
∴ Sn = 7(76-1) / 6
Sn = = 137256
Let the numbers be 2X and 9X
Then their H.C.F. is X, so X = 19
∴ Numbers are (2x19 and 9x19) i.e. 38 and 171
Let the no. of Rs. 500 note be X
Then the no. of Rs. 1000 note = 90 – X
∴ 500X + 1000(90 – X) = 71000
∴ 500X + 90000 – 1000X = 71000
∴ 500X = 19000
∴ X = 38
Let the numbers be x, x+2, x+4 and x+6
Then (x + x + 2 + x + 4 + x + 6)/4 = 12
∴ 4x + 12 = 48
∴ x = 9
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
Hash Functions and list/types of Hash functions
How to Replace Values in a List in Python?
How to Concat Two Columns Into One With the Existing Column Name in MySQL?
Spring - REST Controller
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python? | [
{
"code": null,
"e": 28965,
"s": 28937,
"text": "\n16 May, 2019"
},
{
"code": null,
"e": 29144,
"s": 28965,
"text": "The required numbers are 27, 36, 45......450.\n\nThis is an A.P. with a = 27 and d = 9\n\nLet it has n terms.\n\nThen Tn = 450 = 27 + (n-1) x9\n\n∴ 450 = 27+ 9n - 9\n\n∴ 9n = 432\n\n∴ n = 48"
},
{
"code": null,
"e": 29246,
"s": 29144,
"text": "3, 9, 27, 81..............531441 form a G.P. \nwith a = 3 and r = 9/3 = 3\nLet the number of terms be n"
},
{
"code": null,
"e": 29289,
"s": 29246,
"text": "Then 3 x 3n-1 = 531441\n∴ 3n = 312\n∴ n = 12"
},
{
"code": null,
"e": 29402,
"s": 29289,
"text": "Given series is a G. P. with a = 7, r = 7 and n = 6\n\n∴ Sn = a(rn-1) / (r-1)\n\n∴ Sn = 7(76-1) / 6\n\n Sn = = 137256"
},
{
"code": null,
"e": 29511,
"s": 29402,
"text": "Let the numbers be 2X and 9X\nThen their H.C.F. is X, so X = 19\n∴ Numbers are (2x19 and 9x19) i.e. 38 and 171"
},
{
"code": null,
"e": 29668,
"s": 29511,
"text": "Let the no. of Rs. 500 note be X\nThen the no. of Rs. 1000 note = 90 – X\n∴ 500X + 1000(90 – X) = 71000\n∴ 500X + 90000 – 1000X = 71000\n∴ 500X = 19000\n∴ X = 38"
},
{
"code": null,
"e": 29772,
"s": 29668,
"text": "Let the numbers be x, x+2, x+4 and x+6\nThen (x + x + 2 + x + 4 + x + 6)/4 = 12\n∴ 4x + 12 = 48\n∴ x = 9 "
},
{
"code": null,
"e": 29870,
"s": 29772,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29923,
"s": 29870,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29985,
"s": 29923,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 30065,
"s": 29985,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 30106,
"s": 30065,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30154,
"s": 30106,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 30197,
"s": 30154,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 30272,
"s": 30197,
"text": "How to Concat Two Columns Into One With the Existing Column Name in MySQL?"
},
{
"code": null,
"e": 30297,
"s": 30272,
"text": "Spring - REST Controller"
},
{
"code": null,
"e": 30333,
"s": 30297,
"text": "How to Read Text Files with Pandas?"
}
] |
Count the specific value in a given vector in R - GeeksforGeeks | 07 Apr, 2021
In this article, we will discuss how to find the specific value in a given vector in R Programming Language. For finding the frequency of a given value two approaches can be employed and both of them are discussed below.
We can iterate over the vector in R using a for loop and then check if the element is equivalent to the given value. A counter is maintained, and it is increased by 1, each time the value matches. In case, the element is not present, counter returns a value 0. The time complexity of the approach is O(n), where n is the size of the vector.
Example:
R
# declaring a vectorvec = c(1,2,3,4,2,1,4,6) # printing original vectorprint("Original Vectors:")print(vec) # declaring count = 0 count = 0 # given valuex = 4 # looping over vector valuesfor( i in vec){ # check if the value is equal to x if(vec[i]==x){ # increment counter by 1 count= count + 1 }} print("Count given value in above vector:") # check which values are equal to the given # value and calculate sum of itprint (count)
Output
[1] “Original Vectors:”
[1] 1 2 3 4 2 1 4 6
[1] “Count given value in above vector:”
[1] 2
The sum() method can be used to calculate the summation of the values appearing in the function argument. Here, we specify a logical expression as an argument of the sum() function which calculates the sum of values which are equivalent to the specified value. In case the value is not present, the sum method returns 0 as an output. The time complexity of the approach is O(n), where n is the size of the vector.
Syntax:
sum(vec == given_val)
where, vec is the vector and given_val is the given value to check the presence for in the vector.
Example:
R
# declaring a vectorvec = c("a","g","a","y","s","a","abcs") # printing original vectorprint("Original Vectors:")print(vec) print("Count given value in above vector:") # check which values are equal to the given # value and calculate sum of itprint(sum(vec=="a"))
Output
[1] “Original Vectors:”
[1] “a” “g” “a” “y” “s” “a” “abcs”
[1] “Count given value in above vector:”
[1] 3
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 26173,
"s": 26145,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 26394,
"s": 26173,
"text": "In this article, we will discuss how to find the specific value in a given vector in R Programming Language. For finding the frequency of a given value two approaches can be employed and both of them are discussed below."
},
{
"code": null,
"e": 26736,
"s": 26394,
"text": "We can iterate over the vector in R using a for loop and then check if the element is equivalent to the given value. A counter is maintained, and it is increased by 1, each time the value matches. In case, the element is not present, counter returns a value 0. The time complexity of the approach is O(n), where n is the size of the vector. "
},
{
"code": null,
"e": 26745,
"s": 26736,
"text": "Example:"
},
{
"code": null,
"e": 26747,
"s": 26745,
"text": "R"
},
{
"code": "# declaring a vectorvec = c(1,2,3,4,2,1,4,6) # printing original vectorprint(\"Original Vectors:\")print(vec) # declaring count = 0 count = 0 # given valuex = 4 # looping over vector valuesfor( i in vec){ # check if the value is equal to x if(vec[i]==x){ # increment counter by 1 count= count + 1 }} print(\"Count given value in above vector:\") # check which values are equal to the given # value and calculate sum of itprint (count)",
"e": 27220,
"s": 26747,
"text": null
},
{
"code": null,
"e": 27227,
"s": 27220,
"text": "Output"
},
{
"code": null,
"e": 27251,
"s": 27227,
"text": "[1] “Original Vectors:”"
},
{
"code": null,
"e": 27271,
"s": 27251,
"text": "[1] 1 2 3 4 2 1 4 6"
},
{
"code": null,
"e": 27312,
"s": 27271,
"text": "[1] “Count given value in above vector:”"
},
{
"code": null,
"e": 27318,
"s": 27312,
"text": "[1] 2"
},
{
"code": null,
"e": 27733,
"s": 27318,
"text": "The sum() method can be used to calculate the summation of the values appearing in the function argument. Here, we specify a logical expression as an argument of the sum() function which calculates the sum of values which are equivalent to the specified value. In case the value is not present, the sum method returns 0 as an output. The time complexity of the approach is O(n), where n is the size of the vector. "
},
{
"code": null,
"e": 27741,
"s": 27733,
"text": "Syntax:"
},
{
"code": null,
"e": 27765,
"s": 27741,
"text": "sum(vec == given_val) "
},
{
"code": null,
"e": 27865,
"s": 27765,
"text": "where, vec is the vector and given_val is the given value to check the presence for in the vector. "
},
{
"code": null,
"e": 27874,
"s": 27865,
"text": "Example:"
},
{
"code": null,
"e": 27876,
"s": 27874,
"text": "R"
},
{
"code": "# declaring a vectorvec = c(\"a\",\"g\",\"a\",\"y\",\"s\",\"a\",\"abcs\") # printing original vectorprint(\"Original Vectors:\")print(vec) print(\"Count given value in above vector:\") # check which values are equal to the given # value and calculate sum of itprint(sum(vec==\"a\"))",
"e": 28142,
"s": 27876,
"text": null
},
{
"code": null,
"e": 28149,
"s": 28142,
"text": "Output"
},
{
"code": null,
"e": 28173,
"s": 28149,
"text": "[1] “Original Vectors:”"
},
{
"code": null,
"e": 28226,
"s": 28173,
"text": "[1] “a” “g” “a” “y” “s” “a” “abcs”"
},
{
"code": null,
"e": 28267,
"s": 28226,
"text": "[1] “Count given value in above vector:”"
},
{
"code": null,
"e": 28273,
"s": 28267,
"text": "[1] 3"
},
{
"code": null,
"e": 28280,
"s": 28273,
"text": "Picked"
},
{
"code": null,
"e": 28298,
"s": 28280,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 28308,
"s": 28298,
"text": "R-Vectors"
},
{
"code": null,
"e": 28319,
"s": 28308,
"text": "R Language"
},
{
"code": null,
"e": 28330,
"s": 28319,
"text": "R Programs"
},
{
"code": null,
"e": 28428,
"s": 28330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28486,
"s": 28428,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 28538,
"s": 28486,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 28570,
"s": 28538,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 28614,
"s": 28570,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 28666,
"s": 28614,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28724,
"s": 28666,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 28768,
"s": 28724,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 28826,
"s": 28768,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28869,
"s": 28826,
"text": "Replace Specific Characters in String in R"
}
] |
Virtual vs Sealed vs New vs Abstract in C# | The virtual keyword allows a class to be overridden. For overriding a parent class method in the child class, declare the parent class method as virtual.
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
To prevent being overridden, use the sealed in C#. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.
public sealed override void getResult() { }
Use the new keyword to hide the base class method from the derived class. This is done by declaring the derived class function with new. This is how new is used in Shadowing.
public new string getResult()
Abstract classes contain abstract methods, which are implemented by the derived class.
abstract class Vehicle | [
{
"code": null,
"e": 1216,
"s": 1062,
"text": "The virtual keyword allows a class to be overridden. For overriding a parent class method in the child class, declare the parent class method as virtual."
},
{
"code": null,
"e": 1317,
"s": 1216,
"text": "When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed."
},
{
"code": null,
"e": 1568,
"s": 1317,
"text": "To prevent being overridden, use the sealed in C#. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method."
},
{
"code": null,
"e": 1612,
"s": 1568,
"text": "public sealed override void getResult() { }"
},
{
"code": null,
"e": 1787,
"s": 1612,
"text": "Use the new keyword to hide the base class method from the derived class. This is done by declaring the derived class function with new. This is how new is used in Shadowing."
},
{
"code": null,
"e": 1818,
"s": 1787,
"text": "public new string getResult()\n"
},
{
"code": null,
"e": 1905,
"s": 1818,
"text": "Abstract classes contain abstract methods, which are implemented by the derived class."
},
{
"code": null,
"e": 1928,
"s": 1905,
"text": "abstract class Vehicle"
}
] |
How to evaluate my Classification Model results | by Songhao Wu | Towards Data Science | Confusion Matrix, ROC-AUC, F1 Score, Log Loss
Different from the Regression model, when we assess classification model results, we should not only focus on prediction results but also need to consider the prediction probability and prediction ability of each class.
There are plenty of articles online about classification metrics selection and here I will just use my own words to explain my top 5 important metrics you should consider and know before you evaluate your classification model.
1. Confusion Matrix
2. Accuracy, Recall, Precision
3. F1 Score
4. Receiving Operating Characteristics(ROC),Area under the Curve(AUC)
5. Log Loss
The list above does not follow the sequence of importance. For illustration purposes, I will use a housing data example to show the classification result on predicting the housing price range.
From the name we can tell, Confusion Matrix output is a matrix and it is quite ‘confusing’? However, it is actually quite intuitive if you understand the logic. Confusion Matrix is a 2*2 table(for binary class classification)and it is the basis of many other metrics. Assume your classification only has two categories of results (1 or 0), a confusion matrix is the combination of your prediction(1 or 0) vs actual value(1 or 0).
True Positive: Case when you correctly predict the positive result
False Positive: Case when you predict the result to be positive but it is actually negative
False Negative: Case then you predict the result to be negative but it is actually positive
True Negative: Case when you correctly predict negative result
Among the four sections, the first word indicates whether your prediction is correct and the second word indicates your prediction value. It is very useful to see how your classification model performs on different categories of value. The matrix is not just limited to 2*2 and you are able to see a bigger matrix if your classification result has more than 2 categories.
#Calculate confusion matrixfrom sklearn.metrics import confusion_matrixmatrix=confusion_matrix(y_test, y_predicted,labels=['high','low'])cm=pd.DataFrame(matrix,index=['high','low'],columns=['high','low'])print(cm)
Here I have categorized housing prices into high and low and you can see an overall of classified results in different categories. Note that in sklearn package, the y axis is the true value why x value is the predicted value which is different from the normal convention. You can only see the absolute number and it is not so direct to see the percentage metrics here.
The 3 metrics are calculated directly from the confusion matrix result and are percentage metrics based on the absolute number you see from the confusion matrix.
Accuracy is purely how much percentage of cases that you have predicted correctly overall.
Accuracy = (TP+TN)/(TP+TN+FP+FN)
Accuracy is a good measure of how the overall model performs. However, it is not telling you the performance in each category and thus you may miss important information if you purely look at accuracy. It is best to use when a number of cases in different categories are similar or used together with other metrics.
Recall measures how much percentage of real positive cases are correctly identified.
Recall = TP/(TP+FN)
Recall is used when the aim is to capture a maximum number of positive cases. For example, during the recent Covid-19 situation, the government wants to track all the infected cases in the community. If you have built a model to predict whether the person is infected with Covid-19 based on symptoms, Recall will be an important metric to be measured.
Precision measures that among the cases predicted to be positive, how much percentage of them are really positive.
Precision = TP/(TP+FP)
Precision is used when you want to be very accurate in measuring positive cases. It always conflicts with Recall because the more positive cases you want to capture, the lower the standard you will put to be classified as positive cases. In the Covid-19 cases example, if you want to capture more infected cases, you may want to include all cases that have slight symptoms that could just be because of normal flu.
#Calculate Accuracyfrom sklearn.metrics import accuracy_scoreaccuracy_score(y_test,y_predicted)# Accuracy is 0.88124999999999998#Calculate Recallfrom sklearn.metrics import recall_scorerecall_score(y_test, y_predicted)#Recall is 0.84109589041095889#Calculate Precisionfrom sklearn.metrics import precision_scoreprecision_score(y_test, y_predicted)# Precision is 0.84573002754820936
We can see that Accuracy is slightly higher than both recall and precision here because the model is predicting better on negative(low price) cases.
Considering the conflicting feature between precision and recall, the F1 Score is created to have a balanced metric between recall and precision. It is the Harmonic mean of recall and precision.
You may want to ask: why we do not simply average Precision and Recall? Well, if the distribution of positive and negative cases is very uneven, the average may not be a good representation of model performance.
In the example above, there is only 1 real positive case and the model captures it. However, among the 100 cases identified to be positive, only 1 of them is really positive. Thus, recall=1 and precision=0.01. The average between the two is 0.505 which is clearly not a good representation of how bad the model is. F1 score= 2*(1*0.01)/(1+0.01)=0.0198 and this gives a better picture of how the model performs.
#calculate F1 scorefrom sklearn.metrics import f1_scoref1_score(y_test,y_predicted)# F1 score is 0.84340659340659341
AUC is the area under the ROC curve and it is a good measure on two things:
How well the model can separate the two classes(positive and negative)How accurate is the model identify for different categories(like whether it identify group A to positive correctly)?
How well the model can separate the two classes(positive and negative)
How accurate is the model identify for different categories(like whether it identify group A to positive correctly)?
Here we need to understand two metrics first:
True Positive Rate(TPR): TPR actually equals to Recall which is among the truly positive cases, how much percentage of them are captured in the model correctlyFalse Positive Rate(NPR): This measures among the truly negative cases, how much percentage of them are actually false positive.
True Positive Rate(TPR): TPR actually equals to Recall which is among the truly positive cases, how much percentage of them are captured in the model correctly
False Positive Rate(NPR): This measures among the truly negative cases, how much percentage of them are actually false positive.
TPR and NPR are positively correlated. This is because when you want to capture more positive cases in your classification model, inevitably you will misclassify some of them, and NPR increases. ROC curve is TPR plotted against NPR and the bigger the area under the curve the better the separation between different groups.
#Calculate AUC from sklearn.metrics import roc_curve, aucfpr, tpr, treshold = roc_curve(y_test, y_score_new)roc_auc = auc(fpr, tpr)#auc is 0.96
For classification problems on 2 classes (either 1 or 0), the probability of you blindly guessing is 50%. The blue dotted line shows the curve TPR and FPR when you blindly guess the category and for that diagonal line, the area under the curve(AUC) is 0.5.
Each point on the curve represents a different cut-off point between TPR and FPR. For example, if I cannot tolerate any false positive rate (<0.01), then the true positive rate I can reach is around 0.6(see the green dot on the graph). If I loosen my criteria a bit and I only need to control FPR below 0.1, then my TPR can reach 0.9(see the red dot on the graph).
The selection of threshold is based on different business requirements and usually, the best choice is to maximize the difference between TPR and FPR, and on the graph is represented by the maximum vertical distance between the orange and blue dotted line(see the red line). Our prediction example has a pretty good AUC(0.96) and the optimized point is around (0.1,0.9)
You can find more information on ROC-AUC in the link below:
towardsdatascience.com
Log loss function penalizes wrongly classified cases and also lacks of confidence in correctly-classified cases. Same as ROC-AUC, it does not only consider the classification accuracy or results but also considers the probability assigned to each of the cases from the model. The better the model, the lower the log loss value.
y is the real result(0 or 1) and p function is the probability that the model predicts the outcome to 1. Thus, if the real value is 1, we want to maximize the probability that assigns to the prediction of 1 which is p(y) while if the real value is 0 we want to maximize the probability of predicting 0 which is 1-p(y). That is the part after the summation sign which we want to maximize. log function of value between 0–1 is negative. Thus, to make the whole value positive the function has a minus sign at the front and we need to minimize the whole function.
Log Loss value can vary from 0 to infinity. However, if you calculate according to the formula, the log loss function is 0.69 if you just blindly assign 50% to each case. Thus, you should definitely keep the log loss value below 0.69 and decide the threshold based on business requirements.
#Calculate log lossfrom sklearn.metrics import log_losslog_loss(y_test,y_score)#log loss is 0.32241485496779987
In conclusion, different metrics serve different purposes and can be applied accordingly to different problems. However, it is advised to use ROC-AOC or log loss generally because they consider the prediction probability of the prediction for each class. Even though both models predict correctly for the case, the 90% confidence prediction model is definitely more preferred than the 51% confidence prediction model.
If you are interested to know what metrics to use for the regression model, you can refer to the link below: | [
{
"code": null,
"e": 218,
"s": 172,
"text": "Confusion Matrix, ROC-AUC, F1 Score, Log Loss"
},
{
"code": null,
"e": 438,
"s": 218,
"text": "Different from the Regression model, when we assess classification model results, we should not only focus on prediction results but also need to consider the prediction probability and prediction ability of each class."
},
{
"code": null,
"e": 665,
"s": 438,
"text": "There are plenty of articles online about classification metrics selection and here I will just use my own words to explain my top 5 important metrics you should consider and know before you evaluate your classification model."
},
{
"code": null,
"e": 685,
"s": 665,
"text": "1. Confusion Matrix"
},
{
"code": null,
"e": 716,
"s": 685,
"text": "2. Accuracy, Recall, Precision"
},
{
"code": null,
"e": 728,
"s": 716,
"text": "3. F1 Score"
},
{
"code": null,
"e": 798,
"s": 728,
"text": "4. Receiving Operating Characteristics(ROC),Area under the Curve(AUC)"
},
{
"code": null,
"e": 810,
"s": 798,
"text": "5. Log Loss"
},
{
"code": null,
"e": 1003,
"s": 810,
"text": "The list above does not follow the sequence of importance. For illustration purposes, I will use a housing data example to show the classification result on predicting the housing price range."
},
{
"code": null,
"e": 1433,
"s": 1003,
"text": "From the name we can tell, Confusion Matrix output is a matrix and it is quite ‘confusing’? However, it is actually quite intuitive if you understand the logic. Confusion Matrix is a 2*2 table(for binary class classification)and it is the basis of many other metrics. Assume your classification only has two categories of results (1 or 0), a confusion matrix is the combination of your prediction(1 or 0) vs actual value(1 or 0)."
},
{
"code": null,
"e": 1500,
"s": 1433,
"text": "True Positive: Case when you correctly predict the positive result"
},
{
"code": null,
"e": 1592,
"s": 1500,
"text": "False Positive: Case when you predict the result to be positive but it is actually negative"
},
{
"code": null,
"e": 1684,
"s": 1592,
"text": "False Negative: Case then you predict the result to be negative but it is actually positive"
},
{
"code": null,
"e": 1747,
"s": 1684,
"text": "True Negative: Case when you correctly predict negative result"
},
{
"code": null,
"e": 2119,
"s": 1747,
"text": "Among the four sections, the first word indicates whether your prediction is correct and the second word indicates your prediction value. It is very useful to see how your classification model performs on different categories of value. The matrix is not just limited to 2*2 and you are able to see a bigger matrix if your classification result has more than 2 categories."
},
{
"code": null,
"e": 2333,
"s": 2119,
"text": "#Calculate confusion matrixfrom sklearn.metrics import confusion_matrixmatrix=confusion_matrix(y_test, y_predicted,labels=['high','low'])cm=pd.DataFrame(matrix,index=['high','low'],columns=['high','low'])print(cm)"
},
{
"code": null,
"e": 2702,
"s": 2333,
"text": "Here I have categorized housing prices into high and low and you can see an overall of classified results in different categories. Note that in sklearn package, the y axis is the true value why x value is the predicted value which is different from the normal convention. You can only see the absolute number and it is not so direct to see the percentage metrics here."
},
{
"code": null,
"e": 2864,
"s": 2702,
"text": "The 3 metrics are calculated directly from the confusion matrix result and are percentage metrics based on the absolute number you see from the confusion matrix."
},
{
"code": null,
"e": 2955,
"s": 2864,
"text": "Accuracy is purely how much percentage of cases that you have predicted correctly overall."
},
{
"code": null,
"e": 2988,
"s": 2955,
"text": "Accuracy = (TP+TN)/(TP+TN+FP+FN)"
},
{
"code": null,
"e": 3304,
"s": 2988,
"text": "Accuracy is a good measure of how the overall model performs. However, it is not telling you the performance in each category and thus you may miss important information if you purely look at accuracy. It is best to use when a number of cases in different categories are similar or used together with other metrics."
},
{
"code": null,
"e": 3389,
"s": 3304,
"text": "Recall measures how much percentage of real positive cases are correctly identified."
},
{
"code": null,
"e": 3409,
"s": 3389,
"text": "Recall = TP/(TP+FN)"
},
{
"code": null,
"e": 3761,
"s": 3409,
"text": "Recall is used when the aim is to capture a maximum number of positive cases. For example, during the recent Covid-19 situation, the government wants to track all the infected cases in the community. If you have built a model to predict whether the person is infected with Covid-19 based on symptoms, Recall will be an important metric to be measured."
},
{
"code": null,
"e": 3876,
"s": 3761,
"text": "Precision measures that among the cases predicted to be positive, how much percentage of them are really positive."
},
{
"code": null,
"e": 3899,
"s": 3876,
"text": "Precision = TP/(TP+FP)"
},
{
"code": null,
"e": 4314,
"s": 3899,
"text": "Precision is used when you want to be very accurate in measuring positive cases. It always conflicts with Recall because the more positive cases you want to capture, the lower the standard you will put to be classified as positive cases. In the Covid-19 cases example, if you want to capture more infected cases, you may want to include all cases that have slight symptoms that could just be because of normal flu."
},
{
"code": null,
"e": 4696,
"s": 4314,
"text": "#Calculate Accuracyfrom sklearn.metrics import accuracy_scoreaccuracy_score(y_test,y_predicted)# Accuracy is 0.88124999999999998#Calculate Recallfrom sklearn.metrics import recall_scorerecall_score(y_test, y_predicted)#Recall is 0.84109589041095889#Calculate Precisionfrom sklearn.metrics import precision_scoreprecision_score(y_test, y_predicted)# Precision is 0.84573002754820936"
},
{
"code": null,
"e": 4845,
"s": 4696,
"text": "We can see that Accuracy is slightly higher than both recall and precision here because the model is predicting better on negative(low price) cases."
},
{
"code": null,
"e": 5040,
"s": 4845,
"text": "Considering the conflicting feature between precision and recall, the F1 Score is created to have a balanced metric between recall and precision. It is the Harmonic mean of recall and precision."
},
{
"code": null,
"e": 5252,
"s": 5040,
"text": "You may want to ask: why we do not simply average Precision and Recall? Well, if the distribution of positive and negative cases is very uneven, the average may not be a good representation of model performance."
},
{
"code": null,
"e": 5663,
"s": 5252,
"text": "In the example above, there is only 1 real positive case and the model captures it. However, among the 100 cases identified to be positive, only 1 of them is really positive. Thus, recall=1 and precision=0.01. The average between the two is 0.505 which is clearly not a good representation of how bad the model is. F1 score= 2*(1*0.01)/(1+0.01)=0.0198 and this gives a better picture of how the model performs."
},
{
"code": null,
"e": 5780,
"s": 5663,
"text": "#calculate F1 scorefrom sklearn.metrics import f1_scoref1_score(y_test,y_predicted)# F1 score is 0.84340659340659341"
},
{
"code": null,
"e": 5856,
"s": 5780,
"text": "AUC is the area under the ROC curve and it is a good measure on two things:"
},
{
"code": null,
"e": 6043,
"s": 5856,
"text": "How well the model can separate the two classes(positive and negative)How accurate is the model identify for different categories(like whether it identify group A to positive correctly)?"
},
{
"code": null,
"e": 6114,
"s": 6043,
"text": "How well the model can separate the two classes(positive and negative)"
},
{
"code": null,
"e": 6231,
"s": 6114,
"text": "How accurate is the model identify for different categories(like whether it identify group A to positive correctly)?"
},
{
"code": null,
"e": 6277,
"s": 6231,
"text": "Here we need to understand two metrics first:"
},
{
"code": null,
"e": 6565,
"s": 6277,
"text": "True Positive Rate(TPR): TPR actually equals to Recall which is among the truly positive cases, how much percentage of them are captured in the model correctlyFalse Positive Rate(NPR): This measures among the truly negative cases, how much percentage of them are actually false positive."
},
{
"code": null,
"e": 6725,
"s": 6565,
"text": "True Positive Rate(TPR): TPR actually equals to Recall which is among the truly positive cases, how much percentage of them are captured in the model correctly"
},
{
"code": null,
"e": 6854,
"s": 6725,
"text": "False Positive Rate(NPR): This measures among the truly negative cases, how much percentage of them are actually false positive."
},
{
"code": null,
"e": 7178,
"s": 6854,
"text": "TPR and NPR are positively correlated. This is because when you want to capture more positive cases in your classification model, inevitably you will misclassify some of them, and NPR increases. ROC curve is TPR plotted against NPR and the bigger the area under the curve the better the separation between different groups."
},
{
"code": null,
"e": 7322,
"s": 7178,
"text": "#Calculate AUC from sklearn.metrics import roc_curve, aucfpr, tpr, treshold = roc_curve(y_test, y_score_new)roc_auc = auc(fpr, tpr)#auc is 0.96"
},
{
"code": null,
"e": 7579,
"s": 7322,
"text": "For classification problems on 2 classes (either 1 or 0), the probability of you blindly guessing is 50%. The blue dotted line shows the curve TPR and FPR when you blindly guess the category and for that diagonal line, the area under the curve(AUC) is 0.5."
},
{
"code": null,
"e": 7944,
"s": 7579,
"text": "Each point on the curve represents a different cut-off point between TPR and FPR. For example, if I cannot tolerate any false positive rate (<0.01), then the true positive rate I can reach is around 0.6(see the green dot on the graph). If I loosen my criteria a bit and I only need to control FPR below 0.1, then my TPR can reach 0.9(see the red dot on the graph)."
},
{
"code": null,
"e": 8314,
"s": 7944,
"text": "The selection of threshold is based on different business requirements and usually, the best choice is to maximize the difference between TPR and FPR, and on the graph is represented by the maximum vertical distance between the orange and blue dotted line(see the red line). Our prediction example has a pretty good AUC(0.96) and the optimized point is around (0.1,0.9)"
},
{
"code": null,
"e": 8374,
"s": 8314,
"text": "You can find more information on ROC-AUC in the link below:"
},
{
"code": null,
"e": 8397,
"s": 8374,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8725,
"s": 8397,
"text": "Log loss function penalizes wrongly classified cases and also lacks of confidence in correctly-classified cases. Same as ROC-AUC, it does not only consider the classification accuracy or results but also considers the probability assigned to each of the cases from the model. The better the model, the lower the log loss value."
},
{
"code": null,
"e": 9286,
"s": 8725,
"text": "y is the real result(0 or 1) and p function is the probability that the model predicts the outcome to 1. Thus, if the real value is 1, we want to maximize the probability that assigns to the prediction of 1 which is p(y) while if the real value is 0 we want to maximize the probability of predicting 0 which is 1-p(y). That is the part after the summation sign which we want to maximize. log function of value between 0–1 is negative. Thus, to make the whole value positive the function has a minus sign at the front and we need to minimize the whole function."
},
{
"code": null,
"e": 9577,
"s": 9286,
"text": "Log Loss value can vary from 0 to infinity. However, if you calculate according to the formula, the log loss function is 0.69 if you just blindly assign 50% to each case. Thus, you should definitely keep the log loss value below 0.69 and decide the threshold based on business requirements."
},
{
"code": null,
"e": 9689,
"s": 9577,
"text": "#Calculate log lossfrom sklearn.metrics import log_losslog_loss(y_test,y_score)#log loss is 0.32241485496779987"
},
{
"code": null,
"e": 10107,
"s": 9689,
"text": "In conclusion, different metrics serve different purposes and can be applied accordingly to different problems. However, it is advised to use ROC-AOC or log loss generally because they consider the prediction probability of the prediction for each class. Even though both models predict correctly for the case, the 90% confidence prediction model is definitely more preferred than the 51% confidence prediction model."
}
] |
How to access and modify the values of a Tensor in PyTorch? | We use Indexing and Slicing to access the values of a tensor.Indexing is used to access the value of a single element of the tensor, whereasSlicing is used to access the values of a sequence of elements.
We use the assignment operator to modify the values of a tensor. Assigning new value/s using the assignment operator will modify the tensor with new value/s.
Import the required libraries. Here, the required library is torch.
Import the required libraries. Here, the required library is torch.
Define a PyTorch tensor.
Define a PyTorch tensor.
Access the value of a single element at particular index using indexing or access the values of sequence of elements using slicing.
Access the value of a single element at particular index using indexing or access the values of sequence of elements using slicing.
Modify the accessed values with new values using the assignment operator.
Modify the accessed values with new values using the assignment operator.
Finally, print the tensor to check if the tensor is modified with the new values.
Finally, print the tensor to check if the tensor is modified with the new values.
# Python program to access and modify values of a tensor in PyTorch
# Import the libraries
import torch
# Define PyTorch Tensor
a = torch.Tensor([[3, 5],[1, 2],[5, 7]])
print("a:\n",a)
# Access a value at index [1,0]-> 2nd row, 1st Col using indexing
b = a[1,0]
print("a[1,0]:\n", b)
# Other indexing method to access value
c = a[1][0]
print("a[1][0]:\n",c)
# Modifying the value 1 with new value 9
# assignment operator is used to modify with new value
a[1,0] = 9
print("tensor 'a' after modifying value at a[1,0]:")
print("a:\n",a)
a:
tensor([[3., 5.],
[1., 2.],
[5., 7.]])
a[1,0]:
tensor(1.)
a[1][0]:
tensor(1.)
tensor 'a' after modifying value at a[1,0]:
a:
tensor([[3., 5.],
[9., 2.],
[5., 7.]])
# Python program to access and modify values of a tensor in PyTorch
# Import necessary libraries
import torch
# Define PyTorch Tensor
a = torch.Tensor([[3, 5],[1, 2],[5, 7]])
print("a:\n", a)
# Access all values of 2nd row using slicing
b = a[1]
print("a[1]:\n", a[1])
# Access all values of 1st and 2nd rows
b = a[0:2]
print("a[0:2]:\n" , a[0:2])
# Access all values of 2nd col
c = a[:,1]
print("a[:,1]:\n", a[:,1])
# Access values from first two rows but 2nd col
print("a[0:2, 1]:\n", a[0:2, 1])
# assignment operator is used to modify with new value
# Modifying the values of 2nd row
a[1] = torch.Tensor([9, 9])
print("After modifying a[1]:\n", a)
# Modify values of first two rows but 2nd col
a[0:2, 1] = torch.Tensor([4, 4])
print("After modifying a[0:2, 1]:\n", a)
a:
tensor([[3., 5.],
[1., 2.],
[5., 7.]])
a[1]:
tensor([1., 2.])
a[0:2]:
tensor([[3., 5.],
[1., 2.]])
a[:,1]:
tensor([5., 2., 7.])
a[0:2, 1]:
tensor([5., 2.])
After modifying a[1]:
tensor([[3., 5.],
[9., 9.],
[5., 7.]])
After modifying a[0:2, 1]:
tensor([[3., 4.],
[9., 4.],
[5., 7.]]) | [
{
"code": null,
"e": 1266,
"s": 1062,
"text": "We use Indexing and Slicing to access the values of a tensor.Indexing is used to access the value of a single element of the tensor, whereasSlicing is used to access the values of a sequence of elements."
},
{
"code": null,
"e": 1424,
"s": 1266,
"text": "We use the assignment operator to modify the values of a tensor. Assigning new value/s using the assignment operator will modify the tensor with new value/s."
},
{
"code": null,
"e": 1492,
"s": 1424,
"text": "Import the required libraries. Here, the required library is torch."
},
{
"code": null,
"e": 1560,
"s": 1492,
"text": "Import the required libraries. Here, the required library is torch."
},
{
"code": null,
"e": 1585,
"s": 1560,
"text": "Define a PyTorch tensor."
},
{
"code": null,
"e": 1610,
"s": 1585,
"text": "Define a PyTorch tensor."
},
{
"code": null,
"e": 1742,
"s": 1610,
"text": "Access the value of a single element at particular index using indexing or access the values of sequence of elements using slicing."
},
{
"code": null,
"e": 1874,
"s": 1742,
"text": "Access the value of a single element at particular index using indexing or access the values of sequence of elements using slicing."
},
{
"code": null,
"e": 1948,
"s": 1874,
"text": "Modify the accessed values with new values using the assignment operator."
},
{
"code": null,
"e": 2022,
"s": 1948,
"text": "Modify the accessed values with new values using the assignment operator."
},
{
"code": null,
"e": 2104,
"s": 2022,
"text": "Finally, print the tensor to check if the tensor is modified with the new values."
},
{
"code": null,
"e": 2186,
"s": 2104,
"text": "Finally, print the tensor to check if the tensor is modified with the new values."
},
{
"code": null,
"e": 2724,
"s": 2186,
"text": "# Python program to access and modify values of a tensor in PyTorch\n# Import the libraries\nimport torch\n\n# Define PyTorch Tensor\na = torch.Tensor([[3, 5],[1, 2],[5, 7]])\nprint(\"a:\\n\",a)\n\n# Access a value at index [1,0]-> 2nd row, 1st Col using indexing\nb = a[1,0]\nprint(\"a[1,0]:\\n\", b)\n\n# Other indexing method to access value\nc = a[1][0]\nprint(\"a[1][0]:\\n\",c)\n\n# Modifying the value 1 with new value 9\n# assignment operator is used to modify with new value\na[1,0] = 9\nprint(\"tensor 'a' after modifying value at a[1,0]:\")\nprint(\"a:\\n\",a)"
},
{
"code": null,
"e": 2933,
"s": 2724,
"text": "a:\ntensor([[3., 5.],\n [1., 2.],\n [5., 7.]])\na[1,0]:\n tensor(1.)\na[1][0]:\n tensor(1.)\ntensor 'a' after modifying value at a[1,0]:\na:\ntensor([[3., 5.],\n [9., 2.],\n [5., 7.]])"
},
{
"code": null,
"e": 3711,
"s": 2933,
"text": "# Python program to access and modify values of a tensor in PyTorch\n# Import necessary libraries\nimport torch\n\n# Define PyTorch Tensor\na = torch.Tensor([[3, 5],[1, 2],[5, 7]])\nprint(\"a:\\n\", a)\n\n# Access all values of 2nd row using slicing\nb = a[1]\nprint(\"a[1]:\\n\", a[1])\n\n# Access all values of 1st and 2nd rows\nb = a[0:2]\nprint(\"a[0:2]:\\n\" , a[0:2])\n\n# Access all values of 2nd col\nc = a[:,1]\nprint(\"a[:,1]:\\n\", a[:,1])\n\n# Access values from first two rows but 2nd col\nprint(\"a[0:2, 1]:\\n\", a[0:2, 1])\n\n# assignment operator is used to modify with new value\n# Modifying the values of 2nd row\na[1] = torch.Tensor([9, 9])\nprint(\"After modifying a[1]:\\n\", a)\n\n# Modify values of first two rows but 2nd col\na[0:2, 1] = torch.Tensor([4, 4])\nprint(\"After modifying a[0:2, 1]:\\n\", a)"
},
{
"code": null,
"e": 4081,
"s": 3711,
"text": "a:\ntensor([[3., 5.],\n [1., 2.],\n [5., 7.]])\na[1]:\n tensor([1., 2.])\na[0:2]:\n tensor([[3., 5.],\n [1., 2.]])\na[:,1]:\n tensor([5., 2., 7.])\na[0:2, 1]:\n tensor([5., 2.])\nAfter modifying a[1]:\n tensor([[3., 5.],\n [9., 9.],\n [5., 7.]])\nAfter modifying a[0:2, 1]:\ntensor([[3., 4.],\n [9., 4.],\n [5., 7.]])"
}
] |
Python SQLite - Drop Table | You can remove an entire table using the DROP TABLE statement. You just need to specify the name of the table you need to delete.
Following is the syntax of the DROP TABLE statement in PostgreSQL −
DROP TABLE table_name;
Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries −
sqlite> CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
sqlite> CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT,
SEX CHAR(1), INCOME FLOAT
);
sqlite>
Now if you verify the list of tables using the .tables command, you can see the above created tables in it ( list) as −
sqlite> .tables
CRICKETERS EMPLOYEE
sqlite>
Following statement deletes the table named Employee from the database −
sqlite> DROP table employee;
sqlite>
Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it.
sqlite> .tables
CRICKETERS
sqlite>
If you try to delete the Employee table again, since you have already deleted it you will get an error saying “no such table” as shown below −
sqlite> DROP table employee;
Error: no such table: employee
sqlite>
To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation.
sqlite> DROP table IF EXISTS employee;
sqlite>
You can drop a table whenever you need to, using the DROP statement of MYSQL, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table.
To drop a table from a SQLite3 database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it.
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Doping EMPLOYEE table if already exists
cursor.execute("DROP TABLE emp")
print("Table dropped... ")
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
Table dropped...
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3335,
"s": 3205,
"text": "You can remove an entire table using the DROP TABLE statement. You just need to specify the name of the table you need to delete."
},
{
"code": null,
"e": 3403,
"s": 3335,
"text": "Following is the syntax of the DROP TABLE statement in PostgreSQL −"
},
{
"code": null,
"e": 3427,
"s": 3403,
"text": "DROP TABLE table_name;\n"
},
{
"code": null,
"e": 3526,
"s": 3427,
"text": "Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries −"
},
{
"code": null,
"e": 3812,
"s": 3526,
"text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, \n Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nsqlite> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, \n SEX CHAR(1), INCOME FLOAT\n);\nsqlite>"
},
{
"code": null,
"e": 3932,
"s": 3812,
"text": "Now if you verify the list of tables using the .tables command, you can see the above created tables in it ( list) as −"
},
{
"code": null,
"e": 3977,
"s": 3932,
"text": "sqlite> .tables\nCRICKETERS EMPLOYEE\nsqlite>\n"
},
{
"code": null,
"e": 4050,
"s": 3977,
"text": "Following statement deletes the table named Employee from the database −"
},
{
"code": null,
"e": 4088,
"s": 4050,
"text": "sqlite> DROP table employee;\nsqlite>\n"
},
{
"code": null,
"e": 4211,
"s": 4088,
"text": "Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it."
},
{
"code": null,
"e": 4247,
"s": 4211,
"text": "sqlite> .tables\nCRICKETERS\nsqlite>\n"
},
{
"code": null,
"e": 4390,
"s": 4247,
"text": "If you try to delete the Employee table again, since you have already deleted it you will get an error saying “no such table” as shown below −"
},
{
"code": null,
"e": 4459,
"s": 4390,
"text": "sqlite> DROP table employee;\nError: no such table: employee\nsqlite>\n"
},
{
"code": null,
"e": 4609,
"s": 4459,
"text": "To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation."
},
{
"code": null,
"e": 4657,
"s": 4609,
"text": "sqlite> DROP table IF EXISTS employee;\nsqlite>\n"
},
{
"code": null,
"e": 4869,
"s": 4657,
"text": "You can drop a table whenever you need to, using the DROP statement of MYSQL, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table."
},
{
"code": null,
"e": 5021,
"s": 4869,
"text": "To drop a table from a SQLite3 database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it."
},
{
"code": null,
"e": 5364,
"s": 5021,
"text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists\ncursor.execute(\"DROP TABLE emp\")\nprint(\"Table dropped... \")\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()"
},
{
"code": null,
"e": 5382,
"s": 5364,
"text": "Table dropped...\n"
},
{
"code": null,
"e": 5419,
"s": 5382,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5435,
"s": 5419,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5468,
"s": 5435,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5487,
"s": 5468,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5522,
"s": 5487,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5544,
"s": 5522,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5578,
"s": 5544,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5606,
"s": 5578,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5641,
"s": 5606,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5655,
"s": 5641,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5688,
"s": 5655,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5705,
"s": 5688,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5712,
"s": 5705,
"text": " Print"
},
{
"code": null,
"e": 5723,
"s": 5712,
"text": " Add Notes"
}
] |
Matcher group(String) method in Java with Examples - GeeksforGeeks | 26 Nov, 2018
The group(String string) method of Matcher Class is used to get the group of the match result already done, from the specified string.
Syntax:
public String group(String string)
Parameters: This method takes a parameter string which is the String from which the group index of the matched pattern is required.
Return Value: This method returns the group of the matched group from the specified string.
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 name.
Below examples illustrate the Matcher.group() method:
Example 1:
// Java code to illustrate end() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "\\b(?<Geeks>[A-Za-z\\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("Geeks")); } }}
Current Matcher: java.util.regex.Matcher[pattern=\b(?[A-Za-z\s]+) region=0,13 lastmatch=]GeeksForGeeks
Example 2:
// Java code to illustrate end() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "\\b(?<GFG>[A-Za-z\\s]+)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFG FGF GFG"; // 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("GFG")); } }}
Current Matcher: java.util.regex.Matcher[pattern=\b(?[A-Za-z\s]+) region=0,11 lastmatch=]GFG FGF GFG
Reference: Oracle Doc
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.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 23692,
"s": 23557,
"text": "The group(String string) method of Matcher Class is used to get the group of the match result already done, from the specified string."
},
{
"code": null,
"e": 23700,
"s": 23692,
"text": "Syntax:"
},
{
"code": null,
"e": 23736,
"s": 23700,
"text": "public String group(String string)\n"
},
{
"code": null,
"e": 23868,
"s": 23736,
"text": "Parameters: This method takes a parameter string which is the String from which the group index of the matched pattern is required."
},
{
"code": null,
"e": 23960,
"s": 23868,
"text": "Return Value: This method returns the group of the matched group from the specified string."
},
{
"code": null,
"e": 23991,
"s": 23960,
"text": "Exception: This method throws:"
},
{
"code": null,
"e": 24092,
"s": 23991,
"text": "IllegalStateException if no match has yet been attempted, or if the previous match operation failed."
},
{
"code": null,
"e": 24185,
"s": 24092,
"text": "IndexOutOfBoundsException if there is no capturing group in the pattern with the given name."
},
{
"code": null,
"e": 24239,
"s": 24185,
"text": "Below examples illustrate the Matcher.group() method:"
},
{
"code": null,
"e": 24250,
"s": 24239,
"text": "Example 1:"
},
{
"code": "// Java code to illustrate end() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"\\\\b(?<Geeks>[A-Za-z\\\\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(\"Geeks\")); } }}",
"e": 25168,
"s": 24250,
"text": null
},
{
"code": null,
"e": 25271,
"s": 25168,
"text": "Current Matcher: java.util.regex.Matcher[pattern=\\b(?[A-Za-z\\s]+) region=0,13 lastmatch=]GeeksForGeeks"
},
{
"code": null,
"e": 25282,
"s": 25271,
"text": "Example 2:"
},
{
"code": "// Java code to illustrate end() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"\\\\b(?<GFG>[A-Za-z\\\\s]+)\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFG FGF GFG\"; // 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(\"GFG\")); } }}",
"e": 26193,
"s": 25282,
"text": null
},
{
"code": null,
"e": 26294,
"s": 26193,
"text": "Current Matcher: java.util.regex.Matcher[pattern=\\b(?[A-Za-z\\s]+) region=0,11 lastmatch=]GFG FGF GFG"
},
{
"code": null,
"e": 26316,
"s": 26294,
"text": "Reference: Oracle Doc"
},
{
"code": null,
"e": 26336,
"s": 26316,
"text": "Java - util package"
},
{
"code": null,
"e": 26351,
"s": 26336,
"text": "Java-Functions"
},
{
"code": null,
"e": 26364,
"s": 26351,
"text": "Java-Matcher"
},
{
"code": null,
"e": 26369,
"s": 26364,
"text": "Java"
},
{
"code": null,
"e": 26374,
"s": 26369,
"text": "Java"
},
{
"code": null,
"e": 26472,
"s": 26374,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26481,
"s": 26472,
"text": "Comments"
},
{
"code": null,
"e": 26494,
"s": 26481,
"text": "Old Comments"
},
{
"code": null,
"e": 26524,
"s": 26494,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26539,
"s": 26524,
"text": "Stream In Java"
},
{
"code": null,
"e": 26560,
"s": 26539,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26606,
"s": 26560,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26625,
"s": 26606,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26642,
"s": 26625,
"text": "Generics in Java"
},
{
"code": null,
"e": 26685,
"s": 26642,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26701,
"s": 26685,
"text": "Strings in Java"
},
{
"code": null,
"e": 26757,
"s": 26701,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Linking External Style Sheets in CSS | CSS allows us to link external style sheets to our files. This helps us make changes to CSS separately and improves the page load time. External files are specified in <link> tag inside <head> of the document.
The syntax for including external CSS is as follows.
<link rel="stylesheet" href="#location">
The following examples illustrate how CSS files are embedded &miuns;
HTML file
Live Demo
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>Demo Text</h2>
<div>
<ul>
<li>This is demo text.</li>
<li>This is demo text.</li>
<li>This is demo text.</li>
<li>This is demo text.</li>
<li>This is demo text.</li>
</ul>
</div>
</body>
</html>
CSS file
h2 {
color: red;
}
div {
background-color: lightcyan;
}
This gives the following output −
HTML file
Live Demo
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>Demo Heading</h2>
<p>This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. </p>
</body>
</html>
CSS file
p {
background: url("https://www.tutorialspoint.com/images/QAicon.png");
background-origin: content-box;
background-size: cover;
box-shadow: 0 0 3px black;
padding: 20px;
background-origin: border-box;
}
This gives the following output − | [
{
"code": null,
"e": 1272,
"s": 1062,
"text": "CSS allows us to link external style sheets to our files. This helps us make changes to CSS separately and improves the page load time. External files are specified in <link> tag inside <head> of the document."
},
{
"code": null,
"e": 1325,
"s": 1272,
"text": "The syntax for including external CSS is as follows."
},
{
"code": null,
"e": 1366,
"s": 1325,
"text": "<link rel=\"stylesheet\" href=\"#location\">"
},
{
"code": null,
"e": 1435,
"s": 1366,
"text": "The following examples illustrate how CSS files are embedded &miuns;"
},
{
"code": null,
"e": 1445,
"s": 1435,
"text": "HTML file"
},
{
"code": null,
"e": 1456,
"s": 1445,
"text": " Live Demo"
},
{
"code": null,
"e": 1757,
"s": 1456,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n</head>\n<body>\n<h2>Demo Text</h2>\n<div>\n<ul>\n<li>This is demo text.</li>\n<li>This is demo text.</li>\n<li>This is demo text.</li>\n<li>This is demo text.</li>\n<li>This is demo text.</li>\n</ul>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 1766,
"s": 1757,
"text": "CSS file"
},
{
"code": null,
"e": 1828,
"s": 1766,
"text": "h2 {\n color: red;\n}\ndiv {\n background-color: lightcyan;\n}"
},
{
"code": null,
"e": 1862,
"s": 1828,
"text": "This gives the following output −"
},
{
"code": null,
"e": 1872,
"s": 1862,
"text": "HTML file"
},
{
"code": null,
"e": 1883,
"s": 1872,
"text": " Live Demo"
},
{
"code": null,
"e": 2183,
"s": 1883,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n</head>\n<body>\n<h2>Demo Heading</h2>\n<p>This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. </p>\n</body>\n</html>"
},
{
"code": null,
"e": 2192,
"s": 2183,
"text": "CSS file"
},
{
"code": null,
"e": 2414,
"s": 2192,
"text": "p {\n background: url(\"https://www.tutorialspoint.com/images/QAicon.png\");\n background-origin: content-box;\n background-size: cover;\n box-shadow: 0 0 3px black;\n padding: 20px;\n background-origin: border-box;\n}"
},
{
"code": null,
"e": 2448,
"s": 2414,
"text": "This gives the following output −"
}
] |
Word Embeddings for NLP. Understanding word embeddings and their... | by Renu Khandelwal | Towards Data Science | In this article, we will understand how to process text for usage in machine learning algorithms. What are embeddings and why are they used for text processing?
Natural Language Processing(NLP) refers to computer systems designed to understand human language. Human language, like English or Hindi consists of words and sentences, and NLP attempts to extract information from these sentences.
A few of the tasks that NLP is used for
Text summarization: extractive or abstractive text summarization
Sentiment Analysis
Translating from one language to another: neural machine translation
Chatbots
Machine learning and deep learning algorithms only take numeric input so how do we convert text to numbers?
Bag of words is a simple and popular technique for feature extraction from text. Bag of word model processes the text to find how many times each word appeared in the sentence. This is also called as vectorization.
Steps for creating BOW
Tokenize the text into sentences
Tokenize sentences into words
Remove punctuation or stop words
Convert the words to lower text
Create the frequency distribution of words
In the code below, we use CountVectorizer, it tokenizes a collection of text documents, builds a vocabulary of known words, and encodes new documents using that vocabulary.
#Creating frequency distribution of words using nltkfrom nltk.tokenize import sent_tokenizefrom nltk.tokenize import word_tokenizefrom sklearn.feature_extraction.text import CountVectorizertext="""Achievers are not afraid of Challenges, rather they relish them, thrive in them, use them. Challenges makes is stronger. Challenges makes us uncomfortable. If you get comfortable with uncomfort then you will grow. Challenge the challenge """#Tokenize the sentences from the text corpustokenized_text=sent_tokenize(text)#using CountVectorizer and removing stopwords in english languagecv1= CountVectorizer(lowercase=True,stop_words='english')#fitting the tonized senetnecs to the countvectorizertext_counts=cv1.fit_transform(tokenized_text)# printing the vocabulary and the frequency distribution pf vocabulary in tokinzed sentencesprint(cv1.vocabulary_)print(text_counts.toarray())
In the text classification problem, we have a set of texts and their respective labels. We use the Bag of Words model to extract features from the text and we do this by converting the text into a matrix of occurrence of words within a document.
code for simple text summarizer
What is the problem with bag of words?
In the bag of words model, each document is represented as a word-count vector. These counts can be binary counts, a word may occur in the text or not or will have absolute counts. The size of the vector is equal to the number of elements in the vocabulary. If most of the elements are zero then the bag of words will be a sparse matrix.
In deep learning, we would have sparse matrix as we will be working with huge amount of training data. Sparse representations are harder to model both for computational reasons as well as for informational reasons.
Huge amount of weights: Huge input vectors means a huge number of weights for a neural network.
Computationally intensive: More weights means more computation required to train and predict.
Lack of meaningful relations and no consideration for order of words: BOW is a collection of words that appear in the text or sentences with the word counts. Bag of words does not take into consideration the order in which they appear.
Word Embedding is solution to these problems
Embeddings translate large sparse vectors into a lower-dimensional space that preserves semantic relationships.
Word embeddings is a technique where individual words of a domain or language are represented as real-valued vectors in a lower dimensional space.
Sparse Matrix problem with BOW is solved by mapping high-dimensional data into a lower-dimensional space.
Lack of meaningful relationship issue of BOW is solved by placing vectors of semantically similar items close to each other. This way words that have similar meaning have similar distances in the vector space as shown below.
“king is to queen as man is to woman” encoded in the vector space as well as verb Tense and Country and their capitals are encoded in low dimensional space preserving the semantic relationships.
How are semantically similar items placed close to each other?
Let’s explain this using collaborative filtering used in recommendation engines.
Recommendation engines predict what a user would purchase based on historical purchases of other users with similar interests. using collaborative filtering
Amazon and Netflix use recommendation engines for suggesting products or movies to their users
Collaborative filtering is a method where all the similar products bought by multiple customers are embedded into a low dimensional space. This low dimensional space will contain similar products close to each other, hence, it is also called as nearest neighborhood algorithm.
This technique of nearest neighborhood is used for placing semantically similar items close to each other
How do we map high-dimensional data into a lower-dimensional space?
Standard dimensionality reduction techniques like Principal Component Analysis(PCA) can be used to create word embeddings. PCA tries to find highly correlated dimensions that can be collapsed into a single dimension using the BOW.
Word2vec is an algorithm invented at Google for training word embeddings. word2vec relies on the distributional hypothesis. The distributional hypothesis states that words which, often have the same neighboring words tend to be semantically similar. This helps to map semantically similar words to geometrically close embedding vectors.
Distributional hypothesis uses continuous bag of words(CBOW) or skip grams.
word2vec models are shallow neural network with an input layer, a projection layer and an output layer. It is trained to reconstruct linguistic contexts of words. Input layer for Word2vec neural network takes a larger corpus of text to produce a vector space, typically of several hundred dimensions. Every unique word in the text corpus is assigned a corresponding vector in the space.
This architecture is called continuous bag of words CBOW as it uses continuous distributed representation of the context. It considers both the order of words in the history as well as future.
This helps common context word vectors in the corpus to be located close to one another in the vector space.
Skip gram
Skip gram does not predict the current word based on the context instead it uses each current word as an input to a log-linear classifier with continuous projection layer, and predict words within a certain range before and after the current word.
GloVe was developed by Pennington, et al. at Stanford. It is called Global Vectors as the global corpus statistics are captured directly by the model.
It leverages both
Global matrix factorization methods like latent semantic analysis (LSA) for generating low-dimensional word representations
Local context window methods such as the skip-gram model of Mikolov et al
LSA efficiently leverages statistical information but does not do well on word analogy, thus indicating a sub-optimal vector space structure.
Methods like skip-gram perform better on the analogy task, but poorly utilize the statistics of the corpus as they are not trained on global co-occurrence counts. GloVe uses a specific weighted least squares model to train on global word co-occurrence counts to make efficient use of statistics.
Consider two words i=ice and j=steam in the context of Thermodynamics domain. The relationship of these words can be examined by studying the ratio of their co-occurrence probabilities with various probe words k.
Probe words like water or fashion that are either related to both ice and steam, or to neither, the ratio should be close to one. Probe words like solid related to ice but not to steam will have large value for the ratio
Compared to the raw probabilities, the ratio is better able to distinguish relevant words (solid and gas) from irrelevant words (water and fashion) and it is also better able to discriminate between the two relevant words.
It is the gender that distinguishes man from woman, similar to word pairs, such as king and queen or brother and sister. To state this observation mathematically, we might expect that the vector differences man: woman, king: queen, and brother: sister might all be roughly equal. This property and other interesting patterns can be observed in the above set of visualizations using GloVe.
Word embeddings are considered to be one of the successful applications of unsupervised learning at present. They do not require any annotated corpora. Embeddings use a lower-dimensional space while preserving semantic relationships.
https://nlp.stanford.edu/projects/glove/
GloVe: Global Vectors for Word Representation
Efficient estimation of Word Representations in vector space — Tomas Mikolov, Kai Chen, Greg Corrado, Jeffrey Dean | [
{
"code": null,
"e": 333,
"s": 172,
"text": "In this article, we will understand how to process text for usage in machine learning algorithms. What are embeddings and why are they used for text processing?"
},
{
"code": null,
"e": 565,
"s": 333,
"text": "Natural Language Processing(NLP) refers to computer systems designed to understand human language. Human language, like English or Hindi consists of words and sentences, and NLP attempts to extract information from these sentences."
},
{
"code": null,
"e": 605,
"s": 565,
"text": "A few of the tasks that NLP is used for"
},
{
"code": null,
"e": 670,
"s": 605,
"text": "Text summarization: extractive or abstractive text summarization"
},
{
"code": null,
"e": 689,
"s": 670,
"text": "Sentiment Analysis"
},
{
"code": null,
"e": 758,
"s": 689,
"text": "Translating from one language to another: neural machine translation"
},
{
"code": null,
"e": 767,
"s": 758,
"text": "Chatbots"
},
{
"code": null,
"e": 875,
"s": 767,
"text": "Machine learning and deep learning algorithms only take numeric input so how do we convert text to numbers?"
},
{
"code": null,
"e": 1090,
"s": 875,
"text": "Bag of words is a simple and popular technique for feature extraction from text. Bag of word model processes the text to find how many times each word appeared in the sentence. This is also called as vectorization."
},
{
"code": null,
"e": 1113,
"s": 1090,
"text": "Steps for creating BOW"
},
{
"code": null,
"e": 1146,
"s": 1113,
"text": "Tokenize the text into sentences"
},
{
"code": null,
"e": 1176,
"s": 1146,
"text": "Tokenize sentences into words"
},
{
"code": null,
"e": 1209,
"s": 1176,
"text": "Remove punctuation or stop words"
},
{
"code": null,
"e": 1241,
"s": 1209,
"text": "Convert the words to lower text"
},
{
"code": null,
"e": 1284,
"s": 1241,
"text": "Create the frequency distribution of words"
},
{
"code": null,
"e": 1457,
"s": 1284,
"text": "In the code below, we use CountVectorizer, it tokenizes a collection of text documents, builds a vocabulary of known words, and encodes new documents using that vocabulary."
},
{
"code": null,
"e": 2343,
"s": 1457,
"text": "#Creating frequency distribution of words using nltkfrom nltk.tokenize import sent_tokenizefrom nltk.tokenize import word_tokenizefrom sklearn.feature_extraction.text import CountVectorizertext=\"\"\"Achievers are not afraid of Challenges, rather they relish them, thrive in them, use them. Challenges makes is stronger. Challenges makes us uncomfortable. If you get comfortable with uncomfort then you will grow. Challenge the challenge \"\"\"#Tokenize the sentences from the text corpustokenized_text=sent_tokenize(text)#using CountVectorizer and removing stopwords in english languagecv1= CountVectorizer(lowercase=True,stop_words='english')#fitting the tonized senetnecs to the countvectorizertext_counts=cv1.fit_transform(tokenized_text)# printing the vocabulary and the frequency distribution pf vocabulary in tokinzed sentencesprint(cv1.vocabulary_)print(text_counts.toarray())"
},
{
"code": null,
"e": 2589,
"s": 2343,
"text": "In the text classification problem, we have a set of texts and their respective labels. We use the Bag of Words model to extract features from the text and we do this by converting the text into a matrix of occurrence of words within a document."
},
{
"code": null,
"e": 2621,
"s": 2589,
"text": "code for simple text summarizer"
},
{
"code": null,
"e": 2660,
"s": 2621,
"text": "What is the problem with bag of words?"
},
{
"code": null,
"e": 2998,
"s": 2660,
"text": "In the bag of words model, each document is represented as a word-count vector. These counts can be binary counts, a word may occur in the text or not or will have absolute counts. The size of the vector is equal to the number of elements in the vocabulary. If most of the elements are zero then the bag of words will be a sparse matrix."
},
{
"code": null,
"e": 3213,
"s": 2998,
"text": "In deep learning, we would have sparse matrix as we will be working with huge amount of training data. Sparse representations are harder to model both for computational reasons as well as for informational reasons."
},
{
"code": null,
"e": 3309,
"s": 3213,
"text": "Huge amount of weights: Huge input vectors means a huge number of weights for a neural network."
},
{
"code": null,
"e": 3403,
"s": 3309,
"text": "Computationally intensive: More weights means more computation required to train and predict."
},
{
"code": null,
"e": 3639,
"s": 3403,
"text": "Lack of meaningful relations and no consideration for order of words: BOW is a collection of words that appear in the text or sentences with the word counts. Bag of words does not take into consideration the order in which they appear."
},
{
"code": null,
"e": 3684,
"s": 3639,
"text": "Word Embedding is solution to these problems"
},
{
"code": null,
"e": 3796,
"s": 3684,
"text": "Embeddings translate large sparse vectors into a lower-dimensional space that preserves semantic relationships."
},
{
"code": null,
"e": 3943,
"s": 3796,
"text": "Word embeddings is a technique where individual words of a domain or language are represented as real-valued vectors in a lower dimensional space."
},
{
"code": null,
"e": 4049,
"s": 3943,
"text": "Sparse Matrix problem with BOW is solved by mapping high-dimensional data into a lower-dimensional space."
},
{
"code": null,
"e": 4274,
"s": 4049,
"text": "Lack of meaningful relationship issue of BOW is solved by placing vectors of semantically similar items close to each other. This way words that have similar meaning have similar distances in the vector space as shown below."
},
{
"code": null,
"e": 4469,
"s": 4274,
"text": "“king is to queen as man is to woman” encoded in the vector space as well as verb Tense and Country and their capitals are encoded in low dimensional space preserving the semantic relationships."
},
{
"code": null,
"e": 4532,
"s": 4469,
"text": "How are semantically similar items placed close to each other?"
},
{
"code": null,
"e": 4613,
"s": 4532,
"text": "Let’s explain this using collaborative filtering used in recommendation engines."
},
{
"code": null,
"e": 4770,
"s": 4613,
"text": "Recommendation engines predict what a user would purchase based on historical purchases of other users with similar interests. using collaborative filtering"
},
{
"code": null,
"e": 4865,
"s": 4770,
"text": "Amazon and Netflix use recommendation engines for suggesting products or movies to their users"
},
{
"code": null,
"e": 5142,
"s": 4865,
"text": "Collaborative filtering is a method where all the similar products bought by multiple customers are embedded into a low dimensional space. This low dimensional space will contain similar products close to each other, hence, it is also called as nearest neighborhood algorithm."
},
{
"code": null,
"e": 5248,
"s": 5142,
"text": "This technique of nearest neighborhood is used for placing semantically similar items close to each other"
},
{
"code": null,
"e": 5316,
"s": 5248,
"text": "How do we map high-dimensional data into a lower-dimensional space?"
},
{
"code": null,
"e": 5547,
"s": 5316,
"text": "Standard dimensionality reduction techniques like Principal Component Analysis(PCA) can be used to create word embeddings. PCA tries to find highly correlated dimensions that can be collapsed into a single dimension using the BOW."
},
{
"code": null,
"e": 5884,
"s": 5547,
"text": "Word2vec is an algorithm invented at Google for training word embeddings. word2vec relies on the distributional hypothesis. The distributional hypothesis states that words which, often have the same neighboring words tend to be semantically similar. This helps to map semantically similar words to geometrically close embedding vectors."
},
{
"code": null,
"e": 5960,
"s": 5884,
"text": "Distributional hypothesis uses continuous bag of words(CBOW) or skip grams."
},
{
"code": null,
"e": 6347,
"s": 5960,
"text": "word2vec models are shallow neural network with an input layer, a projection layer and an output layer. It is trained to reconstruct linguistic contexts of words. Input layer for Word2vec neural network takes a larger corpus of text to produce a vector space, typically of several hundred dimensions. Every unique word in the text corpus is assigned a corresponding vector in the space."
},
{
"code": null,
"e": 6540,
"s": 6347,
"text": "This architecture is called continuous bag of words CBOW as it uses continuous distributed representation of the context. It considers both the order of words in the history as well as future."
},
{
"code": null,
"e": 6649,
"s": 6540,
"text": "This helps common context word vectors in the corpus to be located close to one another in the vector space."
},
{
"code": null,
"e": 6659,
"s": 6649,
"text": "Skip gram"
},
{
"code": null,
"e": 6907,
"s": 6659,
"text": "Skip gram does not predict the current word based on the context instead it uses each current word as an input to a log-linear classifier with continuous projection layer, and predict words within a certain range before and after the current word."
},
{
"code": null,
"e": 7058,
"s": 6907,
"text": "GloVe was developed by Pennington, et al. at Stanford. It is called Global Vectors as the global corpus statistics are captured directly by the model."
},
{
"code": null,
"e": 7076,
"s": 7058,
"text": "It leverages both"
},
{
"code": null,
"e": 7200,
"s": 7076,
"text": "Global matrix factorization methods like latent semantic analysis (LSA) for generating low-dimensional word representations"
},
{
"code": null,
"e": 7274,
"s": 7200,
"text": "Local context window methods such as the skip-gram model of Mikolov et al"
},
{
"code": null,
"e": 7416,
"s": 7274,
"text": "LSA efficiently leverages statistical information but does not do well on word analogy, thus indicating a sub-optimal vector space structure."
},
{
"code": null,
"e": 7712,
"s": 7416,
"text": "Methods like skip-gram perform better on the analogy task, but poorly utilize the statistics of the corpus as they are not trained on global co-occurrence counts. GloVe uses a specific weighted least squares model to train on global word co-occurrence counts to make efficient use of statistics."
},
{
"code": null,
"e": 7925,
"s": 7712,
"text": "Consider two words i=ice and j=steam in the context of Thermodynamics domain. The relationship of these words can be examined by studying the ratio of their co-occurrence probabilities with various probe words k."
},
{
"code": null,
"e": 8146,
"s": 7925,
"text": "Probe words like water or fashion that are either related to both ice and steam, or to neither, the ratio should be close to one. Probe words like solid related to ice but not to steam will have large value for the ratio"
},
{
"code": null,
"e": 8369,
"s": 8146,
"text": "Compared to the raw probabilities, the ratio is better able to distinguish relevant words (solid and gas) from irrelevant words (water and fashion) and it is also better able to discriminate between the two relevant words."
},
{
"code": null,
"e": 8758,
"s": 8369,
"text": "It is the gender that distinguishes man from woman, similar to word pairs, such as king and queen or brother and sister. To state this observation mathematically, we might expect that the vector differences man: woman, king: queen, and brother: sister might all be roughly equal. This property and other interesting patterns can be observed in the above set of visualizations using GloVe."
},
{
"code": null,
"e": 8992,
"s": 8758,
"text": "Word embeddings are considered to be one of the successful applications of unsupervised learning at present. They do not require any annotated corpora. Embeddings use a lower-dimensional space while preserving semantic relationships."
},
{
"code": null,
"e": 9033,
"s": 8992,
"text": "https://nlp.stanford.edu/projects/glove/"
},
{
"code": null,
"e": 9079,
"s": 9033,
"text": "GloVe: Global Vectors for Word Representation"
}
] |
ES7 - New Features | This chapter provides knowledge about the new features in ES7.
ES7 introduces a new mathematical operator called exponentiation operator. This operator is similar to using Math.pow() method. Exponentiation operator is represented by a double asterisk **. The operator can be used only with numeric values. The syntax for using the exponentiation operator is given below −
The syntax for the exponentiation operator is mentioned below −
base_value ** exponent_value
The following example calculates the exponent of a number using the Math.pow() method and the exponentiation operator.
<script>
let base = 2
let exponent = 3
console.log('using Math.pow()',Math.pow(base,exponent))
console.log('using exponentiation operator',base**exponent)
</script>
The output of the above snippet is as given below −
using Math.pow() 8
using exponentiation operator 8
The Array.includes() method introduced in ES7 helps to check if an element is available in an array. Prior to ES7, the indexof() method of the Array class could be used to verify if a value exists in an array . The indexof() returns the index of the first occurrence of element in the array if the data is found ,else returns -1 if the data doesn't exist.
The Array.includes() method accepts a parameter, checks if the value passed as parameter exists in the array. This method returns true if the value is found, else returns false if the value doesn't exist. The syntax for using the Array.includes() method is given below −
Array.includes(value)
OR
Array.includes(value,start_index)
The second syntax checks if the value exists from the index specified.
The following example declares an array marks and uses the Array.includes() method to verify if a value is present in the array.
<script>
let marks = [50,60,70,80]
//check if 50 is included in array
if(marks.includes(50)){
console.log('found element in array')
}else{
console.log('could not find element')
}
// check if 50 is found from index 1
if(marks.includes(50,1)){ //search from index 1
console.log('found element in array')
}else{
console.log('could not find element')
}
//check Not a Number(NaN) in an array
console.log([NaN].includes(NaN))
//create an object array
let user1 = {name:'kannan'},
user2 = {name:'varun'},
user3={name:'prijin'}
let users = [user1,user2]
//check object is available in array
console.log(users.includes(user1))
console.log(users.includes(user3))
</script>
The output of the above code will be as stated below −
found element in array
could not find element
true
true
false
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2340,
"s": 2277,
"text": "This chapter provides knowledge about the new features in ES7."
},
{
"code": null,
"e": 2649,
"s": 2340,
"text": "ES7 introduces a new mathematical operator called exponentiation operator. This operator is similar to using Math.pow() method. Exponentiation operator is represented by a double asterisk **. The operator can be used only with numeric values. The syntax for using the exponentiation operator is given below −"
},
{
"code": null,
"e": 2713,
"s": 2649,
"text": "The syntax for the exponentiation operator is mentioned below −"
},
{
"code": null,
"e": 2743,
"s": 2713,
"text": "base_value ** exponent_value\n"
},
{
"code": null,
"e": 2862,
"s": 2743,
"text": "The following example calculates the exponent of a number using the Math.pow() method and the exponentiation operator."
},
{
"code": null,
"e": 3039,
"s": 2862,
"text": "<script>\n let base = 2\n let exponent = 3\n console.log('using Math.pow()',Math.pow(base,exponent))\n console.log('using exponentiation operator',base**exponent)\n</script>"
},
{
"code": null,
"e": 3091,
"s": 3039,
"text": "The output of the above snippet is as given below −"
},
{
"code": null,
"e": 3143,
"s": 3091,
"text": "using Math.pow() 8\nusing exponentiation operator 8\n"
},
{
"code": null,
"e": 3499,
"s": 3143,
"text": "The Array.includes() method introduced in ES7 helps to check if an element is available in an array. Prior to ES7, the indexof() method of the Array class could be used to verify if a value exists in an array . The indexof() returns the index of the first occurrence of element in the array if the data is found ,else returns -1 if the data doesn't exist."
},
{
"code": null,
"e": 3770,
"s": 3499,
"text": "The Array.includes() method accepts a parameter, checks if the value passed as parameter exists in the array. This method returns true if the value is found, else returns false if the value doesn't exist. The syntax for using the Array.includes() method is given below −"
},
{
"code": null,
"e": 3793,
"s": 3770,
"text": "Array.includes(value)\n"
},
{
"code": null,
"e": 3796,
"s": 3793,
"text": "OR"
},
{
"code": null,
"e": 3831,
"s": 3796,
"text": "Array.includes(value,start_index)\n"
},
{
"code": null,
"e": 3902,
"s": 3831,
"text": "The second syntax checks if the value exists from the index specified."
},
{
"code": null,
"e": 4031,
"s": 3902,
"text": "The following example declares an array marks and uses the Array.includes() method to verify if a value is present in the array."
},
{
"code": null,
"e": 4779,
"s": 4031,
"text": "<script>\n let marks = [50,60,70,80]\n //check if 50 is included in array\n if(marks.includes(50)){\n console.log('found element in array')\n }else{\n console.log('could not find element')\n }\n\n // check if 50 is found from index 1\n if(marks.includes(50,1)){ //search from index 1\n console.log('found element in array')\n }else{\n console.log('could not find element')\n }\n\n //check Not a Number(NaN) in an array\n console.log([NaN].includes(NaN))\n\n //create an object array\n let user1 = {name:'kannan'},\n user2 = {name:'varun'},\n user3={name:'prijin'}\n let users = [user1,user2]\n\n //check object is available in array\n console.log(users.includes(user1))\n console.log(users.includes(user3))\n</script>"
},
{
"code": null,
"e": 4834,
"s": 4779,
"text": "The output of the above code will be as stated below −"
},
{
"code": null,
"e": 4897,
"s": 4834,
"text": "found element in array\ncould not find element\ntrue\ntrue\nfalse\n"
},
{
"code": null,
"e": 4932,
"s": 4897,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4946,
"s": 4932,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 4979,
"s": 4946,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4997,
"s": 4979,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 5030,
"s": 4997,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5044,
"s": 5030,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5079,
"s": 5044,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5096,
"s": 5079,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 5129,
"s": 5096,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5145,
"s": 5129,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 5180,
"s": 5145,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5188,
"s": 5180,
"text": " Shweta"
},
{
"code": null,
"e": 5195,
"s": 5188,
"text": " Print"
},
{
"code": null,
"e": 5206,
"s": 5195,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.