title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Solving Algebraic Structures Problems by Composition Table - GeeksforGeeks | 05 Mar, 2021
Problem-1:Set G = { 1, ω, ω2 } i.e., three roots of unity and form a finite abelian group with respect to multiplication, also prove this statement by composition table.
Explanation : Given, Set=G={1, ω, ω2 } , operation=‘*’ i.e. multiplication.
To prove that three roots of unity form a finite abelian group we must satisfy the following five properties that is Closure Property, Associative Property, Identity Property, Inverse Property, and Commutative Property.
Note-: ω3=1
1) Closure Property –
∀ a , b ∈ G ⇒ a * b ∈ G
a=1 , b=ω ∈ G
⇒ 1 * ( ω ) = ω = ω ∈ G
Hence, Closure Property is satisfied.
2) Associative Property –
(a* b) * c = a*(b *c) ∀ a , b , c ∈ G
Let a=1, b=ω and c=ω2
So,
LHS = ( a * b )*c
= (1* ω ) *ω2 = ω3=1
RHS = a * ( b * c)
= 1*( ω* ω2 ) = ω3= 1
Hence, RHS = LHS
Associative Property is also Satisfied
3) Identity Property –
a *e = a ∀ a ∈ G
e=identity=1 (in case of multiplication)
1 ∈ G
Let a=1
1*1= 1
1 ∈ G
Identity property is also satisfied.
4) Inverse Property –
Number
Inverse
1
1/1=1
ω
1/ω = ω2/ω .ω2 = ω2
ω2
1/ω2 = ω /ω2.ω =ω
Here we can see that inverse of 1 is 1, inverse of ω is ω2 and inverse of ω2 is ω . These inverse belong to set G.
So, Inverse property is also satisfied.
5) Commutative Property –
a * b = b * a ∀ a , b ∈ G
Let a=1, b=ω
LHS = a * b
= 1*ω = ω
RHS = b * a
= ω *1= ω
LSH=RHS
Commutative Property is also satisfied.
We can see that all five property is satisfied. Hence, Three roots of unity form a finite abelian group with operation multiplication.
Forming Composition Table :
Step-1: Write all elements of set in row and column and given operation ( * ) on the corner and multiply the elements of the column with row element one by one and write it in the row as shown in the figure given below.
Step-2:After multiplying each element of column with row elements our composition table will look like figure given below,
Step-3:We know that,
ω3=1 So, ω4=ω3.ω=1.ω=ω
so our composition table becomes
Step-4:Finding inverse of elements.
Draw horizontal and vertical line from identity elements in each row, the vertical line provides the inverse of row elements, we can clearly see that inverse of 1 is 1, inverse of ω is ω2 and inverse of ω2 is ω.
Step-5: Satisfying Properties of Abelian Group from Composition Table
We see in the composition table all numbers are in set G, Hence Closure Property is satisfied.We see that all numbers in composition table belong to set G, Hence Associative Property is satisfied.In composition table in each row there is identity element 1, Identity Property is satisfied.We see that inverse of 1 is 1, inverse of ω is ω2 and inverse of ω2 is ω. All belongs to set G, hence Inverse Property is also satisfied.All numbers in composition table belongs to set G , Commutative Property is also satisfied.
We see in the composition table all numbers are in set G, Hence Closure Property is satisfied.
We see that all numbers in composition table belong to set G, Hence Associative Property is satisfied.
In composition table in each row there is identity element 1, Identity Property is satisfied.
We see that inverse of 1 is 1, inverse of ω is ω2 and inverse of ω2 is ω. All belongs to set G, hence Inverse Property is also satisfied.
All numbers in composition table belongs to set G , Commutative Property is also satisfied.
Hence, G = { 1, ω, ω2 } is an abelian group with respect to multiplication.
Problem-2:Set G = { 1, -1 , i , -i } i.e., four roots of unity and form a finite abelian group with respect to multiplication.
Explanation :Four roots of unity are 1 ,-1 , i , -i . So our set will be G={ 1 , -1 , i , -i }
Operation = ‘*’ i.e. multiplication.
To prove that four roots of unity form a finite abelian group we must satisfy the following five properties that are Closure Property, Associative Property, Identity Property, Inverse Property, and Commutative Property.
1) Closure Property –
∀ a , b ∈ G ⇒ a * b ∈ G
a=i , b= -i ∈ G
⇒ i * ( -i ) = -i2 = - ( -1 )
=1 ∈ G
Hence, Closure Property is satisfied.
2) Associative Property –
( a* b ) * c = a*( b *c) ∀ a , b , c ∈ G
Let a=1, b=-1 and c=i
So, LHS= ( a * b )*c
= (1* ( -1 ) ) * i = -i
RHS= a * ( b * c)
=1*( -1* i ) = -i
Hence, RHS = LHS
Associative Property is also Satisfied
3) Identity Property –
a *e = a ∀ a ∈ G
e=identity=1 (in case of multiplication)
1 ∈ G
1*1= 1
1 ∈ G
Identity property is also satisfied.
4) Inverse Property –
a * ( 1/a ) = 1 ∀ a ∈ G , 1/a ∈ G
Number
Inverse
1
1/1=1
-1
1/-1 = -1
i
1/i = i/i.i = i/i2 = -i
-i
1/-i = i/-i.i = i/-i2 =i
Here we can see that inverse of 1 is 1, inverse of -1 is 1, inverse of i is -i and inverse of -i is i. These inverse belong to set G.
So, Inverse property is also satisfied.
5) Commutative Property –
a * b = b * a ∀ a , b ∈ G
Let a=1, b=-1
LHS = a * b
= 1*( -1 ) = -1
RHS = b * a
= 1* ( -1 )= -1
LSH=RHS
Commutative Property is also satisfied.
We can see that all five property is satisfied. Hence, Four roots of unity form a finite abelian group with operation multiplication.
portalpirate
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Difference between Propositional Logic and Predicate Logic
Logic Notations in LaTeX
Univariate, Bivariate and Multivariate data and its analysis
Z-test
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS | [
{
"code": null,
"e": 26163,
"s": 26135,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 26334,
"s": 26163,
"text": "Problem-1:Set G = { 1, ω, ω2 } i.e., three roots of unity and form a finite abelian group with respect to multiplication, also prove this statement by composition table."
},
{
"code": null,
"e": 26412,
"s": 26334,
"text": "Explanation : Given, Set=G={1, ω, ω2 } , operation=‘*’ i.e. multiplication."
},
{
"code": null,
"e": 26632,
"s": 26412,
"text": "To prove that three roots of unity form a finite abelian group we must satisfy the following five properties that is Closure Property, Associative Property, Identity Property, Inverse Property, and Commutative Property."
},
{
"code": null,
"e": 26644,
"s": 26632,
"text": "Note-: ω3=1"
},
{
"code": null,
"e": 26666,
"s": 26644,
"text": "1) Closure Property –"
},
{
"code": null,
"e": 26731,
"s": 26666,
"text": "∀ a , b ∈ G ⇒ a * b ∈ G\na=1 , b=ω ∈ G \n⇒ 1 * ( ω ) = ω = ω ∈ G"
},
{
"code": null,
"e": 26769,
"s": 26731,
"text": "Hence, Closure Property is satisfied."
},
{
"code": null,
"e": 26795,
"s": 26769,
"text": "2) Associative Property –"
},
{
"code": null,
"e": 26984,
"s": 26795,
"text": "(a* b) * c = a*(b *c) ∀ a , b , c ∈ G\nLet a=1, b=ω and c=ω2\nSo, \nLHS = ( a * b )*c\n = (1* ω ) *ω2 = ω3=1\n \nRHS = a * ( b * c)\n = 1*( ω* ω2 ) = ω3= 1\n\nHence, RHS = LHS"
},
{
"code": null,
"e": 27023,
"s": 26984,
"text": "Associative Property is also Satisfied"
},
{
"code": null,
"e": 27046,
"s": 27023,
"text": "3) Identity Property –"
},
{
"code": null,
"e": 27176,
"s": 27046,
"text": "a *e = a ∀ a ∈ G\ne=identity=1 (in case of multiplication)\n1 ∈ G\nLet a=1\n1*1= 1\n1 ∈ G\nIdentity property is also satisfied."
},
{
"code": null,
"e": 27198,
"s": 27176,
"text": "4) Inverse Property –"
},
{
"code": null,
"e": 27205,
"s": 27198,
"text": "Number"
},
{
"code": null,
"e": 27213,
"s": 27205,
"text": "Inverse"
},
{
"code": null,
"e": 27215,
"s": 27213,
"text": "1"
},
{
"code": null,
"e": 27221,
"s": 27215,
"text": "1/1=1"
},
{
"code": null,
"e": 27224,
"s": 27221,
"text": "ω "
},
{
"code": null,
"e": 27244,
"s": 27224,
"text": "1/ω = ω2/ω .ω2 = ω2"
},
{
"code": null,
"e": 27247,
"s": 27244,
"text": "ω2"
},
{
"code": null,
"e": 27266,
"s": 27247,
"text": "1/ω2 = ω /ω2.ω =ω "
},
{
"code": null,
"e": 27381,
"s": 27266,
"text": "Here we can see that inverse of 1 is 1, inverse of ω is ω2 and inverse of ω2 is ω . These inverse belong to set G."
},
{
"code": null,
"e": 27421,
"s": 27381,
"text": "So, Inverse property is also satisfied."
},
{
"code": null,
"e": 27447,
"s": 27421,
"text": "5) Commutative Property –"
},
{
"code": null,
"e": 27557,
"s": 27447,
"text": "a * b = b * a ∀ a , b ∈ G\nLet a=1, b=ω\nLHS = a * b\n = 1*ω = ω\nRHS = b * a\n = ω *1= ω\nLSH=RHS"
},
{
"code": null,
"e": 27597,
"s": 27557,
"text": "Commutative Property is also satisfied."
},
{
"code": null,
"e": 27732,
"s": 27597,
"text": "We can see that all five property is satisfied. Hence, Three roots of unity form a finite abelian group with operation multiplication."
},
{
"code": null,
"e": 27762,
"s": 27734,
"text": "Forming Composition Table :"
},
{
"code": null,
"e": 27983,
"s": 27762,
"text": "Step-1: Write all elements of set in row and column and given operation ( * ) on the corner and multiply the elements of the column with row element one by one and write it in the row as shown in the figure given below."
},
{
"code": null,
"e": 28106,
"s": 27983,
"text": "Step-2:After multiplying each element of column with row elements our composition table will look like figure given below,"
},
{
"code": null,
"e": 28128,
"s": 28106,
"text": "Step-3:We know that, "
},
{
"code": null,
"e": 28151,
"s": 28128,
"text": "ω3=1 So, ω4=ω3.ω=1.ω=ω"
},
{
"code": null,
"e": 28185,
"s": 28151,
"text": "so our composition table becomes "
},
{
"code": null,
"e": 28221,
"s": 28185,
"text": "Step-4:Finding inverse of elements."
},
{
"code": null,
"e": 28433,
"s": 28221,
"text": "Draw horizontal and vertical line from identity elements in each row, the vertical line provides the inverse of row elements, we can clearly see that inverse of 1 is 1, inverse of ω is ω2 and inverse of ω2 is ω."
},
{
"code": null,
"e": 28503,
"s": 28433,
"text": "Step-5: Satisfying Properties of Abelian Group from Composition Table"
},
{
"code": null,
"e": 29021,
"s": 28503,
"text": "We see in the composition table all numbers are in set G, Hence Closure Property is satisfied.We see that all numbers in composition table belong to set G, Hence Associative Property is satisfied.In composition table in each row there is identity element 1, Identity Property is satisfied.We see that inverse of 1 is 1, inverse of ω is ω2 and inverse of ω2 is ω. All belongs to set G, hence Inverse Property is also satisfied.All numbers in composition table belongs to set G , Commutative Property is also satisfied."
},
{
"code": null,
"e": 29116,
"s": 29021,
"text": "We see in the composition table all numbers are in set G, Hence Closure Property is satisfied."
},
{
"code": null,
"e": 29219,
"s": 29116,
"text": "We see that all numbers in composition table belong to set G, Hence Associative Property is satisfied."
},
{
"code": null,
"e": 29313,
"s": 29219,
"text": "In composition table in each row there is identity element 1, Identity Property is satisfied."
},
{
"code": null,
"e": 29451,
"s": 29313,
"text": "We see that inverse of 1 is 1, inverse of ω is ω2 and inverse of ω2 is ω. All belongs to set G, hence Inverse Property is also satisfied."
},
{
"code": null,
"e": 29543,
"s": 29451,
"text": "All numbers in composition table belongs to set G , Commutative Property is also satisfied."
},
{
"code": null,
"e": 29619,
"s": 29543,
"text": "Hence, G = { 1, ω, ω2 } is an abelian group with respect to multiplication."
},
{
"code": null,
"e": 29746,
"s": 29619,
"text": "Problem-2:Set G = { 1, -1 , i , -i } i.e., four roots of unity and form a finite abelian group with respect to multiplication."
},
{
"code": null,
"e": 29841,
"s": 29746,
"text": "Explanation :Four roots of unity are 1 ,-1 , i , -i . So our set will be G={ 1 , -1 , i , -i }"
},
{
"code": null,
"e": 29878,
"s": 29841,
"text": "Operation = ‘*’ i.e. multiplication."
},
{
"code": null,
"e": 30098,
"s": 29878,
"text": "To prove that four roots of unity form a finite abelian group we must satisfy the following five properties that are Closure Property, Associative Property, Identity Property, Inverse Property, and Commutative Property."
},
{
"code": null,
"e": 30120,
"s": 30098,
"text": "1) Closure Property –"
},
{
"code": null,
"e": 30203,
"s": 30120,
"text": "∀ a , b ∈ G ⇒ a * b ∈ G\na=i , b= -i ∈ G \n⇒ i * ( -i ) = -i2 = - ( -1 )\n =1 ∈ G"
},
{
"code": null,
"e": 30241,
"s": 30203,
"text": "Hence, Closure Property is satisfied."
},
{
"code": null,
"e": 30267,
"s": 30241,
"text": "2) Associative Property –"
},
{
"code": null,
"e": 30457,
"s": 30267,
"text": "( a* b ) * c = a*( b *c) ∀ a , b , c ∈ G\nLet a=1, b=-1 and c=i\nSo, LHS= ( a * b )*c\n = (1* ( -1 ) ) * i = -i\n RHS= a * ( b * c)\n =1*( -1* i ) = -i\nHence, RHS = LHS"
},
{
"code": null,
"e": 30496,
"s": 30457,
"text": "Associative Property is also Satisfied"
},
{
"code": null,
"e": 30519,
"s": 30496,
"text": "3) Identity Property –"
},
{
"code": null,
"e": 30604,
"s": 30519,
"text": "a *e = a ∀ a ∈ G\ne=identity=1 (in case of multiplication)\n1 ∈ G\n1*1= 1\n1 ∈ G"
},
{
"code": null,
"e": 30641,
"s": 30604,
"text": "Identity property is also satisfied."
},
{
"code": null,
"e": 30663,
"s": 30641,
"text": "4) Inverse Property –"
},
{
"code": null,
"e": 30707,
"s": 30663,
"text": "a * ( 1/a ) = 1 ∀ a ∈ G , 1/a ∈ G "
},
{
"code": null,
"e": 30714,
"s": 30707,
"text": "Number"
},
{
"code": null,
"e": 30722,
"s": 30714,
"text": "Inverse"
},
{
"code": null,
"e": 30724,
"s": 30722,
"text": "1"
},
{
"code": null,
"e": 30730,
"s": 30724,
"text": "1/1=1"
},
{
"code": null,
"e": 30733,
"s": 30730,
"text": "-1"
},
{
"code": null,
"e": 30743,
"s": 30733,
"text": "1/-1 = -1"
},
{
"code": null,
"e": 30745,
"s": 30743,
"text": "i"
},
{
"code": null,
"e": 30769,
"s": 30745,
"text": "1/i = i/i.i = i/i2 = -i"
},
{
"code": null,
"e": 30772,
"s": 30769,
"text": "-i"
},
{
"code": null,
"e": 30797,
"s": 30772,
"text": "1/-i = i/-i.i = i/-i2 =i"
},
{
"code": null,
"e": 30931,
"s": 30797,
"text": "Here we can see that inverse of 1 is 1, inverse of -1 is 1, inverse of i is -i and inverse of -i is i. These inverse belong to set G."
},
{
"code": null,
"e": 30971,
"s": 30931,
"text": "So, Inverse property is also satisfied."
},
{
"code": null,
"e": 30997,
"s": 30971,
"text": "5) Commutative Property –"
},
{
"code": null,
"e": 31122,
"s": 30997,
"text": "a * b = b * a ∀ a , b ∈ G\nLet a=1, b=-1\nLHS = a * b\n = 1*( -1 ) = -1\nRHS = b * a\n = 1* ( -1 )= -1\nLSH=RHS"
},
{
"code": null,
"e": 31162,
"s": 31122,
"text": "Commutative Property is also satisfied."
},
{
"code": null,
"e": 31296,
"s": 31162,
"text": "We can see that all five property is satisfied. Hence, Four roots of unity form a finite abelian group with operation multiplication."
},
{
"code": null,
"e": 31309,
"s": 31296,
"text": "portalpirate"
},
{
"code": null,
"e": 31333,
"s": 31309,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 31341,
"s": 31333,
"text": "GATE CS"
},
{
"code": null,
"e": 31439,
"s": 31341,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31460,
"s": 31439,
"text": "Activation Functions"
},
{
"code": null,
"e": 31519,
"s": 31460,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 31544,
"s": 31519,
"text": "Logic Notations in LaTeX"
},
{
"code": null,
"e": 31605,
"s": 31544,
"text": "Univariate, Bivariate and Multivariate data and its analysis"
},
{
"code": null,
"e": 31612,
"s": 31605,
"text": "Z-test"
},
{
"code": null,
"e": 31632,
"s": 31612,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 31656,
"s": 31632,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 31669,
"s": 31656,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 31696,
"s": 31669,
"text": "Types of Operating Systems"
}
] |
Convert a String to an Expression in R Programming - parse() Function - GeeksforGeeks | 24 Jun, 2020
parse() function in R Language is used to convert an object of character class to an object of expression class.
Syntax: parse(text = character)
Parameters:character: Object of character class
Example 1:
# R program to convert # character to expression # Creating an object of character classx <- "sin(pi / 2)" # Class of objectclass(x) # Calling parse() Functionx1 <- parse(text = x) # Class of parsed objectclass(x1)
Output:
[1] "character"
[1] "expression"
Example 2:
# R program to convert # character to expression # Creating an object of character classx <- "2 ^ 3" # Evaluating the value of objecteval(x) # Calling parse() Functionx1 <- parse(text = x) # Evaluating the value of objecteval(x1)
Output:
[1] "2^3"
[1] 8
R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
R Programming Language - Introduction
K-Means Clustering in R Programming
Replace Specific Characters in String in R | [
{
"code": null,
"e": 26223,
"s": 26195,
"text": "\n24 Jun, 2020"
},
{
"code": null,
"e": 26336,
"s": 26223,
"text": "parse() function in R Language is used to convert an object of character class to an object of expression class."
},
{
"code": null,
"e": 26368,
"s": 26336,
"text": "Syntax: parse(text = character)"
},
{
"code": null,
"e": 26416,
"s": 26368,
"text": "Parameters:character: Object of character class"
},
{
"code": null,
"e": 26427,
"s": 26416,
"text": "Example 1:"
},
{
"code": "# R program to convert # character to expression # Creating an object of character classx <- \"sin(pi / 2)\" # Class of objectclass(x) # Calling parse() Functionx1 <- parse(text = x) # Class of parsed objectclass(x1)",
"e": 26646,
"s": 26427,
"text": null
},
{
"code": null,
"e": 26654,
"s": 26646,
"text": "Output:"
},
{
"code": null,
"e": 26688,
"s": 26654,
"text": "[1] \"character\"\n[1] \"expression\"\n"
},
{
"code": null,
"e": 26699,
"s": 26688,
"text": "Example 2:"
},
{
"code": "# R program to convert # character to expression # Creating an object of character classx <- \"2 ^ 3\" # Evaluating the value of objecteval(x) # Calling parse() Functionx1 <- parse(text = x) # Evaluating the value of objecteval(x1)",
"e": 26933,
"s": 26699,
"text": null
},
{
"code": null,
"e": 26941,
"s": 26933,
"text": "Output:"
},
{
"code": null,
"e": 26958,
"s": 26941,
"text": "[1] \"2^3\"\n[1] 8\n"
},
{
"code": null,
"e": 26977,
"s": 26958,
"text": "R String-Functions"
},
{
"code": null,
"e": 26988,
"s": 26977,
"text": "R Language"
},
{
"code": null,
"e": 27086,
"s": 26988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27138,
"s": 27086,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27170,
"s": 27138,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 27222,
"s": 27170,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27266,
"s": 27222,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27301,
"s": 27266,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27339,
"s": 27301,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27397,
"s": 27339,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27435,
"s": 27397,
"text": "R Programming Language - Introduction"
},
{
"code": null,
"e": 27471,
"s": 27435,
"text": "K-Means Clustering in R Programming"
}
] |
numpy.random.permutation() in Python - GeeksforGeeks | 15 Jul, 2020
With the help of numpy.random.permutation() method, we can get the random samples of sequence of permutation and return sequence by using this method.
Syntax : numpy.random.permutation(x)
Return : Return the random sequence of permuted values.
Example #1 :
In this example we can see that by using numpy.random.permutation() method, we are able to get the sequence of permutation and it will return the sequence by using this method.
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using permutation() methodgfg = np.random.permutation(200) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Example #2 :
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt arr = np.arange(12).reshape((4, 3))# Using permutation() methodgfg = np.random.permutation(arr) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python | [
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 26216,
"s": 26065,
"text": "With the help of numpy.random.permutation() method, we can get the random samples of sequence of permutation and return sequence by using this method."
},
{
"code": null,
"e": 26253,
"s": 26216,
"text": "Syntax : numpy.random.permutation(x)"
},
{
"code": null,
"e": 26309,
"s": 26253,
"text": "Return : Return the random sequence of permuted values."
},
{
"code": null,
"e": 26322,
"s": 26309,
"text": "Example #1 :"
},
{
"code": null,
"e": 26499,
"s": 26322,
"text": "In this example we can see that by using numpy.random.permutation() method, we are able to get the sequence of permutation and it will return the sequence by using this method."
},
{
"code": null,
"e": 26507,
"s": 26499,
"text": "Python3"
},
{
"code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using permutation() methodgfg = np.random.permutation(200) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()",
"e": 26701,
"s": 26507,
"text": null
},
{
"code": null,
"e": 26710,
"s": 26701,
"text": "Output :"
},
{
"code": null,
"e": 26723,
"s": 26710,
"text": "Example #2 :"
},
{
"code": null,
"e": 26731,
"s": 26723,
"text": "Python3"
},
{
"code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt arr = np.arange(12).reshape((4, 3))# Using permutation() methodgfg = np.random.permutation(arr) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()",
"e": 26960,
"s": 26731,
"text": null
},
{
"code": null,
"e": 26969,
"s": 26960,
"text": "Output :"
},
{
"code": null,
"e": 26989,
"s": 26969,
"text": "Python numpy-Random"
},
{
"code": null,
"e": 27002,
"s": 26989,
"text": "Python-numpy"
},
{
"code": null,
"e": 27009,
"s": 27002,
"text": "Python"
},
{
"code": null,
"e": 27107,
"s": 27009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27125,
"s": 27107,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27157,
"s": 27125,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27179,
"s": 27157,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27221,
"s": 27179,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27247,
"s": 27221,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27276,
"s": 27247,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27320,
"s": 27276,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27357,
"s": 27320,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27393,
"s": 27357,
"text": "Convert integer to string in Python"
}
] |
How to check a JavaScript Object is a DOM Object ? - GeeksforGeeks | 19 Jun, 2019
Prerequisite: DOM (Document object model), Instanceof Operator
DOM (Document Object Model): Document Object Model is a hierarchical representation of HTML and XML documents in a format that is easier to interpret in terms of programming. It makes manipulation of tags, elements, attributes, and classes by interpreting its structure in the form of a tree-like model consisting of nodes.
Element: In HTML DOM, Element is the general base class for all objects. An Element object represents all HTML elements.
Approach: In order to check whether a JavaScript object is a DOM object, we need to check whether the given JS object is of Element type Object. In order to check this, we will use instanceof operator. The instanceof operator returns a boolean value which specifies whether or not an object is an instance of a given Class.
Syntax:
Object instanceof ObjectType
Parameters:
Object: It stores the Object which need to be tested.
ObjectType: It stores the Object Type to be tested against.
Example:
<!DOCTYPE HTML> <html> <head> <title> How to check a JavaScript Object is a DOM Object ? </title></head> <body> <div id="div1"></div> <div id="nonElem"></div> <script> // Function to check the object // id DOM object or not function isDOM(Obj) { // Function that checks whether // object is of type Element return Obj instanceof Element; } // Set all elements into HTML var div = document.getElementById('div1'); var nonElem = document.getElementById('nonElem'); // Creating a non-DOM Object var x = 1; // Checks against HTML elements and // non-HTML elements if (isDOM(div)) div.innerHTML = "Div is detected as a DOM Object"; if (!isDOM(x)) nonElem.innerHTML = "x is detected as a non-DOM Object"; </script></body> </html>
Output:
Div is detected as a DOM Object
x is detected as a non-DOM Object
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
javascript-object
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 39213,
"s": 39185,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 39276,
"s": 39213,
"text": "Prerequisite: DOM (Document object model), Instanceof Operator"
},
{
"code": null,
"e": 39600,
"s": 39276,
"text": "DOM (Document Object Model): Document Object Model is a hierarchical representation of HTML and XML documents in a format that is easier to interpret in terms of programming. It makes manipulation of tags, elements, attributes, and classes by interpreting its structure in the form of a tree-like model consisting of nodes."
},
{
"code": null,
"e": 39721,
"s": 39600,
"text": "Element: In HTML DOM, Element is the general base class for all objects. An Element object represents all HTML elements."
},
{
"code": null,
"e": 40045,
"s": 39721,
"text": "Approach: In order to check whether a JavaScript object is a DOM object, we need to check whether the given JS object is of Element type Object. In order to check this, we will use instanceof operator. The instanceof operator returns a boolean value which specifies whether or not an object is an instance of a given Class."
},
{
"code": null,
"e": 40053,
"s": 40045,
"text": "Syntax:"
},
{
"code": null,
"e": 40082,
"s": 40053,
"text": "Object instanceof ObjectType"
},
{
"code": null,
"e": 40094,
"s": 40082,
"text": "Parameters:"
},
{
"code": null,
"e": 40148,
"s": 40094,
"text": "Object: It stores the Object which need to be tested."
},
{
"code": null,
"e": 40208,
"s": 40148,
"text": "ObjectType: It stores the Object Type to be tested against."
},
{
"code": null,
"e": 40217,
"s": 40208,
"text": "Example:"
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to check a JavaScript Object is a DOM Object ? </title></head> <body> <div id=\"div1\"></div> <div id=\"nonElem\"></div> <script> // Function to check the object // id DOM object or not function isDOM(Obj) { // Function that checks whether // object is of type Element return Obj instanceof Element; } // Set all elements into HTML var div = document.getElementById('div1'); var nonElem = document.getElementById('nonElem'); // Creating a non-DOM Object var x = 1; // Checks against HTML elements and // non-HTML elements if (isDOM(div)) div.innerHTML = \"Div is detected as a DOM Object\"; if (!isDOM(x)) nonElem.innerHTML = \"x is detected as a non-DOM Object\"; </script></body> </html>",
"e": 41186,
"s": 40217,
"text": null
},
{
"code": null,
"e": 41194,
"s": 41186,
"text": "Output:"
},
{
"code": null,
"e": 41261,
"s": 41194,
"text": "Div is detected as a DOM Object\nx is detected as a non-DOM Object\n"
},
{
"code": null,
"e": 41398,
"s": 41261,
"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": 41407,
"s": 41398,
"text": "HTML-DOM"
},
{
"code": null,
"e": 41425,
"s": 41407,
"text": "javascript-object"
},
{
"code": null,
"e": 41432,
"s": 41425,
"text": "Picked"
},
{
"code": null,
"e": 41437,
"s": 41432,
"text": "HTML"
},
{
"code": null,
"e": 41448,
"s": 41437,
"text": "JavaScript"
},
{
"code": null,
"e": 41465,
"s": 41448,
"text": "Web Technologies"
},
{
"code": null,
"e": 41492,
"s": 41465,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 41497,
"s": 41492,
"text": "HTML"
},
{
"code": null,
"e": 41595,
"s": 41497,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41645,
"s": 41595,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 41707,
"s": 41645,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 41755,
"s": 41707,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 41815,
"s": 41755,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 41868,
"s": 41815,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 41908,
"s": 41868,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 41953,
"s": 41908,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42014,
"s": 41953,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 42086,
"s": 42014,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Match a pattern and String without using regular expressions - GeeksforGeeks | 25 Jan, 2022
Given a string, find out if string follows a given pattern or not without using any regular expressions. Examples:
Input:
string - GraphTreesGraph
pattern - aba
Output:
a->Graph
b->Trees
Input:
string - GraphGraphGraph
pattern - aaa
Output:
a->Graph
Input:
string - GeeksforGeeks
pattern - GfG
Output:
G->Geeks
f->for
Input:
string - GeeksforGeeks
pattern - GG
Output:
No solution exists
We can solve this problem with the help of Backtracking. For each character in the pattern, if the character is not seen before, we consider all possible sub-strings and recurse to see if it leads to the solution or not. We maintain a map that stores sub-string mapped to a pattern character. If pattern character is seen before, we use the same sub-string present in the map. If we found a solution, for each distinct character in the pattern, we print string mapped to it using our map.Below is C++ implementation of above idea –
CPP
Java
Python3
Javascript
// C++ program to find out if string follows// a given pattern or not#include <bits/stdc++.h>using namespace std; /* Function to find out if string follows a given pattern or not str - given string n - length of given string i - current index in input string pat - given pattern m - length of given pattern j - current index in given pattern map - stores mapping between pattern and string */bool patternMatchUtil(string str, int n, int i, string pat, int m, int j, unordered_map<char, string>& map){ // If both string and pattern reach their end if (i == n && j == m) return true; // If either string or pattern reach their end if (i == n || j == m) return false; // read next character from the pattern char ch = pat[j]; // if character is seen before if (map.find(ch)!= map.end()) { string s = map[ch]; int len = s.size(); // consider next len characters of str string subStr = str.substr(i, len); // if next len characters of string str // don't match with s, return false if (subStr.compare(s)) return false; // if it matches, recurse for remaining characters return patternMatchUtil(str, n, i + len, pat, m, j + 1, map); } // If character is seen for first time, try out all // remaining characters in the string for (int len = 1; len <= n - i; len++) { // consider substring that starts at position i // and spans len characters and add it to map map[ch] = str.substr(i, len); // see if it leads to the solution if (patternMatchUtil(str, n, i + len, pat, m, j + 1, map)) return true; // if not, remove ch from the map map.erase(ch); } return false;} // A wrapper over patternMatchUtil()functionbool patternMatch(string str, string pat, int n, int m){ if (n < m) return false; // create an empty hashmap unordered_map<char, string> map; // store result in a boolean variable res bool res = patternMatchUtil(str, n, 0, pat, m, 0, map); // if solution exists, print the mappings for (auto it = map.begin(); res && it != map.end(); it++) cout << it->first << "->" << it->second << endl; // return result return res;} // Driver codeint main(){ string str = "GeeksforGeeks", pat = "GfG"; int n = str.size(), m = pat.size(); if (!patternMatch(str, pat, n, m)) cout << "No Solution exists"; return 0;}
import java.util.HashMap;import java.util.Map; class Main{ // Function to determine if given pattern matches with a string or not public static boolean match(String str, int i, String pat, int j, Map<Character, String> map) { int n = str.length(), m = pat.length(); // base condition if (n < m) { return false; } // if both pattern and the string reaches end if (i == n && j == m) { return true; } // if either string or pattern reaches end if (i == n || j == m) { return false; } // consider next character from the pattern char curr = pat.charAt(j); // if the character is seen before if (map.containsKey(curr)) { String s = map.get(curr); int k = s.length(); // ss stores next k characters of the given string String ss; if (i + k < str.length()) { ss = str.substring(i, i + k); } else { ss = str.substring(i); } // return false if next k characters doesn't match with s if (ss.compareTo(s) != 0) { return false; } // recur for remaining characters if next k characters matches return match(str, i + k, pat, j + 1, map); } // process all remaining characters in the string if current // character is never seen before for (int k = 1; k <= n - i; k++) { // insert substring formed by next k characters of the string // into the map map.put(curr, str.substring(i, i + k)); // check if it leads to the solution if (match(str, i + k, pat, j + 1, map)) { return true; } // else backtrack - remove current character from the map map.remove(curr); } return false; } public static void main(String[] args) { // input string and pattern String str = "GeeksforGeeks"; String pat = "GfG"; // create a map to store mappings between the pattern and string Map<Character, String> map = new HashMap<>(); // check for solution if (match(str, 0, pat, 0, map)) { for (Map.Entry<Character, String> entry: map.entrySet()) { System.out.println(entry.getKey() + "->" + entry.getValue()); } } else { System.out.println("Solution doesn't exist"); } }} //This code is contributed by Priyadarshini Kumari
# Function to determine if given pattern matches with a string or notdef match(str, pat, dict, i=0, j=0): n = len(str) m = len(pat) # base condition if n < m: return False # if both pattern and the string reaches end if i == n and j == m: return True # if either string or pattern reaches end if i == n or j == m: return False # consider next character from the pattern curr = pat[j] # if the character is seen before if curr in dict: s = dict[curr] k = len(s) # ss stores next k characters of the given string if i + k < len(str): ss = str[i:i + k] else: ss = str[i:] # return false if next k characters doesn't match with s if ss != s: return False # recur for remaining characters if next k characters matches return match(str, pat, dict, i + k, j + 1) # process all remaining characters in the string if current # character is never seen before for k in range(1, n - i + 1): # insert substring formed by next k characters of the string # into the dictionary dict[curr] = str[i:i + k] # check if it leads to the solution if match(str, pat, dict, i + k, j + 1): return True # else backtrack - remove current character from the dictionary dict.pop(curr) return False if __name__ == '__main__': # input string and pattern str = "GeeksforGeeks" pat = "GfG" # create a dictionary to store mappings between the pattern and string dict = {} # check for solution if match(str, pat, dict): print(dict) else: print("Solution doesn't exist") # This code is contributed by Priyadarshini Kumari
<script> // Javascript program to find out if string follows// a given pattern or not /* Function to find out if string follows a given pattern or not str - given string n - length of given string i - current index in input string pat - given pattern m - length of given pattern j - current index in given pattern map - stores mapping between pattern and string */function patternMatchUtil(str, n, i, pat, m, j, map) { // If both string and pattern reach their end if (i == n && j == m) return true; // If either string or pattern reach their end if (i == n || j == m) return false; // read next character from the pattern let ch = pat[j]; // if character is seen before if (map.has(ch)) { let s = map.get(ch); let len = s.length; // consider next len characters of str let subStr = str.substr(i, len); // if next len characters of string str // don't match with s, return false if (subStr != s) return false; // if it matches, recurse for remaining characters return patternMatchUtil(str, n, i + len, pat, m, j + 1, map); } // If character is seen for first time, try out all // remaining characters in the string for (let len = 1; len <= n - i; len++) { // consider substring that starts at position i // and spans len characters and add it to map map.set(ch, str.substr(i, len)); // see if it leads to the solution if (patternMatchUtil(str, n, i + len, pat, m, j + 1, map)) return true; // if not, remove ch from the map map.delete(ch); } return false;} // A wrapper over patternMatchUtil()functionfunction patternMatch(str, pat, n, m) { if (n < m) return false; // create an empty hashmap let map = new Map(); // store result in a boolean variable res let res = patternMatchUtil(str, n, 0, pat, m, 0, map); // if solution exists, print the mappings console.log(map) for (it of [...map.keys()].reverse()) document.write(it + "->" + map.get(it) + "<br>"); // return result return res;} // Driver codelet str = "GeeksforGeeks", pat = "GfG"; let n = str.lengthlet m = pat.length; if (!patternMatch(str, pat, n, m)) document.write("No Solution exists"); // This code is contributed by saurabh_jaiswal.</script>
Output:
f->for
G->Geeks
This article is contributed by Aditya Goel. 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.
pawki
_saurabh_jaiswal
Backtracking
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
m Coloring Problem | Backtracking-5
Print all paths from a given source to a destination
Subset Sum | Backtracking-4
Backtracking to find all subsets
Combinational Sum
Print all permutations of a string in Java
Travelling Salesman Problem implementation using BackTracking
8 queen problem
Count all possible paths between two vertices | [
{
"code": null,
"e": 26327,
"s": 26299,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 26444,
"s": 26327,
"text": "Given a string, find out if string follows a given pattern or not without using any regular expressions. Examples: "
},
{
"code": null,
"e": 26728,
"s": 26444,
"text": "Input: \nstring - GraphTreesGraph\npattern - aba\nOutput: \na->Graph\nb->Trees\n\nInput: \nstring - GraphGraphGraph\npattern - aaa\nOutput: \na->Graph\n\nInput: \nstring - GeeksforGeeks\npattern - GfG\nOutput: \nG->Geeks\nf->for\n\nInput: \nstring - GeeksforGeeks\npattern - GG\nOutput: \nNo solution exists"
},
{
"code": null,
"e": 27263,
"s": 26730,
"text": "We can solve this problem with the help of Backtracking. For each character in the pattern, if the character is not seen before, we consider all possible sub-strings and recurse to see if it leads to the solution or not. We maintain a map that stores sub-string mapped to a pattern character. If pattern character is seen before, we use the same sub-string present in the map. If we found a solution, for each distinct character in the pattern, we print string mapped to it using our map.Below is C++ implementation of above idea – "
},
{
"code": null,
"e": 27267,
"s": 27263,
"text": "CPP"
},
{
"code": null,
"e": 27272,
"s": 27267,
"text": "Java"
},
{
"code": null,
"e": 27280,
"s": 27272,
"text": "Python3"
},
{
"code": null,
"e": 27291,
"s": 27280,
"text": "Javascript"
},
{
"code": "// C++ program to find out if string follows// a given pattern or not#include <bits/stdc++.h>using namespace std; /* Function to find out if string follows a given pattern or not str - given string n - length of given string i - current index in input string pat - given pattern m - length of given pattern j - current index in given pattern map - stores mapping between pattern and string */bool patternMatchUtil(string str, int n, int i, string pat, int m, int j, unordered_map<char, string>& map){ // If both string and pattern reach their end if (i == n && j == m) return true; // If either string or pattern reach their end if (i == n || j == m) return false; // read next character from the pattern char ch = pat[j]; // if character is seen before if (map.find(ch)!= map.end()) { string s = map[ch]; int len = s.size(); // consider next len characters of str string subStr = str.substr(i, len); // if next len characters of string str // don't match with s, return false if (subStr.compare(s)) return false; // if it matches, recurse for remaining characters return patternMatchUtil(str, n, i + len, pat, m, j + 1, map); } // If character is seen for first time, try out all // remaining characters in the string for (int len = 1; len <= n - i; len++) { // consider substring that starts at position i // and spans len characters and add it to map map[ch] = str.substr(i, len); // see if it leads to the solution if (patternMatchUtil(str, n, i + len, pat, m, j + 1, map)) return true; // if not, remove ch from the map map.erase(ch); } return false;} // A wrapper over patternMatchUtil()functionbool patternMatch(string str, string pat, int n, int m){ if (n < m) return false; // create an empty hashmap unordered_map<char, string> map; // store result in a boolean variable res bool res = patternMatchUtil(str, n, 0, pat, m, 0, map); // if solution exists, print the mappings for (auto it = map.begin(); res && it != map.end(); it++) cout << it->first << \"->\" << it->second << endl; // return result return res;} // Driver codeint main(){ string str = \"GeeksforGeeks\", pat = \"GfG\"; int n = str.size(), m = pat.size(); if (!patternMatch(str, pat, n, m)) cout << \"No Solution exists\"; return 0;}",
"e": 29909,
"s": 27291,
"text": null
},
{
"code": "import java.util.HashMap;import java.util.Map; class Main{ // Function to determine if given pattern matches with a string or not public static boolean match(String str, int i, String pat, int j, Map<Character, String> map) { int n = str.length(), m = pat.length(); // base condition if (n < m) { return false; } // if both pattern and the string reaches end if (i == n && j == m) { return true; } // if either string or pattern reaches end if (i == n || j == m) { return false; } // consider next character from the pattern char curr = pat.charAt(j); // if the character is seen before if (map.containsKey(curr)) { String s = map.get(curr); int k = s.length(); // ss stores next k characters of the given string String ss; if (i + k < str.length()) { ss = str.substring(i, i + k); } else { ss = str.substring(i); } // return false if next k characters doesn't match with s if (ss.compareTo(s) != 0) { return false; } // recur for remaining characters if next k characters matches return match(str, i + k, pat, j + 1, map); } // process all remaining characters in the string if current // character is never seen before for (int k = 1; k <= n - i; k++) { // insert substring formed by next k characters of the string // into the map map.put(curr, str.substring(i, i + k)); // check if it leads to the solution if (match(str, i + k, pat, j + 1, map)) { return true; } // else backtrack - remove current character from the map map.remove(curr); } return false; } public static void main(String[] args) { // input string and pattern String str = \"GeeksforGeeks\"; String pat = \"GfG\"; // create a map to store mappings between the pattern and string Map<Character, String> map = new HashMap<>(); // check for solution if (match(str, 0, pat, 0, map)) { for (Map.Entry<Character, String> entry: map.entrySet()) { System.out.println(entry.getKey() + \"->\" + entry.getValue()); } } else { System.out.println(\"Solution doesn't exist\"); } }} //This code is contributed by Priyadarshini Kumari",
"e": 32235,
"s": 29909,
"text": null
},
{
"code": "# Function to determine if given pattern matches with a string or notdef match(str, pat, dict, i=0, j=0): n = len(str) m = len(pat) # base condition if n < m: return False # if both pattern and the string reaches end if i == n and j == m: return True # if either string or pattern reaches end if i == n or j == m: return False # consider next character from the pattern curr = pat[j] # if the character is seen before if curr in dict: s = dict[curr] k = len(s) # ss stores next k characters of the given string if i + k < len(str): ss = str[i:i + k] else: ss = str[i:] # return false if next k characters doesn't match with s if ss != s: return False # recur for remaining characters if next k characters matches return match(str, pat, dict, i + k, j + 1) # process all remaining characters in the string if current # character is never seen before for k in range(1, n - i + 1): # insert substring formed by next k characters of the string # into the dictionary dict[curr] = str[i:i + k] # check if it leads to the solution if match(str, pat, dict, i + k, j + 1): return True # else backtrack - remove current character from the dictionary dict.pop(curr) return False if __name__ == '__main__': # input string and pattern str = \"GeeksforGeeks\" pat = \"GfG\" # create a dictionary to store mappings between the pattern and string dict = {} # check for solution if match(str, pat, dict): print(dict) else: print(\"Solution doesn't exist\") # This code is contributed by Priyadarshini Kumari",
"e": 34002,
"s": 32235,
"text": null
},
{
"code": "<script> // Javascript program to find out if string follows// a given pattern or not /* Function to find out if string follows a given pattern or not str - given string n - length of given string i - current index in input string pat - given pattern m - length of given pattern j - current index in given pattern map - stores mapping between pattern and string */function patternMatchUtil(str, n, i, pat, m, j, map) { // If both string and pattern reach their end if (i == n && j == m) return true; // If either string or pattern reach their end if (i == n || j == m) return false; // read next character from the pattern let ch = pat[j]; // if character is seen before if (map.has(ch)) { let s = map.get(ch); let len = s.length; // consider next len characters of str let subStr = str.substr(i, len); // if next len characters of string str // don't match with s, return false if (subStr != s) return false; // if it matches, recurse for remaining characters return patternMatchUtil(str, n, i + len, pat, m, j + 1, map); } // If character is seen for first time, try out all // remaining characters in the string for (let len = 1; len <= n - i; len++) { // consider substring that starts at position i // and spans len characters and add it to map map.set(ch, str.substr(i, len)); // see if it leads to the solution if (patternMatchUtil(str, n, i + len, pat, m, j + 1, map)) return true; // if not, remove ch from the map map.delete(ch); } return false;} // A wrapper over patternMatchUtil()functionfunction patternMatch(str, pat, n, m) { if (n < m) return false; // create an empty hashmap let map = new Map(); // store result in a boolean variable res let res = patternMatchUtil(str, n, 0, pat, m, 0, map); // if solution exists, print the mappings console.log(map) for (it of [...map.keys()].reverse()) document.write(it + \"->\" + map.get(it) + \"<br>\"); // return result return res;} // Driver codelet str = \"GeeksforGeeks\", pat = \"GfG\"; let n = str.lengthlet m = pat.length; if (!patternMatch(str, pat, n, m)) document.write(\"No Solution exists\"); // This code is contributed by saurabh_jaiswal.</script>",
"e": 36409,
"s": 34002,
"text": null
},
{
"code": null,
"e": 36419,
"s": 36409,
"text": "Output: "
},
{
"code": null,
"e": 36435,
"s": 36419,
"text": "f->for\nG->Geeks"
},
{
"code": null,
"e": 36859,
"s": 36435,
"text": "This article is contributed by Aditya Goel. 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. "
},
{
"code": null,
"e": 36865,
"s": 36859,
"text": "pawki"
},
{
"code": null,
"e": 36882,
"s": 36865,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 36895,
"s": 36882,
"text": "Backtracking"
},
{
"code": null,
"e": 36908,
"s": 36895,
"text": "Backtracking"
},
{
"code": null,
"e": 37006,
"s": 36908,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37034,
"s": 37006,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 37070,
"s": 37034,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 37123,
"s": 37070,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 37151,
"s": 37123,
"text": "Subset Sum | Backtracking-4"
},
{
"code": null,
"e": 37184,
"s": 37151,
"text": "Backtracking to find all subsets"
},
{
"code": null,
"e": 37202,
"s": 37184,
"text": "Combinational Sum"
},
{
"code": null,
"e": 37245,
"s": 37202,
"text": "Print all permutations of a string in Java"
},
{
"code": null,
"e": 37307,
"s": 37245,
"text": "Travelling Salesman Problem implementation using BackTracking"
},
{
"code": null,
"e": 37323,
"s": 37307,
"text": "8 queen problem"
}
] |
Data Mining - Mining Text Data | Text databases consist of huge collection of documents. They collect these information from several sources such as news articles, books, digital libraries, e-mail messages, web pages, etc. Due to increase in the amount of information, the text databases are growing rapidly. In many of the text databases, the data is semi-structured.
For example, a document may contain a few structured fields, such as title, author, publishing_date, etc. But along with the structure data, the document also contains unstructured text components, such as abstract and contents. Without knowing what could be in the documents, it is difficult to formulate effective queries for analyzing and extracting useful information from the data. Users require tools to compare the documents and rank their importance and relevance. Therefore, text mining has become popular and an essential theme in data mining.
Information retrieval deals with the retrieval of information from a large number of text-based documents. Some of the database systems are not usually present in information retrieval systems because both handle different kinds of data. Examples of information retrieval system include −
Online Library catalogue system
Online Document Management Systems
Web Search Systems etc.
Note − The main problem in an information retrieval system is to locate relevant documents in a document collection based on a user's query. This kind of user's query consists of some keywords describing an information need.
In such search problems, the user takes an initiative to pull relevant information out from a collection. This is appropriate when the user has ad-hoc information need, i.e., a short-term need. But if the user has a long-term information need, then the retrieval system can also take an initiative to push any newly arrived information item to the user.
This kind of access to information is called Information Filtering. And the corresponding systems are known as Filtering Systems or Recommender Systems.
We need to check the accuracy of a system when it retrieves a number of documents on the basis of user's input. Let the set of documents relevant to a query be denoted as {Relevant} and the set of retrieved document as {Retrieved}. The set of documents that are relevant and retrieved can be denoted as {Relevant} ∩ {Retrieved}. This can be shown in the form of a Venn diagram as follows −
There are three fundamental measures for assessing the quality of text retrieval −
Precision
Recall
F-score
Precision is the percentage of retrieved documents that are in fact relevant to the query. Precision can be defined as −
Precision= |{Relevant} ∩ {Retrieved}| / |{Retrieved}|
Recall is the percentage of documents that are relevant to the query and were in fact retrieved. Recall is defined as −
Recall = |{Relevant} ∩ {Retrieved}| / |{Relevant}|
F-score is the commonly used trade-off. The information retrieval system often needs to trade-off for precision or vice versa. F-score is defined as harmonic mean of recall or precision as follows −
F-score = recall x precision / (recall + precision) / 2
42 Lectures
1.5 hours
Ravi Kiran
141 Lectures
13 hours
Arnab Chakraborty
26 Lectures
8.5 hours
Parth Panjabi
65 Lectures
6 hours
Arnab Chakraborty
75 Lectures
13 hours
Eduonix Learning Solutions
64 Lectures
10.5 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2446,
"s": 2110,
"text": "Text databases consist of huge collection of documents. They collect these information from several sources such as news articles, books, digital libraries, e-mail messages, web pages, etc. Due to increase in the amount of information, the text databases are growing rapidly. In many of the text databases, the data is semi-structured."
},
{
"code": null,
"e": 3000,
"s": 2446,
"text": "For example, a document may contain a few structured fields, such as title, author, publishing_date, etc. But along with the structure data, the document also contains unstructured text components, such as abstract and contents. Without knowing what could be in the documents, it is difficult to formulate effective queries for analyzing and extracting useful information from the data. Users require tools to compare the documents and rank their importance and relevance. Therefore, text mining has become popular and an essential theme in data mining."
},
{
"code": null,
"e": 3289,
"s": 3000,
"text": "Information retrieval deals with the retrieval of information from a large number of text-based documents. Some of the database systems are not usually present in information retrieval systems because both handle different kinds of data. Examples of information retrieval system include −"
},
{
"code": null,
"e": 3321,
"s": 3289,
"text": "Online Library catalogue system"
},
{
"code": null,
"e": 3356,
"s": 3321,
"text": "Online Document Management Systems"
},
{
"code": null,
"e": 3380,
"s": 3356,
"text": "Web Search Systems etc."
},
{
"code": null,
"e": 3605,
"s": 3380,
"text": "Note − The main problem in an information retrieval system is to locate relevant documents in a document collection based on a user's query. This kind of user's query consists of some keywords describing an information need."
},
{
"code": null,
"e": 3959,
"s": 3605,
"text": "In such search problems, the user takes an initiative to pull relevant information out from a collection. This is appropriate when the user has ad-hoc information need, i.e., a short-term need. But if the user has a long-term information need, then the retrieval system can also take an initiative to push any newly arrived information item to the user."
},
{
"code": null,
"e": 4112,
"s": 3959,
"text": "This kind of access to information is called Information Filtering. And the corresponding systems are known as Filtering Systems or Recommender Systems."
},
{
"code": null,
"e": 4502,
"s": 4112,
"text": "We need to check the accuracy of a system when it retrieves a number of documents on the basis of user's input. Let the set of documents relevant to a query be denoted as {Relevant} and the set of retrieved document as {Retrieved}. The set of documents that are relevant and retrieved can be denoted as {Relevant} ∩ {Retrieved}. This can be shown in the form of a Venn diagram as follows −"
},
{
"code": null,
"e": 4585,
"s": 4502,
"text": "There are three fundamental measures for assessing the quality of text retrieval −"
},
{
"code": null,
"e": 4595,
"s": 4585,
"text": "Precision"
},
{
"code": null,
"e": 4602,
"s": 4595,
"text": "Recall"
},
{
"code": null,
"e": 4610,
"s": 4602,
"text": "F-score"
},
{
"code": null,
"e": 4731,
"s": 4610,
"text": "Precision is the percentage of retrieved documents that are in fact relevant to the query. Precision can be defined as −"
},
{
"code": null,
"e": 4787,
"s": 4731,
"text": "Precision= |{Relevant} ∩ {Retrieved}| / |{Retrieved}|\n"
},
{
"code": null,
"e": 4907,
"s": 4787,
"text": "Recall is the percentage of documents that are relevant to the query and were in fact retrieved. Recall is defined as −"
},
{
"code": null,
"e": 4960,
"s": 4907,
"text": "Recall = |{Relevant} ∩ {Retrieved}| / |{Relevant}|\n"
},
{
"code": null,
"e": 5159,
"s": 4960,
"text": "F-score is the commonly used trade-off. The information retrieval system often needs to trade-off for precision or vice versa. F-score is defined as harmonic mean of recall or precision as follows −"
},
{
"code": null,
"e": 5216,
"s": 5159,
"text": "F-score = recall x precision / (recall + precision) / 2\n"
},
{
"code": null,
"e": 5251,
"s": 5216,
"text": "\n 42 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5263,
"s": 5251,
"text": " Ravi Kiran"
},
{
"code": null,
"e": 5298,
"s": 5263,
"text": "\n 141 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5317,
"s": 5298,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5352,
"s": 5317,
"text": "\n 26 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5367,
"s": 5352,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 5400,
"s": 5367,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5419,
"s": 5400,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5453,
"s": 5419,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5481,
"s": 5453,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5517,
"s": 5481,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5545,
"s": 5517,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5552,
"s": 5545,
"text": " Print"
},
{
"code": null,
"e": 5563,
"s": 5552,
"text": " Add Notes"
}
] |
MySQL count(*) from multiple tables? | To achieve this for multiple tables, use the UNION ALL.
The syntax is as follows
select sum(variableName.aliasName)
from
(
select count(*) as yourAliasName from yourTableName1
UNION ALL
select count(*) as yourAliasName from yourTableName2
) yourVariableName;
Let us implement the above syntax. Here, I am using the sample database which has more tables.
The two tables we are using are
userdemo
wheredemo
Here is the query to display all records of both the tables. The query is as follows to display records from table ‘userdemo’.
mysql> select *from userdemo;
The following is the output
+--------+----------+------------------+
| UserId | UserName | RegisteredCourse |
+--------+----------+------------------+
| 1 | John | Java |
| 2 | Larry | C |
| 3 | Carol | C++ |
| 4 | Mike | C# |
+--------+----------+------------------+
4 rows in set (0.08 sec)
The query is as follows to display records from table ‘wheredemo’.
mysql> select *from wheredemo;
The following is the output
+------+---------+
| Id | Name |
+------+---------+
| 101 | Maxwell |
| 110 | David |
| 1000 | Carol |
| 1100 | Bob |
| 115 | Sam |
+------+---------+
5 rows in set (0.20 sec)
Here is the query to implement count(*) from both the above tables
mysql> select sum(tbl.EachTableCount)
-> from
-> (
-> select count(*) as EachTableCount from userdemo
-> UNION ALL
-> select count(*) as EachTableCount from wheredemo
-> )tbl;
The following is the output
+-------------------------+
| sum(tbl.EachTableCount) |
+-------------------------+
| 9 |
+-------------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1118,
"s": 1062,
"text": "To achieve this for multiple tables, use the UNION ALL."
},
{
"code": null,
"e": 1143,
"s": 1118,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1336,
"s": 1143,
"text": "select sum(variableName.aliasName)\nfrom\n (\n select count(*) as yourAliasName from yourTableName1\n UNION ALL\n select count(*) as yourAliasName from yourTableName2\n ) yourVariableName;"
},
{
"code": null,
"e": 1431,
"s": 1336,
"text": "Let us implement the above syntax. Here, I am using the sample database which has more tables."
},
{
"code": null,
"e": 1463,
"s": 1431,
"text": "The two tables we are using are"
},
{
"code": null,
"e": 1472,
"s": 1463,
"text": "userdemo"
},
{
"code": null,
"e": 1482,
"s": 1472,
"text": "wheredemo"
},
{
"code": null,
"e": 1609,
"s": 1482,
"text": "Here is the query to display all records of both the tables. The query is as follows to display records from table ‘userdemo’."
},
{
"code": null,
"e": 1639,
"s": 1609,
"text": "mysql> select *from userdemo;"
},
{
"code": null,
"e": 1667,
"s": 1639,
"text": "The following is the output"
},
{
"code": null,
"e": 2020,
"s": 1667,
"text": "+--------+----------+------------------+\n| UserId | UserName | RegisteredCourse |\n+--------+----------+------------------+\n| 1 | John | Java |\n| 2 | Larry | C |\n| 3 | Carol | C++ |\n| 4 | Mike | C# |\n+--------+----------+------------------+\n4 rows in set (0.08 sec)"
},
{
"code": null,
"e": 2087,
"s": 2020,
"text": "The query is as follows to display records from table ‘wheredemo’."
},
{
"code": null,
"e": 2118,
"s": 2087,
"text": "mysql> select *from wheredemo;"
},
{
"code": null,
"e": 2146,
"s": 2118,
"text": "The following is the output"
},
{
"code": null,
"e": 2342,
"s": 2146,
"text": "+------+---------+\n| Id | Name |\n+------+---------+\n| 101 | Maxwell |\n| 110 | David |\n| 1000 | Carol |\n| 1100 | Bob |\n| 115 | Sam |\n+------+---------+\n5 rows in set (0.20 sec)"
},
{
"code": null,
"e": 2409,
"s": 2342,
"text": "Here is the query to implement count(*) from both the above tables"
},
{
"code": null,
"e": 2603,
"s": 2409,
"text": "mysql> select sum(tbl.EachTableCount)\n -> from\n -> (\n -> select count(*) as EachTableCount from userdemo\n -> UNION ALL\n -> select count(*) as EachTableCount from wheredemo\n -> )tbl;"
},
{
"code": null,
"e": 2631,
"s": 2603,
"text": "The following is the output"
},
{
"code": null,
"e": 2795,
"s": 2631,
"text": "+-------------------------+\n| sum(tbl.EachTableCount) |\n+-------------------------+\n| 9 |\n+-------------------------+\n1 row in set (0.00 sec)"
}
] |
The Basics of Hash Table. Hash table is fundamentally a data... | by billydharmawan | Towards Data Science | Those of us who’ve lived reasonably long enough must know or at least have seen a yellow page. Yup! You’re right. It is the thick yellow book containing directories of businesses and their phone numbers. This enables us to search for a business that sells what we need and contact them.
(I don’t think Gen Z and the next generations after that would come to know about this thick yellow book. 😆)
A directory of phone number is usually alphabetically ordered, so we know where we can start our search. Once we find the business name that we want, we can grab the phone number and call them. You get the idea. 💡
What if I tell you that a yellow page or a phone book is an implementation of hash table? You bet! 🐴
Hash table is essentially an array coupled with a hash function. It is commonly used to store key-value data, for example, businesses and their phone number, students and their grades, items and their prices and many more, in an unordered fashion.
Each key has to be unique and is mapped to a specific index in the array and its value stored in that location. 🔑 ➡🚪 Notice that because of this, insertion, search and delete operations are ⚡️ fast. In fact, the average time complexity of insertion, search and delete operations of hash table is constant time or O(1).
Therefore, when you require a data structure that offers fast insertion, lookup and deletion, hash table is one of the go-to option. This can be really useful when you have a large amount of relational key-value data, e.g. in Data Science and/or Machine Learning algorithm.
Hash function is what makes hash table a powerful and useful data structure. A hash function takes a piece of data, or usually referred to as a key, and returns a hash code as an output. This hash code, which is an integer, is then mapped to an index in the array, where the value will be stored.
One of the reasons why the hash code is not associated directly with an index in the array is because the value of the hash code can be very large, e.g. 10000000, whilst the amount of key-value data we want to store (or the size of the array that forms our hash table) might not necessarily be that big.
A simple way to map the hash code to an index in the array is by applying a modulo operation with respect to the size of the hash table.
index = hashCode(String key) % length(array)
Let’s take a look at an example of a hash function.
function int hashCode(String s) { return s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]}
This is the hash function used by Java String object, where s is the array of characters of the String object, e.g. s[0] is the first character, and n is the length of the String object. Let’s see it in action.
hashCode("Apple") // 63476538hashCode("Costco") // 2024204569hashCode("Ikea") // 2280798hashCode("Snowflake") // 1973786418
Notice from the few examples ☝️ that the hash function outputs different hash code values for each String object. As mentioned earlier, each key is expected to be unique, so the hash function is also expected to produce unique hash code for each key. This will allow a better chance for the key-value data to be uniformly distributed across the hash table.
Furthermore, let’s map the hash codes to the indices in the array.
function int mapToIndex(int hashCode, int arraySize) { return abs(hashCode % arraySize)}// Let's assume the size of our hash table or the length of the array is 500hashTable = Array(500)mapToIndex(hashCode("Apple"), size(hashTable)) // 38mapToIndex(hashCode("Costco"), size(hashTable)) // 69mapToIndex(hashCode("Ikea"), size(hashTable)) // 298mapToIndex(hashCode("Snowflake"), size(hashTable)) // 418
As per ☝️ Apple’s data will be located at index 38, Costco’s data at index 69, Ikea’s data at index 298 and Snowflake’s data at index 418.
In the previous section, we had a look at an example of how hash function is used to determine the location of a particular key-value data in the hash table. Now, let’s take a look at another example of a hash function.
function int hashCode(int i) { return i % 5}
This hash function takes an integer as input and apply modulo operation to output the hash code. Now, let’s test it out with a few integer input.
hashCode(1) // 1hashCode(5) // 0hashCode(11) // 1
Wait a second. Isn’t hash code supposed to be different for each key? Well, in this case, the hash function we chose is probably not ideal for the possible keys that we might have. It produces the same hash code for different input values, i.e. input values of 1 and 11 will return a hash code of 1, which means they will be mapped to the same location in the array. This phenomenon is called collision.
There are two common ways used to deal with collisions in hash table:
linear probing
separate chaining
In linear probing, we deal with collisions in hash tables by searching for the nearest available space in the array after the supposed location as determined by the hash function. Let’s imagine this using the collision example from the previous section, where input values of 1 and 11 result in the same hash code.
Let’s say we insert key-value data of 1-Apple into our hash table. The hash function returns hash code of 1, and let’s assume it is mapped to index 1 in the array. Now, index 1 in the array contains key-value data of 1-Apple.
Next, we want to add key-value data of 11-Orange into the hash table. The hash function returns hash code of 1, which is also mapped to index 1, however, by this time, the block in index 1 of the array has already been occupied by key-value data 1-Apple.
In this case, linear probing will look for the closest free location in the array and store the key-value data 11-Orange there. The same is also true when we want to retrieve data from the hash table where the key equals 11. Linear probing will find key-value data 1-Apple first, then keeps searching in the adjacent locations until it finds a block in the array that matches the key 11 or an empty block, which indicates the key 11 does not exist.
When separate chaining method is used, hash table will store key-value data in linked lists. This means that each block in the array contains a linked list, not just a single key-value data.
So, at the time of collision, instead of looking for the next free block in the array like what linear probing does, separate chaining adds the key-value data into the linked list.
Again, taking the collision example from the previous section, separate chaining will store both 1-Apple and 11-Orange key-value pairs in a linked list at index 1 of the array, where the head of the linked list would be 1-Apple as it was added before 11-Orange.
Based on what we have learnt so far, we can deduce that a good hash function should have the following properties.
A good hash function should make use of every element of the data in order to increase the number of possible hash codes.
Let’s take a look at the following example.
function int hashCode(String k) { String s = k.substring(start=0, end=2) return s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]}
This hash function accepts an input data, which has String type, takes the first 3 characters and apply the hash function used by Java String object. You can imagine that collisions will occur for data that have the same first three characters, e.g. apple and application.
Not all piece of information are used to generate the hash code in this case. As you can see, there’s a higher chance of collision because there’s less available possible hash codes.
One of the reasons why we would use hash table is its speed of insertion, lookup and deletion. Every operation relies on the hash function to get the hash code and hence, the position of data in the array.
So, we want to make sure that our hash function is super fast in order to provide the speed that we are looking for in hash table.
This means we should avoid hash function that uses complex or slow operation and aim for speedy, simple and yet, effective operation.
It is most ideal for our hash function to uniformly distribute the data across the hash table. If the hash function does not distribute the data evenly, then there will be a higher chance for a collision to occur.
We have learned the basics of hash table, which include its structure, what hash function is and does, collisions and ways to deal with them. The next time you are faced a problem that requires speedy lookup, insertion and deletion, hash table is probably your best bet to solve it. 😺 | [
{
"code": null,
"e": 459,
"s": 172,
"text": "Those of us who’ve lived reasonably long enough must know or at least have seen a yellow page. Yup! You’re right. It is the thick yellow book containing directories of businesses and their phone numbers. This enables us to search for a business that sells what we need and contact them."
},
{
"code": null,
"e": 568,
"s": 459,
"text": "(I don’t think Gen Z and the next generations after that would come to know about this thick yellow book. 😆)"
},
{
"code": null,
"e": 782,
"s": 568,
"text": "A directory of phone number is usually alphabetically ordered, so we know where we can start our search. Once we find the business name that we want, we can grab the phone number and call them. You get the idea. 💡"
},
{
"code": null,
"e": 883,
"s": 782,
"text": "What if I tell you that a yellow page or a phone book is an implementation of hash table? You bet! 🐴"
},
{
"code": null,
"e": 1131,
"s": 883,
"text": "Hash table is essentially an array coupled with a hash function. It is commonly used to store key-value data, for example, businesses and their phone number, students and their grades, items and their prices and many more, in an unordered fashion."
},
{
"code": null,
"e": 1450,
"s": 1131,
"text": "Each key has to be unique and is mapped to a specific index in the array and its value stored in that location. 🔑 ➡🚪 Notice that because of this, insertion, search and delete operations are ⚡️ fast. In fact, the average time complexity of insertion, search and delete operations of hash table is constant time or O(1)."
},
{
"code": null,
"e": 1724,
"s": 1450,
"text": "Therefore, when you require a data structure that offers fast insertion, lookup and deletion, hash table is one of the go-to option. This can be really useful when you have a large amount of relational key-value data, e.g. in Data Science and/or Machine Learning algorithm."
},
{
"code": null,
"e": 2021,
"s": 1724,
"text": "Hash function is what makes hash table a powerful and useful data structure. A hash function takes a piece of data, or usually referred to as a key, and returns a hash code as an output. This hash code, which is an integer, is then mapped to an index in the array, where the value will be stored."
},
{
"code": null,
"e": 2325,
"s": 2021,
"text": "One of the reasons why the hash code is not associated directly with an index in the array is because the value of the hash code can be very large, e.g. 10000000, whilst the amount of key-value data we want to store (or the size of the array that forms our hash table) might not necessarily be that big."
},
{
"code": null,
"e": 2462,
"s": 2325,
"text": "A simple way to map the hash code to an index in the array is by applying a modulo operation with respect to the size of the hash table."
},
{
"code": null,
"e": 2507,
"s": 2462,
"text": "index = hashCode(String key) % length(array)"
},
{
"code": null,
"e": 2559,
"s": 2507,
"text": "Let’s take a look at an example of a hash function."
},
{
"code": null,
"e": 2647,
"s": 2559,
"text": "function int hashCode(String s) { return s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]}"
},
{
"code": null,
"e": 2858,
"s": 2647,
"text": "This is the hash function used by Java String object, where s is the array of characters of the String object, e.g. s[0] is the first character, and n is the length of the String object. Let’s see it in action."
},
{
"code": null,
"e": 2982,
"s": 2858,
"text": "hashCode(\"Apple\") // 63476538hashCode(\"Costco\") // 2024204569hashCode(\"Ikea\") // 2280798hashCode(\"Snowflake\") // 1973786418"
},
{
"code": null,
"e": 3339,
"s": 2982,
"text": "Notice from the few examples ☝️ that the hash function outputs different hash code values for each String object. As mentioned earlier, each key is expected to be unique, so the hash function is also expected to produce unique hash code for each key. This will allow a better chance for the key-value data to be uniformly distributed across the hash table."
},
{
"code": null,
"e": 3406,
"s": 3339,
"text": "Furthermore, let’s map the hash codes to the indices in the array."
},
{
"code": null,
"e": 3808,
"s": 3406,
"text": "function int mapToIndex(int hashCode, int arraySize) { return abs(hashCode % arraySize)}// Let's assume the size of our hash table or the length of the array is 500hashTable = Array(500)mapToIndex(hashCode(\"Apple\"), size(hashTable)) // 38mapToIndex(hashCode(\"Costco\"), size(hashTable)) // 69mapToIndex(hashCode(\"Ikea\"), size(hashTable)) // 298mapToIndex(hashCode(\"Snowflake\"), size(hashTable)) // 418"
},
{
"code": null,
"e": 3947,
"s": 3808,
"text": "As per ☝️ Apple’s data will be located at index 38, Costco’s data at index 69, Ikea’s data at index 298 and Snowflake’s data at index 418."
},
{
"code": null,
"e": 4167,
"s": 3947,
"text": "In the previous section, we had a look at an example of how hash function is used to determine the location of a particular key-value data in the hash table. Now, let’s take a look at another example of a hash function."
},
{
"code": null,
"e": 4213,
"s": 4167,
"text": "function int hashCode(int i) { return i % 5}"
},
{
"code": null,
"e": 4359,
"s": 4213,
"text": "This hash function takes an integer as input and apply modulo operation to output the hash code. Now, let’s test it out with a few integer input."
},
{
"code": null,
"e": 4409,
"s": 4359,
"text": "hashCode(1) // 1hashCode(5) // 0hashCode(11) // 1"
},
{
"code": null,
"e": 4813,
"s": 4409,
"text": "Wait a second. Isn’t hash code supposed to be different for each key? Well, in this case, the hash function we chose is probably not ideal for the possible keys that we might have. It produces the same hash code for different input values, i.e. input values of 1 and 11 will return a hash code of 1, which means they will be mapped to the same location in the array. This phenomenon is called collision."
},
{
"code": null,
"e": 4883,
"s": 4813,
"text": "There are two common ways used to deal with collisions in hash table:"
},
{
"code": null,
"e": 4898,
"s": 4883,
"text": "linear probing"
},
{
"code": null,
"e": 4916,
"s": 4898,
"text": "separate chaining"
},
{
"code": null,
"e": 5231,
"s": 4916,
"text": "In linear probing, we deal with collisions in hash tables by searching for the nearest available space in the array after the supposed location as determined by the hash function. Let’s imagine this using the collision example from the previous section, where input values of 1 and 11 result in the same hash code."
},
{
"code": null,
"e": 5457,
"s": 5231,
"text": "Let’s say we insert key-value data of 1-Apple into our hash table. The hash function returns hash code of 1, and let’s assume it is mapped to index 1 in the array. Now, index 1 in the array contains key-value data of 1-Apple."
},
{
"code": null,
"e": 5712,
"s": 5457,
"text": "Next, we want to add key-value data of 11-Orange into the hash table. The hash function returns hash code of 1, which is also mapped to index 1, however, by this time, the block in index 1 of the array has already been occupied by key-value data 1-Apple."
},
{
"code": null,
"e": 6161,
"s": 5712,
"text": "In this case, linear probing will look for the closest free location in the array and store the key-value data 11-Orange there. The same is also true when we want to retrieve data from the hash table where the key equals 11. Linear probing will find key-value data 1-Apple first, then keeps searching in the adjacent locations until it finds a block in the array that matches the key 11 or an empty block, which indicates the key 11 does not exist."
},
{
"code": null,
"e": 6352,
"s": 6161,
"text": "When separate chaining method is used, hash table will store key-value data in linked lists. This means that each block in the array contains a linked list, not just a single key-value data."
},
{
"code": null,
"e": 6533,
"s": 6352,
"text": "So, at the time of collision, instead of looking for the next free block in the array like what linear probing does, separate chaining adds the key-value data into the linked list."
},
{
"code": null,
"e": 6795,
"s": 6533,
"text": "Again, taking the collision example from the previous section, separate chaining will store both 1-Apple and 11-Orange key-value pairs in a linked list at index 1 of the array, where the head of the linked list would be 1-Apple as it was added before 11-Orange."
},
{
"code": null,
"e": 6910,
"s": 6795,
"text": "Based on what we have learnt so far, we can deduce that a good hash function should have the following properties."
},
{
"code": null,
"e": 7032,
"s": 6910,
"text": "A good hash function should make use of every element of the data in order to increase the number of possible hash codes."
},
{
"code": null,
"e": 7076,
"s": 7032,
"text": "Let’s take a look at the following example."
},
{
"code": null,
"e": 7204,
"s": 7076,
"text": "function int hashCode(String k) { String s = k.substring(start=0, end=2) return s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]}"
},
{
"code": null,
"e": 7477,
"s": 7204,
"text": "This hash function accepts an input data, which has String type, takes the first 3 characters and apply the hash function used by Java String object. You can imagine that collisions will occur for data that have the same first three characters, e.g. apple and application."
},
{
"code": null,
"e": 7660,
"s": 7477,
"text": "Not all piece of information are used to generate the hash code in this case. As you can see, there’s a higher chance of collision because there’s less available possible hash codes."
},
{
"code": null,
"e": 7866,
"s": 7660,
"text": "One of the reasons why we would use hash table is its speed of insertion, lookup and deletion. Every operation relies on the hash function to get the hash code and hence, the position of data in the array."
},
{
"code": null,
"e": 7997,
"s": 7866,
"text": "So, we want to make sure that our hash function is super fast in order to provide the speed that we are looking for in hash table."
},
{
"code": null,
"e": 8131,
"s": 7997,
"text": "This means we should avoid hash function that uses complex or slow operation and aim for speedy, simple and yet, effective operation."
},
{
"code": null,
"e": 8345,
"s": 8131,
"text": "It is most ideal for our hash function to uniformly distribute the data across the hash table. If the hash function does not distribute the data evenly, then there will be a higher chance for a collision to occur."
}
] |
How to Convert Loops to List Comprehensions in Python | by Soner Yıldırım | Towards Data Science | List comprehension is used for creating lists based on iterables. It can also be described as representing for and if loops with a simpler and more appealing syntax. List comprehensions are relatively faster than for loops.
The syntax of a list comprehension is actually easy to understand. However, when it comes to complex and nested operations, it might get a little tricky to figure out how to structure a list comprehension.
In such cases, writing the loop version first makes it easier to write the code for the list comprehension. We will go over several examples that demonstrate how to convert a loop-wise syntax to a list comprehension.
Let’s start with a simple example. We have a list of 5 integers and want to create a list that contains the squares of each item. Following is the for loop that performs this operation.
lst_a = [1, 2, 3, 4, 5]lst_b = []for i in lst_a: lst_b.append(i**2)print(lst_b)[1, 4, 9, 16, 25]
The list comprehension version of the same task:
lst_b = [i**2 for i in lst_a]print(lst_b)[1, 4, 9, 16, 25]
We already notice how the list comprehension simplifies the syntax. It serves as a powerful one-liner. The figure below illustrates the conversion.
The list comprehension starts with the final operation. Then, we place the line that defines the for loop.
The operation placed in a list comprehension can be more complex than a single math operation. Consider the following list of names.
names = ["John Doe", "Jane Doe", "Mike Fence"]
We would like to create a list that contains only the first names. Here is the loop that accomplishes this task:
first_names = []for name in names: first_names.append(name.split(" ")[0])print(first_names)['John', 'Jane', 'Mike']
We first split the name string at the space character and then take the first word. It is quite similar to the previous example to convert this loop to a list comprehension.
first_names = [name.split(" ")[0] for name in names]print(first_names)['John', 'Jane', 'Mike']
We can also place conditional statements in a list comprehension. Let’s repeat the previous example but with a condition. The list of first names will only contain names that start with the letter j.
first_names = []for name in names: if name.startswith("J"): first_names.append(name.split(" ")[0])print(first_names)['John', 'Jane']
We use the startswith method to apply the desired condition. The same condition is added to a list comprehension as follows.
first_names = [name.split(" ")[0] for name in names if name.startswith("J")]print(first_names)['John', 'Jane']
The following figure demonstrated the conversion.
We put the final operation at the beginning of the list comprehension. Then, we follow the lines from the top to the bottom as indicated with the colored box.
If you follow this logic, you can easily convert complex loops to a list comprehension. Let’s finish up with a slightly more complicated examples. Consider the following list of 3 lists.
lst_a = [[4,3,5], [1,5,3,8], [1,6,2,4]]
We want to create a new list that contains the all the numbers from the nested lists that are greater than 3.
mylist = []for lst in lst_a: for item in lst: if item > 3: mylist.append(item)print(mylist)[4, 5, 5, 8, 6, 4]
The list comprehension that performs this task is:
mylist = [item for lst in lst_a for item in lst if item > 3]
Although this loop is more complicated than the previous ones, the logic to convert it to a list comprehension is the same.
It starts with the last operation in the loop. Then, we follow the loop from the top to the bottom. Each line in the loop is placed in the comprehension consecutively.
List comprehensions are faster than loops in general. It achieves to be faster by loading the entire list into the memory.
There is a downside of this approach when working with large lists (e.g. 1 billion elements). It may cause your computer to crash due to the extreme amount of memory requirement.
A better alternative for such large lists is using a generator that does not actually create a large data structure in memory. A generator creates items as they are called.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 270,
"s": 46,
"text": "List comprehension is used for creating lists based on iterables. It can also be described as representing for and if loops with a simpler and more appealing syntax. List comprehensions are relatively faster than for loops."
},
{
"code": null,
"e": 476,
"s": 270,
"text": "The syntax of a list comprehension is actually easy to understand. However, when it comes to complex and nested operations, it might get a little tricky to figure out how to structure a list comprehension."
},
{
"code": null,
"e": 693,
"s": 476,
"text": "In such cases, writing the loop version first makes it easier to write the code for the list comprehension. We will go over several examples that demonstrate how to convert a loop-wise syntax to a list comprehension."
},
{
"code": null,
"e": 879,
"s": 693,
"text": "Let’s start with a simple example. We have a list of 5 integers and want to create a list that contains the squares of each item. Following is the for loop that performs this operation."
},
{
"code": null,
"e": 978,
"s": 879,
"text": "lst_a = [1, 2, 3, 4, 5]lst_b = []for i in lst_a: lst_b.append(i**2)print(lst_b)[1, 4, 9, 16, 25]"
},
{
"code": null,
"e": 1027,
"s": 978,
"text": "The list comprehension version of the same task:"
},
{
"code": null,
"e": 1086,
"s": 1027,
"text": "lst_b = [i**2 for i in lst_a]print(lst_b)[1, 4, 9, 16, 25]"
},
{
"code": null,
"e": 1234,
"s": 1086,
"text": "We already notice how the list comprehension simplifies the syntax. It serves as a powerful one-liner. The figure below illustrates the conversion."
},
{
"code": null,
"e": 1341,
"s": 1234,
"text": "The list comprehension starts with the final operation. Then, we place the line that defines the for loop."
},
{
"code": null,
"e": 1474,
"s": 1341,
"text": "The operation placed in a list comprehension can be more complex than a single math operation. Consider the following list of names."
},
{
"code": null,
"e": 1521,
"s": 1474,
"text": "names = [\"John Doe\", \"Jane Doe\", \"Mike Fence\"]"
},
{
"code": null,
"e": 1634,
"s": 1521,
"text": "We would like to create a list that contains only the first names. Here is the loop that accomplishes this task:"
},
{
"code": null,
"e": 1752,
"s": 1634,
"text": "first_names = []for name in names: first_names.append(name.split(\" \")[0])print(first_names)['John', 'Jane', 'Mike']"
},
{
"code": null,
"e": 1926,
"s": 1752,
"text": "We first split the name string at the space character and then take the first word. It is quite similar to the previous example to convert this loop to a list comprehension."
},
{
"code": null,
"e": 2021,
"s": 1926,
"text": "first_names = [name.split(\" \")[0] for name in names]print(first_names)['John', 'Jane', 'Mike']"
},
{
"code": null,
"e": 2221,
"s": 2021,
"text": "We can also place conditional statements in a list comprehension. Let’s repeat the previous example but with a condition. The list of first names will only contain names that start with the letter j."
},
{
"code": null,
"e": 2361,
"s": 2221,
"text": "first_names = []for name in names: if name.startswith(\"J\"): first_names.append(name.split(\" \")[0])print(first_names)['John', 'Jane']"
},
{
"code": null,
"e": 2486,
"s": 2361,
"text": "We use the startswith method to apply the desired condition. The same condition is added to a list comprehension as follows."
},
{
"code": null,
"e": 2597,
"s": 2486,
"text": "first_names = [name.split(\" \")[0] for name in names if name.startswith(\"J\")]print(first_names)['John', 'Jane']"
},
{
"code": null,
"e": 2647,
"s": 2597,
"text": "The following figure demonstrated the conversion."
},
{
"code": null,
"e": 2806,
"s": 2647,
"text": "We put the final operation at the beginning of the list comprehension. Then, we follow the lines from the top to the bottom as indicated with the colored box."
},
{
"code": null,
"e": 2993,
"s": 2806,
"text": "If you follow this logic, you can easily convert complex loops to a list comprehension. Let’s finish up with a slightly more complicated examples. Consider the following list of 3 lists."
},
{
"code": null,
"e": 3033,
"s": 2993,
"text": "lst_a = [[4,3,5], [1,5,3,8], [1,6,2,4]]"
},
{
"code": null,
"e": 3143,
"s": 3033,
"text": "We want to create a new list that contains the all the numbers from the nested lists that are greater than 3."
},
{
"code": null,
"e": 3268,
"s": 3143,
"text": "mylist = []for lst in lst_a: for item in lst: if item > 3: mylist.append(item)print(mylist)[4, 5, 5, 8, 6, 4]"
},
{
"code": null,
"e": 3319,
"s": 3268,
"text": "The list comprehension that performs this task is:"
},
{
"code": null,
"e": 3380,
"s": 3319,
"text": "mylist = [item for lst in lst_a for item in lst if item > 3]"
},
{
"code": null,
"e": 3504,
"s": 3380,
"text": "Although this loop is more complicated than the previous ones, the logic to convert it to a list comprehension is the same."
},
{
"code": null,
"e": 3672,
"s": 3504,
"text": "It starts with the last operation in the loop. Then, we follow the loop from the top to the bottom. Each line in the loop is placed in the comprehension consecutively."
},
{
"code": null,
"e": 3795,
"s": 3672,
"text": "List comprehensions are faster than loops in general. It achieves to be faster by loading the entire list into the memory."
},
{
"code": null,
"e": 3974,
"s": 3795,
"text": "There is a downside of this approach when working with large lists (e.g. 1 billion elements). It may cause your computer to crash due to the extreme amount of memory requirement."
},
{
"code": null,
"e": 4147,
"s": 3974,
"text": "A better alternative for such large lists is using a generator that does not actually create a large data structure in memory. A generator creates items as they are called."
}
] |
How to Make a Barcode Reader in Python? - GeeksforGeeks | 07 Sep, 2021
Barcode represents data in graphical representation and machine-readable. For making Barcode Reader in Python we are using pyzbar library. Using pyzbar we can decode the one-dimensional barcode and QR-code.
This pyzbar can return 3 fields based on the barcode object:
Type: There are several kinds of barcodes are available. Which are differentiated by unique code names like CODE-128, Code-11, CODE-39, etc. If the symbol detected by pyzabr then is QRcode for that type is QR-CODE.
Data: This is data that is embedded inside the barcode. This data is of various kinds ( alphanumerical, numerical, binary, etc..) depending upon the type of barcode.
Location: This is the collection of points that are located in the code. For barcodes, these points are starting and ending line boundaries. and for QRcode, it is a list of four points corresponding to the four corners of the QR code quad.
For installation:
pip install pyzbar
pyzbar Provides the rect method to locate the barcode in the image. Rect stands for a rectangle that will give you the coordinates of the barcode. We can also decode the multiple barcodes included in one image. Using the following steps we are going to make a barcode recorder. (ensure that you are having both libraries installed)
Approach:
Import cv2.
Import decode function from pyzbar.
Take the image from the user.
Decode that image using pyzbar
Locate the barcode in the given Image
Print the data and type of image
Display located barcode.
Below is the Implementation
Python3
# Importing libraryimport cv2from pyzbar.pyzbar import decode # Make one method to decode the barcodedef BarcodeReader(image): # read the image in numpy array using cv2 img = cv2.imread(image) # Decode the barcode image detectedBarcodes = decode(img) # If not detected then print the message if not detectedBarcodes: print("Barcode Not Detected or your barcode is blank/corrupted!") else: # Traverse through all the detected barcodes in image for barcode in detectedBarcodes: # Locate the barcode position in image (x, y, w, h) = barcode.rect # Put the rectangle in image using # cv2 to heighlight the barcode cv2.rectangle(img, (x-10, y-10), (x + w+10, y + h+10), (255, 0, 0), 2) if barcode.data!="": # Print the barcode data print(barcode.data) print(barcode.type) #Display the image cv2.imshow("Image", img) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == "__main__": # Take the image from user image="Img.jpg" BarcodeReader(image)
Output:
b'GeeksForGeek-112021'
CODE128
sagartomar9927
Picked
python-utility
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 25855,
"s": 25647,
"text": "Barcode represents data in graphical representation and machine-readable. For making Barcode Reader in Python we are using pyzbar library. Using pyzbar we can decode the one-dimensional barcode and QR-code. "
},
{
"code": null,
"e": 25916,
"s": 25855,
"text": "This pyzbar can return 3 fields based on the barcode object:"
},
{
"code": null,
"e": 26131,
"s": 25916,
"text": "Type: There are several kinds of barcodes are available. Which are differentiated by unique code names like CODE-128, Code-11, CODE-39, etc. If the symbol detected by pyzabr then is QRcode for that type is QR-CODE."
},
{
"code": null,
"e": 26297,
"s": 26131,
"text": "Data: This is data that is embedded inside the barcode. This data is of various kinds ( alphanumerical, numerical, binary, etc..) depending upon the type of barcode."
},
{
"code": null,
"e": 26537,
"s": 26297,
"text": "Location: This is the collection of points that are located in the code. For barcodes, these points are starting and ending line boundaries. and for QRcode, it is a list of four points corresponding to the four corners of the QR code quad."
},
{
"code": null,
"e": 26555,
"s": 26537,
"text": "For installation:"
},
{
"code": null,
"e": 26574,
"s": 26555,
"text": "pip install pyzbar"
},
{
"code": null,
"e": 26906,
"s": 26574,
"text": "pyzbar Provides the rect method to locate the barcode in the image. Rect stands for a rectangle that will give you the coordinates of the barcode. We can also decode the multiple barcodes included in one image. Using the following steps we are going to make a barcode recorder. (ensure that you are having both libraries installed)"
},
{
"code": null,
"e": 26916,
"s": 26906,
"text": "Approach:"
},
{
"code": null,
"e": 26928,
"s": 26916,
"text": "Import cv2."
},
{
"code": null,
"e": 26964,
"s": 26928,
"text": "Import decode function from pyzbar."
},
{
"code": null,
"e": 26994,
"s": 26964,
"text": "Take the image from the user."
},
{
"code": null,
"e": 27025,
"s": 26994,
"text": "Decode that image using pyzbar"
},
{
"code": null,
"e": 27063,
"s": 27025,
"text": "Locate the barcode in the given Image"
},
{
"code": null,
"e": 27096,
"s": 27063,
"text": "Print the data and type of image"
},
{
"code": null,
"e": 27121,
"s": 27096,
"text": "Display located barcode."
},
{
"code": null,
"e": 27149,
"s": 27121,
"text": "Below is the Implementation"
},
{
"code": null,
"e": 27157,
"s": 27149,
"text": "Python3"
},
{
"code": "# Importing libraryimport cv2from pyzbar.pyzbar import decode # Make one method to decode the barcodedef BarcodeReader(image): # read the image in numpy array using cv2 img = cv2.imread(image) # Decode the barcode image detectedBarcodes = decode(img) # If not detected then print the message if not detectedBarcodes: print(\"Barcode Not Detected or your barcode is blank/corrupted!\") else: # Traverse through all the detected barcodes in image for barcode in detectedBarcodes: # Locate the barcode position in image (x, y, w, h) = barcode.rect # Put the rectangle in image using # cv2 to heighlight the barcode cv2.rectangle(img, (x-10, y-10), (x + w+10, y + h+10), (255, 0, 0), 2) if barcode.data!=\"\": # Print the barcode data print(barcode.data) print(barcode.type) #Display the image cv2.imshow(\"Image\", img) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == \"__main__\": # Take the image from user image=\"Img.jpg\" BarcodeReader(image)",
"e": 28413,
"s": 27157,
"text": null
},
{
"code": null,
"e": 28421,
"s": 28413,
"text": "Output:"
},
{
"code": null,
"e": 28452,
"s": 28421,
"text": "b'GeeksForGeek-112021'\nCODE128"
},
{
"code": null,
"e": 28467,
"s": 28452,
"text": "sagartomar9927"
},
{
"code": null,
"e": 28474,
"s": 28467,
"text": "Picked"
},
{
"code": null,
"e": 28489,
"s": 28474,
"text": "python-utility"
},
{
"code": null,
"e": 28496,
"s": 28489,
"text": "Python"
},
{
"code": null,
"e": 28594,
"s": 28496,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28626,
"s": 28594,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28668,
"s": 28626,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28710,
"s": 28668,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28766,
"s": 28710,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28793,
"s": 28766,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28824,
"s": 28793,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28860,
"s": 28824,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 28889,
"s": 28860,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28911,
"s": 28889,
"text": "Defaultdict in Python"
}
] |
Maximizing Unique Pairs from two arrays - GeeksforGeeks | 10 Feb, 2022
Given two arrays of equal size N, form maximum number of pairs by using their elements, one from the first array and second from the second array, such that an element from each array is used at-most-once and the absolute difference between the selected elements used for forming a pair is less than or equal to a given element K.Examples:
Input : a[] = {3, 4, 5, 2, 1}
b[] = {6, 5, 4, 7, 15}
k = 3
Output : 4
The maximum number of pairs that can be formed
using the above 2 arrays is 4 and the corresponding
pairs are [1, 4], [2, 5], [3, 6], [4, 7], we can't
pair the remaining elements.
Other way of pairing under given constraint is
[2, 5], [3, 6], [4, 4], but count of pairs here
is 3 which is less than the result 4.
Simple Approach: By taking few examples, we can observe that if we sort both arrays. Then one by picking the closest feasible element for every element, we get the optimal answer.In this approach we first sort both the arrays and then compare each element of the first array with each element of the second array for the possible pair, if it’s possible to form a pair, we form the pair and move to check for the next possible pair for the next element of the first array.
C++
Java
Python 3
C#
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>#define ll long long intusing namespace std; // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.ll findMaxPairs(ll a[], ll b[], ll n, ll k){ sort(a, a+n); // Sorting the first array. sort(b, b+n); // Sorting the second array. // To keep track of visited elements of b[] bool flag[n]; memset(flag, false, sizeof(flag)); // For every element of a[], find a pair // for it and break as soon as a pair is // found. int result = 0; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { if (abs(a[i]-b[j])<=k && flag[j]==false) { // Increasing the count if a pair is formed. result++; /* Making the corresponding flag array element as 1 indicating the element in the second array element has been used. */ flag[j] = true; // We break the loop to make sure an // element of a[] is used only once. break; } } } return result;} // Driver codeint main(){ ll a[] = {10, 15, 20}, b[] = {17, 12, 24}; int n = sizeof(a)/sizeof(a[0]); int k = 3; cout << findMaxPairs(a, b, n, k); return 0;}
// Java implementation of above approachimport java.util.*; class solution{ // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.static int findMaxPairs(int a[], int b[], int n, int k){ Arrays.sort(a); // Sorting the first array. Arrays.sort(b); // Sorting the second array. // To keep track of visited elements of b[] boolean []flag = new boolean[n]; Arrays.fill(flag,false); // For every element of a[], find a pair // for it and break as soon as a pair is // found. int result = 0; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { if (Math.abs(a[i]-b[j])<=k && flag[j]==false) { // Increasing the count if a pair is formed. result++; /* Making the corresponding flag array element as 1 indicating the element in the second array element has been used. */ flag[j] = true; // We break the loop to make sure an // element of a[] is used only once. break; } } } return result;} // Driver codepublic static void main(String args[]){ int[] a = {10, 15, 20}; int[] b = {17, 12, 24}; int n = a.length; int k = 3; System.out.println(findMaxPairs(a, b, n, k)); }} // This code is contributed by// Shashank_Sharma
# Returns count of maximum pairs# that can be formed from a[] and# b[] under given constraints.def findMaxPairs(a, b, n, k): a.sort() # Sorting the first array. b.sort() # Sorting the second array. # To keep track of visited # elements of b[] flag = [False] * n # For every element of a[], find # a pair for it and break as soon # as a pair is found. result = 0 for i in range(n): for j in range(n): if (abs(a[i] - b[j]) <= k and flag[j] == False): # Increasing the count if # a pair is formed. result += 1 ''' Making the corresponding flag array element as 1 indicating the element in the second array element has been used. ''' flag[j] = True # We break the loop to make sure an # element of a[] is used only once. break return result # Driver codeif __name__ == "__main__": a = [10, 15, 20] b = [17, 12, 24] n = len(a) k = 3 print(findMaxPairs(a, b, n, k)) # This code is contributed# by ChitraNayal
// C# implementation of above approachusing System; class GFG{ // Returns count of maximum pairs that can // be formed from a[] and b[] under given // constraints. static int findMaxPairs(int []a, int []b, int n, int k) { Array.Sort(a); // Sorting the first array. Array.Sort(b); // Sorting the second array. // To keep track of visited elements of b[] bool []flag = new bool[n]; //Arrays.fill(flag,false); // For every element of a[], find a pair // for it and break as soon as a pair is // found. int result = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (Math.Abs(a[i] - b[j]) <= k && flag[j] == false) { // Increasing the count if a pair is formed. result++; /* Making the corresponding flag array element as 1 indicating the element in the second array element has been used. */ flag[j] = true; // We break the loop to make sure an // element of a[] is used only once. break; } } } return result; } // Driver code public static void Main() { int[] a = {10, 15, 20}; int[] b = {17, 12, 24}; int n = a.Length; int k = 3; Console.WriteLine(findMaxPairs(a, b, n, k)); }} // This code is contributed by Rajput-Ji
<script>// Javascript implementation of above approach // Returns count of maximum pairs that can // be formed from a[] and b[] under given // constraints. function findMaxPairs(a,b,n,k) { a.sort(function(c,d){return c-d;}); // Sorting the first array. b.sort(function(c,d){return c-d;}) // Sorting the second array. // To keep track of visited elements of b[] let flag = new Array(n); for(let i=0;i<flag.length;i++) { flag[i]=false; } // For every element of a[], find a pair // for it and break as soon as a pair is // found. let result = 0; for (let i=0; i<n; i++) { for (let j=0; j<n; j++) { if (Math.abs(a[i]-b[j])<=k && flag[j]==false) { // Increasing the count if a pair is formed. result++; /* Making the corresponding flag array element as 1 indicating the element in the second array element has been used. */ flag[j] = true; // We break the loop to make sure an // element of a[] is used only once. break; } } } return result; } // Driver code let a=[10, 15, 20]; let b=[17, 12, 24]; let n = a.length; let k = 3; document.write(findMaxPairs(a, b, n, k)); // This code is contributed by rag2127</script>
Output:
2
Time complexity : O(n2) Auxiliary Space : O(n) Efficient Approach: In this approach, rather than checking all the possible combinations of pairs, we optimize our code by checking only the feasible combination of pairs using the 2 pointer approach.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>#define ll long long intusing namespace std; // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.ll findMaxPairs(ll a[], ll b[], ll n, ll k){ sort(a, a+n); // Sorting the first array. sort(b, b+n); // Sorting the second array. int result = 0; for (int i=0, j=0; i<n && j<n;) { if (abs(a[i] - b[j]) <= k) { result++; // Increasing array pointer of // both the first and the second array. i++; j++; } // Increasing array pointer of the second array. else if(a[i] > b[j]) j++; // Increasing array pointer of the first array. else i++; } return result;} // Driver codeint main(){ ll a[] = {10, 15, 20}; ll b[] = {17, 12, 24}; int n = sizeof(a)/sizeof(a[0]); int k = 3; cout << findMaxPairs(a, b, n, k); return 0;}
// Java program for Maximizing Unique Pairs// from two arraysimport java.util.*; class GFG{ // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.static int findMaxPairs(int a[], int b[], int n, int k){ Arrays.sort(a); // Sorting the first array. Arrays.sort(b); // Sorting the second array. int result = 0; for (int i = 0, j = 0; i < n && j < n;) { if (Math.abs(a[i] - b[j]) <= k) { result++; // Increasing array pointer of // both the first and the second array. i++; j++; } // Increasing array pointer // of the second array. else if(a[i] > b[j]) j++; // Increasing array pointer // of the first array. else i++; } return result;} // Driver codepublic static void main(String args[]){ int a[] = {10, 15, 20}; int b[] = {17, 12, 24}; int n = a.length; int k = 3; System.out.println(findMaxPairs(a, b, n, k));}} // This code is contributed by// Sanjit_Prasad
# Python3 program for# Maximizing Unique Pairs# from two arrays # Returns count of maximum pairs that can# be formed from a[] and b[] under given# constraints.def findMaxPairs(a,b,n,k): # Sorting the first array. a.sort() # Sorting the second array. b.sort() result =0 j=0 for i in range(n): if j<n: if abs(a[i]-b[j])<=k: result+=1 # Increasing array pointer of # both the first and the second array. j +=1 # Increasing array pointer of # the second array. elif a[i]>b[j]: j+=1 return result # Driver codeif __name__=='__main__': a = [10,15,20] b = [17,12,24] n = len(a) k =3 print(findMaxPairs(a,b,n,k)) # This code is contributed by# Shrikant13
// C# program for Maximizing Unique Pairs// from two arraysusing System; class GFG{ // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.static int findMaxPairs(int []a, int []b, int n, int k){ Array.Sort(a); // Sorting the first array. Array.Sort(b); // Sorting the second array. int result = 0; for (int i = 0, j = 0; i < n && j < n;) { if (Math.Abs(a[i] - b[j]) <= k) { result++; // Increasing array pointer of // both the first and the second array. i++; j++; } // Increasing array pointer // of the second array. else if(a[i] > b[j]) j++; // Increasing array pointer // of the first array. else i++; } return result;} // Driver codepublic static void Main(String []args){ int []a = {10, 15, 20}; int []b = {17, 12, 24}; int n = a.Length; int k = 3; Console.WriteLine(findMaxPairs(a, b, n, k));}} // This code has been contributed by 29AjayKumar
<script> // Javascript program for Maximizing // Unique Pairs from two arrays // Returns count of maximum pairs that can // be formed from a[] and b[] under given // constraints. function findMaxPairs(a, b, n, k) { // Sorting the first array. a.sort(function(a, b){return a - b}); // Sorting the second array. b.sort(function(a, b){return a - b}); let result = 0; for (let i = 0, j = 0; i < n && j < n;) { if (Math.abs(a[i] - b[j]) <= k) { result++; // Increasing array pointer of // both the first and the second array. i++; j++; } // Increasing array pointer // of the second array. else if(a[i] > b[j]) j++; // Increasing array pointer // of the first array. else i++; } return result; } let a = [10, 15, 20]; let b = [17, 12, 24]; let n = a.length; let k = 3; document.write(findMaxPairs(a, b, n, k)); </script>
Output:
2
Time complexity : O(n Log n) Auxiliary Space : O(1) This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
ukasp
Shashank_Sharma
Rajput-Ji
Sanjit_Prasad
29AjayKumar
Code_r
rameshtravel07
rag2127
sagar0719kumar
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation | [
{
"code": null,
"e": 24431,
"s": 24403,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 24773,
"s": 24431,
"text": "Given two arrays of equal size N, form maximum number of pairs by using their elements, one from the first array and second from the second array, such that an element from each array is used at-most-once and the absolute difference between the selected elements used for forming a pair is less than or equal to a given element K.Examples: "
},
{
"code": null,
"e": 25175,
"s": 24773,
"text": "Input : a[] = {3, 4, 5, 2, 1}\n b[] = {6, 5, 4, 7, 15}\n k = 3\nOutput : 4\nThe maximum number of pairs that can be formed\nusing the above 2 arrays is 4 and the corresponding\npairs are [1, 4], [2, 5], [3, 6], [4, 7], we can't \npair the remaining elements.\nOther way of pairing under given constraint is \n[2, 5], [3, 6], [4, 4], but count of pairs here\nis 3 which is less than the result 4."
},
{
"code": null,
"e": 25650,
"s": 25177,
"text": "Simple Approach: By taking few examples, we can observe that if we sort both arrays. Then one by picking the closest feasible element for every element, we get the optimal answer.In this approach we first sort both the arrays and then compare each element of the first array with each element of the second array for the possible pair, if it’s possible to form a pair, we form the pair and move to check for the next possible pair for the next element of the first array. "
},
{
"code": null,
"e": 25654,
"s": 25650,
"text": "C++"
},
{
"code": null,
"e": 25659,
"s": 25654,
"text": "Java"
},
{
"code": null,
"e": 25668,
"s": 25659,
"text": "Python 3"
},
{
"code": null,
"e": 25671,
"s": 25668,
"text": "C#"
},
{
"code": null,
"e": 25682,
"s": 25671,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>#define ll long long intusing namespace std; // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.ll findMaxPairs(ll a[], ll b[], ll n, ll k){ sort(a, a+n); // Sorting the first array. sort(b, b+n); // Sorting the second array. // To keep track of visited elements of b[] bool flag[n]; memset(flag, false, sizeof(flag)); // For every element of a[], find a pair // for it and break as soon as a pair is // found. int result = 0; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { if (abs(a[i]-b[j])<=k && flag[j]==false) { // Increasing the count if a pair is formed. result++; /* Making the corresponding flag array element as 1 indicating the element in the second array element has been used. */ flag[j] = true; // We break the loop to make sure an // element of a[] is used only once. break; } } } return result;} // Driver codeint main(){ ll a[] = {10, 15, 20}, b[] = {17, 12, 24}; int n = sizeof(a)/sizeof(a[0]); int k = 3; cout << findMaxPairs(a, b, n, k); return 0;}",
"e": 27037,
"s": 25682,
"text": null
},
{
"code": "// Java implementation of above approachimport java.util.*; class solution{ // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.static int findMaxPairs(int a[], int b[], int n, int k){ Arrays.sort(a); // Sorting the first array. Arrays.sort(b); // Sorting the second array. // To keep track of visited elements of b[] boolean []flag = new boolean[n]; Arrays.fill(flag,false); // For every element of a[], find a pair // for it and break as soon as a pair is // found. int result = 0; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { if (Math.abs(a[i]-b[j])<=k && flag[j]==false) { // Increasing the count if a pair is formed. result++; /* Making the corresponding flag array element as 1 indicating the element in the second array element has been used. */ flag[j] = true; // We break the loop to make sure an // element of a[] is used only once. break; } } } return result;} // Driver codepublic static void main(String args[]){ int[] a = {10, 15, 20}; int[] b = {17, 12, 24}; int n = a.length; int k = 3; System.out.println(findMaxPairs(a, b, n, k)); }} // This code is contributed by// Shashank_Sharma",
"e": 28453,
"s": 27037,
"text": null
},
{
"code": "# Returns count of maximum pairs# that can be formed from a[] and# b[] under given constraints.def findMaxPairs(a, b, n, k): a.sort() # Sorting the first array. b.sort() # Sorting the second array. # To keep track of visited # elements of b[] flag = [False] * n # For every element of a[], find # a pair for it and break as soon # as a pair is found. result = 0 for i in range(n): for j in range(n): if (abs(a[i] - b[j]) <= k and flag[j] == False): # Increasing the count if # a pair is formed. result += 1 ''' Making the corresponding flag array element as 1 indicating the element in the second array element has been used. ''' flag[j] = True # We break the loop to make sure an # element of a[] is used only once. break return result # Driver codeif __name__ == \"__main__\": a = [10, 15, 20] b = [17, 12, 24] n = len(a) k = 3 print(findMaxPairs(a, b, n, k)) # This code is contributed# by ChitraNayal",
"e": 29621,
"s": 28453,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG{ // Returns count of maximum pairs that can // be formed from a[] and b[] under given // constraints. static int findMaxPairs(int []a, int []b, int n, int k) { Array.Sort(a); // Sorting the first array. Array.Sort(b); // Sorting the second array. // To keep track of visited elements of b[] bool []flag = new bool[n]; //Arrays.fill(flag,false); // For every element of a[], find a pair // for it and break as soon as a pair is // found. int result = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (Math.Abs(a[i] - b[j]) <= k && flag[j] == false) { // Increasing the count if a pair is formed. result++; /* Making the corresponding flag array element as 1 indicating the element in the second array element has been used. */ flag[j] = true; // We break the loop to make sure an // element of a[] is used only once. break; } } } return result; } // Driver code public static void Main() { int[] a = {10, 15, 20}; int[] b = {17, 12, 24}; int n = a.Length; int k = 3; Console.WriteLine(findMaxPairs(a, b, n, k)); }} // This code is contributed by Rajput-Ji",
"e": 31221,
"s": 29621,
"text": null
},
{
"code": "<script>// Javascript implementation of above approach // Returns count of maximum pairs that can // be formed from a[] and b[] under given // constraints. function findMaxPairs(a,b,n,k) { a.sort(function(c,d){return c-d;}); // Sorting the first array. b.sort(function(c,d){return c-d;}) // Sorting the second array. // To keep track of visited elements of b[] let flag = new Array(n); for(let i=0;i<flag.length;i++) { flag[i]=false; } // For every element of a[], find a pair // for it and break as soon as a pair is // found. let result = 0; for (let i=0; i<n; i++) { for (let j=0; j<n; j++) { if (Math.abs(a[i]-b[j])<=k && flag[j]==false) { // Increasing the count if a pair is formed. result++; /* Making the corresponding flag array element as 1 indicating the element in the second array element has been used. */ flag[j] = true; // We break the loop to make sure an // element of a[] is used only once. break; } } } return result; } // Driver code let a=[10, 15, 20]; let b=[17, 12, 24]; let n = a.length; let k = 3; document.write(findMaxPairs(a, b, n, k)); // This code is contributed by rag2127</script>",
"e": 32668,
"s": 31221,
"text": null
},
{
"code": null,
"e": 32678,
"s": 32668,
"text": "Output: "
},
{
"code": null,
"e": 32680,
"s": 32678,
"text": "2"
},
{
"code": null,
"e": 32929,
"s": 32680,
"text": "Time complexity : O(n2) Auxiliary Space : O(n) Efficient Approach: In this approach, rather than checking all the possible combinations of pairs, we optimize our code by checking only the feasible combination of pairs using the 2 pointer approach. "
},
{
"code": null,
"e": 32933,
"s": 32929,
"text": "C++"
},
{
"code": null,
"e": 32938,
"s": 32933,
"text": "Java"
},
{
"code": null,
"e": 32946,
"s": 32938,
"text": "Python3"
},
{
"code": null,
"e": 32949,
"s": 32946,
"text": "C#"
},
{
"code": null,
"e": 32960,
"s": 32949,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>#define ll long long intusing namespace std; // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.ll findMaxPairs(ll a[], ll b[], ll n, ll k){ sort(a, a+n); // Sorting the first array. sort(b, b+n); // Sorting the second array. int result = 0; for (int i=0, j=0; i<n && j<n;) { if (abs(a[i] - b[j]) <= k) { result++; // Increasing array pointer of // both the first and the second array. i++; j++; } // Increasing array pointer of the second array. else if(a[i] > b[j]) j++; // Increasing array pointer of the first array. else i++; } return result;} // Driver codeint main(){ ll a[] = {10, 15, 20}; ll b[] = {17, 12, 24}; int n = sizeof(a)/sizeof(a[0]); int k = 3; cout << findMaxPairs(a, b, n, k); return 0;}",
"e": 33909,
"s": 32960,
"text": null
},
{
"code": "// Java program for Maximizing Unique Pairs// from two arraysimport java.util.*; class GFG{ // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.static int findMaxPairs(int a[], int b[], int n, int k){ Arrays.sort(a); // Sorting the first array. Arrays.sort(b); // Sorting the second array. int result = 0; for (int i = 0, j = 0; i < n && j < n;) { if (Math.abs(a[i] - b[j]) <= k) { result++; // Increasing array pointer of // both the first and the second array. i++; j++; } // Increasing array pointer // of the second array. else if(a[i] > b[j]) j++; // Increasing array pointer // of the first array. else i++; } return result;} // Driver codepublic static void main(String args[]){ int a[] = {10, 15, 20}; int b[] = {17, 12, 24}; int n = a.length; int k = 3; System.out.println(findMaxPairs(a, b, n, k));}} // This code is contributed by// Sanjit_Prasad",
"e": 35016,
"s": 33909,
"text": null
},
{
"code": "# Python3 program for# Maximizing Unique Pairs# from two arrays # Returns count of maximum pairs that can# be formed from a[] and b[] under given# constraints.def findMaxPairs(a,b,n,k): # Sorting the first array. a.sort() # Sorting the second array. b.sort() result =0 j=0 for i in range(n): if j<n: if abs(a[i]-b[j])<=k: result+=1 # Increasing array pointer of # both the first and the second array. j +=1 # Increasing array pointer of # the second array. elif a[i]>b[j]: j+=1 return result # Driver codeif __name__=='__main__': a = [10,15,20] b = [17,12,24] n = len(a) k =3 print(findMaxPairs(a,b,n,k)) # This code is contributed by# Shrikant13",
"e": 35853,
"s": 35016,
"text": null
},
{
"code": "// C# program for Maximizing Unique Pairs// from two arraysusing System; class GFG{ // Returns count of maximum pairs that can// be formed from a[] and b[] under given// constraints.static int findMaxPairs(int []a, int []b, int n, int k){ Array.Sort(a); // Sorting the first array. Array.Sort(b); // Sorting the second array. int result = 0; for (int i = 0, j = 0; i < n && j < n;) { if (Math.Abs(a[i] - b[j]) <= k) { result++; // Increasing array pointer of // both the first and the second array. i++; j++; } // Increasing array pointer // of the second array. else if(a[i] > b[j]) j++; // Increasing array pointer // of the first array. else i++; } return result;} // Driver codepublic static void Main(String []args){ int []a = {10, 15, 20}; int []b = {17, 12, 24}; int n = a.Length; int k = 3; Console.WriteLine(findMaxPairs(a, b, n, k));}} // This code has been contributed by 29AjayKumar",
"e": 36951,
"s": 35853,
"text": null
},
{
"code": "<script> // Javascript program for Maximizing // Unique Pairs from two arrays // Returns count of maximum pairs that can // be formed from a[] and b[] under given // constraints. function findMaxPairs(a, b, n, k) { // Sorting the first array. a.sort(function(a, b){return a - b}); // Sorting the second array. b.sort(function(a, b){return a - b}); let result = 0; for (let i = 0, j = 0; i < n && j < n;) { if (Math.abs(a[i] - b[j]) <= k) { result++; // Increasing array pointer of // both the first and the second array. i++; j++; } // Increasing array pointer // of the second array. else if(a[i] > b[j]) j++; // Increasing array pointer // of the first array. else i++; } return result; } let a = [10, 15, 20]; let b = [17, 12, 24]; let n = a.length; let k = 3; document.write(findMaxPairs(a, b, n, k)); </script>",
"e": 38096,
"s": 36951,
"text": null
},
{
"code": null,
"e": 38106,
"s": 38096,
"text": "Output: "
},
{
"code": null,
"e": 38108,
"s": 38106,
"text": "2"
},
{
"code": null,
"e": 38581,
"s": 38108,
"text": "Time complexity : O(n Log n) Auxiliary Space : O(1) This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 38593,
"s": 38581,
"text": "shrikanth13"
},
{
"code": null,
"e": 38599,
"s": 38593,
"text": "ukasp"
},
{
"code": null,
"e": 38615,
"s": 38599,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 38625,
"s": 38615,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38639,
"s": 38625,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 38651,
"s": 38639,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38658,
"s": 38651,
"text": "Code_r"
},
{
"code": null,
"e": 38673,
"s": 38658,
"text": "rameshtravel07"
},
{
"code": null,
"e": 38681,
"s": 38673,
"text": "rag2127"
},
{
"code": null,
"e": 38696,
"s": 38681,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 38703,
"s": 38696,
"text": "Arrays"
},
{
"code": null,
"e": 38711,
"s": 38703,
"text": "Sorting"
},
{
"code": null,
"e": 38718,
"s": 38711,
"text": "Arrays"
},
{
"code": null,
"e": 38726,
"s": 38718,
"text": "Sorting"
},
{
"code": null,
"e": 38824,
"s": 38726,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38833,
"s": 38824,
"text": "Comments"
},
{
"code": null,
"e": 38846,
"s": 38833,
"text": "Old Comments"
},
{
"code": null,
"e": 38867,
"s": 38846,
"text": "Next Greater Element"
},
{
"code": null,
"e": 38892,
"s": 38867,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 38919,
"s": 38892,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 38968,
"s": 38919,
"text": "Program to find sum of elements in a given array"
}
] |
Difference between Physical and Logical Tags - GeeksforGeeks | 22 Sep, 2021
In this article, we will learn about physical tags & logical tags in HTML & their implementation. We will also explore the difference between them. Let’s begin the discussion with a physical tag.
Physical tags: Physical tags are used to indicate that how specific characters are to be formatted or indicated using HTML tags. Any physical style tag may contain any item allowed in text, including conventional text, images, line breaks, etc. Physical tags can only be used for styling purposes for specific elements. Although each physical tag has a defined style, you can override that style by defining your own look for each tag. All physical tags require ending tags. Please refer to the What are physical tags in HTML? article for further details.
Syntax :
<tagname>Content</tagname>
Features:
They are extremely straightforward.
They are used to highlighting important sentences.
Physical Text Styles indicate the specific type of appearance for a section e.g., bold, italics, etc.
Physical Styles are rendered in the same manner by all browsers.
Here are some useful Physical tag lists:
<sup> Superscript is usually used for showing elements above base-line
<sub> The subscript is used for alternate baseline.
<i> An Italic tag is used to define a text with a special meaning.
<big> Big tag increase the font size by 1 (Note: You can not use the big tag in HTML 5)
<small> A small tag defines the small text, and it is used while writing copyright.
<b> Bold increases the importance of the text because bold tag covert the text into bold size.
<u> It is used to underline the text.
<tt> Teletype text gives the default font-family which is monospace.
<strike> It is an editing markup that tells the reader to ignore the text passage.
Example:
HTML
<!DOCTYPE html><html> <head> <title>Physical Tags</title> <style> .container { font-family: sans-serif; white-space: pre-line; } h1 { color: green; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> Welcome to the official channel of GeeksforGeeks! <b> Learn Data Structures Online At Your Own Pace With The Best Of Faculty In The Industry. </b> <big> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. </big> <i> The Best Data Structures Course Available Online From Skilled And Experienced Faculty. </i> <small> Python is a widely used, high-level programming language. </small> 5<sup>2</sup> SO<sub>2</sub> <tt> We provide a variety of services for you to learn, thrive and also have fun! </tt> <u> Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. Knowledge is power! </u> </div></body> </html>
Output:
Logical Tags: Logical tags are used to tell the browser what kind of text is written inside the tags. Logical tags are also known as Structural tags because they specify the structure of the document. Logical tags are used to indicate to the visually impaired person that there is something more important in the text or to emphasize the text ie, logical tags can be used for styling purposes as well as to give special importance to text content. Please refer to the What are logical tags in HTML? article for further details.
Syntax :
<tagname>Content</tagname>
Some cases where logical tags are useful:
To write code on our website.
To Emphasize some text.
To display the abbreviation on the Web page.
To display some famous quotation on our web page.
To write some mathematical formula in terms of variables.
Here are some useful Logical tags list:
<abbr> Defines the abbreviation of text.
<acronym> Defines the acronym.
<address> Contact information of a person or an organization.
<cite> Defines citation. It displays the text in italic format.
<code> Defines the piece of computer code.
<blockquote> Defines a long quotation.
<del> Defines the deleted text and is used to mark a portion of text which has been deleted from the document.
<dfn> Defines the definition element and is used to representing a defining instance in HTML.
<ins> Defines inserted text.
<kbd> Defines keyboard input text.
<pre> Defines the block of preformatted text which preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers.
<q> Defines the short quotation.
<samp> Defines the sample output text from a computer program.
<strong> Defines strong text i.e. show the importance of the text.
<var> Defines the variable in a mathematical equation or in the computer program.Example:HTMLHTML<!DOCTYPE html><html> <head> <title>Logical Tag</title> <style> .container { font-family: sans-serif; white-space: pre-line; } h1 { color: green; } </style></head> <body> <div class="container"> <h1>GeeksForGeeks</h1> Welcome to <abbr title="tags"> Logical tags</abbr> This is <acronym title="GeeksforGeeks">GFG</acronym> <address> 5th Floor, A-118, Sector-136, Noida, Uttar Pradesh - 201305 </address> <cite> C++ </cite> is my favourite Language. <code> Sample code: system.out.println(); </code> <blockquote cite="https://www.geeksforgeeks.org/"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes. </blockquote> <del> This contains deleted content.</del> <ins> Newly inserted content.</ins> <p> <dfn> GeeksforGeeks </dfn> is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes. </p> <kbd>This is a Keyboard input </kbd> <pre> Hello GFG, Greetings to all Community members !! Here I'm presenting my first blog of GFG Blogathon-2021. This is a predefine formatted text </pre> </div></body> </html>Output:Differences between Logical & Physical Tags:S.No.Logical tags Physical tags 1.Logical tags describe the behaviour, nature of content for the text enclosed inside the tag. They represent the function of text on the page.Physical tags are used to decide the appearance of the text and do not provide any information about the text.2.It carries certain obligations.It is extremely straightforward.3.It is used to mention visually impaired texts.It is used to indicate the specific characters which need formation.4.Here, the pages are more accessible.Page accessibility is comparatively low.5.It supports the latest technology.This concept is dependent upon weak tools.6.Logical tags are used to provide information by giving the special importance to the text. For instance, <em> tag is used to emphasize the text by representing it in italic format.Physical tags are used to style the content only. For instance, <i> is used to display the text in italic format.Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes
arrow_drop_upSave
Example:
HTML
<!DOCTYPE html><html> <head> <title>Logical Tag</title> <style> .container { font-family: sans-serif; white-space: pre-line; } h1 { color: green; } </style></head> <body> <div class="container"> <h1>GeeksForGeeks</h1> Welcome to <abbr title="tags"> Logical tags</abbr> This is <acronym title="GeeksforGeeks">GFG</acronym> <address> 5th Floor, A-118, Sector-136, Noida, Uttar Pradesh - 201305 </address> <cite> C++ </cite> is my favourite Language. <code> Sample code: system.out.println(); </code> <blockquote cite="https://www.geeksforgeeks.org/"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes. </blockquote> <del> This contains deleted content.</del> <ins> Newly inserted content.</ins> <p> <dfn> GeeksforGeeks </dfn> is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes. </p> <kbd>This is a Keyboard input </kbd> <pre> Hello GFG, Greetings to all Community members !! Here I'm presenting my first blog of GFG Blogathon-2021. This is a predefine formatted text </pre> </div></body> </html>
Output:
Differences between Logical & Physical Tags:
Logical tags describe the behaviour, nature of content for the text enclosed inside the tag. They represent the function of text on the page.
Physical tags are used to decide the appearance of the text and do not provide any information about the text.
It carries certain obligations.
It is extremely straightforward.
It is used to mention visually impaired texts.
It is used to indicate the specific characters which need formation.
Here, the pages are more accessible.
Page accessibility is comparatively low.
It supports the latest technology.
This concept is dependent upon weak tools.
Logical tags are used to provide information by giving the special importance to the text. For instance, <em> tag is used to emphasize the text by representing it in italic format.
Physical tags are used to style the content only. For instance, <i> is used to display the text in italic format.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Blogathon-2021
HTML-Questions
HTML-Tags
Picked
Blogathon
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
SQL Query to Convert Datetime to Date
How to pass data into table from a form using React Components
SQL Query to Create Table With a Primary Key
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 set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 24812,
"s": 24784,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 25008,
"s": 24812,
"text": "In this article, we will learn about physical tags & logical tags in HTML & their implementation. We will also explore the difference between them. Let’s begin the discussion with a physical tag."
},
{
"code": null,
"e": 25565,
"s": 25008,
"text": "Physical tags: Physical tags are used to indicate that how specific characters are to be formatted or indicated using HTML tags. Any physical style tag may contain any item allowed in text, including conventional text, images, line breaks, etc. Physical tags can only be used for styling purposes for specific elements. Although each physical tag has a defined style, you can override that style by defining your own look for each tag. All physical tags require ending tags. Please refer to the What are physical tags in HTML? article for further details."
},
{
"code": null,
"e": 25575,
"s": 25565,
"text": "Syntax : "
},
{
"code": null,
"e": 25602,
"s": 25575,
"text": "<tagname>Content</tagname>"
},
{
"code": null,
"e": 25612,
"s": 25602,
"text": "Features:"
},
{
"code": null,
"e": 25648,
"s": 25612,
"text": "They are extremely straightforward."
},
{
"code": null,
"e": 25699,
"s": 25648,
"text": "They are used to highlighting important sentences."
},
{
"code": null,
"e": 25801,
"s": 25699,
"text": "Physical Text Styles indicate the specific type of appearance for a section e.g., bold, italics, etc."
},
{
"code": null,
"e": 25866,
"s": 25801,
"text": "Physical Styles are rendered in the same manner by all browsers."
},
{
"code": null,
"e": 25909,
"s": 25868,
"text": "Here are some useful Physical tag lists:"
},
{
"code": null,
"e": 25982,
"s": 25909,
"text": "<sup> Superscript is usually used for showing elements above base-line "
},
{
"code": null,
"e": 26034,
"s": 25982,
"text": "<sub> The subscript is used for alternate baseline."
},
{
"code": null,
"e": 26102,
"s": 26034,
"text": "<i> An Italic tag is used to define a text with a special meaning. "
},
{
"code": null,
"e": 26190,
"s": 26102,
"text": "<big> Big tag increase the font size by 1 (Note: You can not use the big tag in HTML 5)"
},
{
"code": null,
"e": 26274,
"s": 26190,
"text": "<small> A small tag defines the small text, and it is used while writing copyright."
},
{
"code": null,
"e": 26369,
"s": 26274,
"text": "<b> Bold increases the importance of the text because bold tag covert the text into bold size."
},
{
"code": null,
"e": 26407,
"s": 26369,
"text": "<u> It is used to underline the text."
},
{
"code": null,
"e": 26476,
"s": 26407,
"text": "<tt> Teletype text gives the default font-family which is monospace."
},
{
"code": null,
"e": 26559,
"s": 26476,
"text": "<strike> It is an editing markup that tells the reader to ignore the text passage."
},
{
"code": null,
"e": 26568,
"s": 26559,
"text": "Example:"
},
{
"code": null,
"e": 26573,
"s": 26568,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Physical Tags</title> <style> .container { font-family: sans-serif; white-space: pre-line; } h1 { color: green; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> Welcome to the official channel of GeeksforGeeks! <b> Learn Data Structures Online At Your Own Pace With The Best Of Faculty In The Industry. </b> <big> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. </big> <i> The Best Data Structures Course Available Online From Skilled And Experienced Faculty. </i> <small> Python is a widely used, high-level programming language. </small> 5<sup>2</sup> SO<sub>2</sub> <tt> We provide a variety of services for you to learn, thrive and also have fun! </tt> <u> Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. Knowledge is power! </u> </div></body> </html>",
"e": 28052,
"s": 26573,
"text": null
},
{
"code": null,
"e": 28060,
"s": 28052,
"text": "Output:"
},
{
"code": null,
"e": 28588,
"s": 28060,
"text": "Logical Tags: Logical tags are used to tell the browser what kind of text is written inside the tags. Logical tags are also known as Structural tags because they specify the structure of the document. Logical tags are used to indicate to the visually impaired person that there is something more important in the text or to emphasize the text ie, logical tags can be used for styling purposes as well as to give special importance to text content. Please refer to the What are logical tags in HTML? article for further details."
},
{
"code": null,
"e": 28598,
"s": 28588,
"text": "Syntax : "
},
{
"code": null,
"e": 28633,
"s": 28598,
"text": "<tagname>Content</tagname> "
},
{
"code": null,
"e": 28675,
"s": 28633,
"text": "Some cases where logical tags are useful:"
},
{
"code": null,
"e": 28705,
"s": 28675,
"text": "To write code on our website."
},
{
"code": null,
"e": 28729,
"s": 28705,
"text": "To Emphasize some text."
},
{
"code": null,
"e": 28774,
"s": 28729,
"text": "To display the abbreviation on the Web page."
},
{
"code": null,
"e": 28824,
"s": 28774,
"text": "To display some famous quotation on our web page."
},
{
"code": null,
"e": 28882,
"s": 28824,
"text": "To write some mathematical formula in terms of variables."
},
{
"code": null,
"e": 28922,
"s": 28882,
"text": "Here are some useful Logical tags list:"
},
{
"code": null,
"e": 28963,
"s": 28922,
"text": "<abbr> Defines the abbreviation of text."
},
{
"code": null,
"e": 28994,
"s": 28963,
"text": "<acronym> Defines the acronym."
},
{
"code": null,
"e": 29056,
"s": 28994,
"text": "<address> Contact information of a person or an organization."
},
{
"code": null,
"e": 29120,
"s": 29056,
"text": "<cite> Defines citation. It displays the text in italic format."
},
{
"code": null,
"e": 29163,
"s": 29120,
"text": "<code> Defines the piece of computer code."
},
{
"code": null,
"e": 29202,
"s": 29163,
"text": "<blockquote> Defines a long quotation."
},
{
"code": null,
"e": 29313,
"s": 29202,
"text": "<del> Defines the deleted text and is used to mark a portion of text which has been deleted from the document."
},
{
"code": null,
"e": 29407,
"s": 29313,
"text": "<dfn> Defines the definition element and is used to representing a defining instance in HTML."
},
{
"code": null,
"e": 29436,
"s": 29407,
"text": "<ins> Defines inserted text."
},
{
"code": null,
"e": 29471,
"s": 29436,
"text": "<kbd> Defines keyboard input text."
},
{
"code": null,
"e": 29635,
"s": 29471,
"text": "<pre> Defines the block of preformatted text which preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers."
},
{
"code": null,
"e": 29668,
"s": 29635,
"text": "<q> Defines the short quotation."
},
{
"code": null,
"e": 29731,
"s": 29668,
"text": "<samp> Defines the sample output text from a computer program."
},
{
"code": null,
"e": 29798,
"s": 29731,
"text": "<strong> Defines strong text i.e. show the importance of the text."
},
{
"code": null,
"e": 32648,
"s": 29798,
"text": "<var> Defines the variable in a mathematical equation or in the computer program.Example:HTMLHTML<!DOCTYPE html><html> <head> <title>Logical Tag</title> <style> .container { font-family: sans-serif; white-space: pre-line; } h1 { color: green; } </style></head> <body> <div class=\"container\"> <h1>GeeksForGeeks</h1> Welcome to <abbr title=\"tags\"> Logical tags</abbr> This is <acronym title=\"GeeksforGeeks\">GFG</acronym> <address> 5th Floor, A-118, Sector-136, Noida, Uttar Pradesh - 201305 </address> <cite> C++ </cite> is my favourite Language. <code> Sample code: system.out.println(); </code> <blockquote cite=\"https://www.geeksforgeeks.org/\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes. </blockquote> <del> This contains deleted content.</del> <ins> Newly inserted content.</ins> <p> <dfn> GeeksforGeeks </dfn> is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes. </p> <kbd>This is a Keyboard input </kbd> <pre> Hello GFG, Greetings to all Community members !! Here I'm presenting my first blog of GFG Blogathon-2021. This is a predefine formatted text </pre> </div></body> </html>Output:Differences between Logical & Physical Tags:S.No.Logical tags Physical tags 1.Logical tags describe the behaviour, nature of content for the text enclosed inside the tag. They represent the function of text on the page.Physical tags are used to decide the appearance of the text and do not provide any information about the text.2.It carries certain obligations.It is extremely straightforward.3.It is used to mention visually impaired texts.It is used to indicate the specific characters which need formation.4.Here, the pages are more accessible.Page accessibility is comparatively low.5.It supports the latest technology.This concept is dependent upon weak tools.6.Logical tags are used to provide information by giving the special importance to the text. For instance, <em> tag is used to emphasize the text by representing it in italic format.Physical tags are used to style the content only. For instance, <i> is used to display the text in italic format.Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 32657,
"s": 32648,
"text": "Example:"
},
{
"code": null,
"e": 32662,
"s": 32657,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Logical Tag</title> <style> .container { font-family: sans-serif; white-space: pre-line; } h1 { color: green; } </style></head> <body> <div class=\"container\"> <h1>GeeksForGeeks</h1> Welcome to <abbr title=\"tags\"> Logical tags</abbr> This is <acronym title=\"GeeksforGeeks\">GFG</acronym> <address> 5th Floor, A-118, Sector-136, Noida, Uttar Pradesh - 201305 </address> <cite> C++ </cite> is my favourite Language. <code> Sample code: system.out.println(); </code> <blockquote cite=\"https://www.geeksforgeeks.org/\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes. </blockquote> <del> This contains deleted content.</del> <ins> Newly inserted content.</ins> <p> <dfn> GeeksforGeeks </dfn> is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes. </p> <kbd>This is a Keyboard input </kbd> <pre> Hello GFG, Greetings to all Community members !! Here I'm presenting my first blog of GFG Blogathon-2021. This is a predefine formatted text </pre> </div></body> </html>",
"e": 34249,
"s": 32662,
"text": null
},
{
"code": null,
"e": 34257,
"s": 34249,
"text": "Output:"
},
{
"code": null,
"e": 34302,
"s": 34257,
"text": "Differences between Logical & Physical Tags:"
},
{
"code": null,
"e": 34444,
"s": 34302,
"text": "Logical tags describe the behaviour, nature of content for the text enclosed inside the tag. They represent the function of text on the page."
},
{
"code": null,
"e": 34555,
"s": 34444,
"text": "Physical tags are used to decide the appearance of the text and do not provide any information about the text."
},
{
"code": null,
"e": 34587,
"s": 34555,
"text": "It carries certain obligations."
},
{
"code": null,
"e": 34620,
"s": 34587,
"text": "It is extremely straightforward."
},
{
"code": null,
"e": 34667,
"s": 34620,
"text": "It is used to mention visually impaired texts."
},
{
"code": null,
"e": 34736,
"s": 34667,
"text": "It is used to indicate the specific characters which need formation."
},
{
"code": null,
"e": 34773,
"s": 34736,
"text": "Here, the pages are more accessible."
},
{
"code": null,
"e": 34814,
"s": 34773,
"text": "Page accessibility is comparatively low."
},
{
"code": null,
"e": 34849,
"s": 34814,
"text": "It supports the latest technology."
},
{
"code": null,
"e": 34892,
"s": 34849,
"text": "This concept is dependent upon weak tools."
},
{
"code": null,
"e": 35073,
"s": 34892,
"text": "Logical tags are used to provide information by giving the special importance to the text. For instance, <em> tag is used to emphasize the text by representing it in italic format."
},
{
"code": null,
"e": 35187,
"s": 35073,
"text": "Physical tags are used to style the content only. For instance, <i> is used to display the text in italic format."
},
{
"code": null,
"e": 35324,
"s": 35187,
"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": 35339,
"s": 35324,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 35354,
"s": 35339,
"text": "HTML-Questions"
},
{
"code": null,
"e": 35364,
"s": 35354,
"text": "HTML-Tags"
},
{
"code": null,
"e": 35371,
"s": 35364,
"text": "Picked"
},
{
"code": null,
"e": 35381,
"s": 35371,
"text": "Blogathon"
},
{
"code": null,
"e": 35386,
"s": 35381,
"text": "HTML"
},
{
"code": null,
"e": 35403,
"s": 35386,
"text": "Web Technologies"
},
{
"code": null,
"e": 35408,
"s": 35403,
"text": "HTML"
},
{
"code": null,
"e": 35506,
"s": 35408,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35547,
"s": 35506,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 35582,
"s": 35547,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 35620,
"s": 35582,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 35683,
"s": 35620,
"text": "How to pass data into table from a form using React Components"
},
{
"code": null,
"e": 35728,
"s": 35683,
"text": "SQL Query to Create Table With a Primary Key"
},
{
"code": null,
"e": 35790,
"s": 35728,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35840,
"s": 35790,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35888,
"s": 35840,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35948,
"s": 35888,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
What happens if we try to extend a final class in java? | In Java final is the access modifier which can be used with a filed class and a method.
When a method if final it cannot be overridden.
When a variable is final its value cannot be modified further.
When a class is finale it cannot be extended.
When we try to extend a final class that will lead to a compilation error saying “cannot inherit from final SuperClass”
In the following Java program, we have a final class with name SuperClass and we are trying to inherent it from another class (SubClass).
final class SuperClass{
public void display() {
System.out.println("This is a method of the superclass");
}
}
public class SubClass extends SuperClass{
public static void main(String args[]){
//Calling method of the superclass
new SubClass().display();
}
}
On compiling, this program generates a compilation error as shown below −
SubClass.java:7: error: cannot inherit from final SuperClass
public class SubClass extends SuperClass{
^
1 error | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In Java final is the access modifier which can be used with a filed class and a method."
},
{
"code": null,
"e": 1198,
"s": 1150,
"text": "When a method if final it cannot be overridden."
},
{
"code": null,
"e": 1261,
"s": 1198,
"text": "When a variable is final its value cannot be modified further."
},
{
"code": null,
"e": 1307,
"s": 1261,
"text": "When a class is finale it cannot be extended."
},
{
"code": null,
"e": 1427,
"s": 1307,
"text": "When we try to extend a final class that will lead to a compilation error saying “cannot inherit from final SuperClass”"
},
{
"code": null,
"e": 1565,
"s": 1427,
"text": "In the following Java program, we have a final class with name SuperClass and we are trying to inherent it from another class (SubClass)."
},
{
"code": null,
"e": 1852,
"s": 1565,
"text": "final class SuperClass{\n public void display() {\n System.out.println(\"This is a method of the superclass\");\n }\n}\npublic class SubClass extends SuperClass{\n public static void main(String args[]){\n //Calling method of the superclass\n new SubClass().display();\n }\n}"
},
{
"code": null,
"e": 1926,
"s": 1852,
"text": "On compiling, this program generates a compilation error as shown below −"
},
{
"code": null,
"e": 2069,
"s": 1926,
"text": "SubClass.java:7: error: cannot inherit from final SuperClass\npublic class SubClass extends SuperClass{\n ^\n1 error"
}
] |
Print matrix in snake pattern from the last column - GeeksforGeeks | 19 Dec, 2018
Given a matrix of 2-Dimensional array of n rows and n columns. Print this matrix in snake fashion starting from column n-1 as shown in the figure below.
Examples:
Input : mat[][] =
1 2 3
4 5 6
7 8 9
Output: 3 2 1 4 5 6 9 8 7
Input: mat[][] =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output: 4 3 2 1 5 6 7 8 12 11 10 9 13 14 15 16
Algorithm:
Start traversing from top right cell belonging to row 0 and column n-1.First move will always be a horizontal move towards LEFT(WEST) direction.Alternatively Horizontal and vertical moves are made during matrix traversal.In a single horizontal move, we traverse multiple cells till we reach any of the wall of the matrix.In a horizontal move, if the row is odd numbered, we move in RIGHT(EAST) direction else we move in LEFT(WEST) directionIn a single vertical move, we traverse a single cell in DOWNWARDS direction.
Start traversing from top right cell belonging to row 0 and column n-1.
First move will always be a horizontal move towards LEFT(WEST) direction.
Alternatively Horizontal and vertical moves are made during matrix traversal.
In a single horizontal move, we traverse multiple cells till we reach any of the wall of the matrix.
In a horizontal move, if the row is odd numbered, we move in RIGHT(EAST) direction else we move in LEFT(WEST) direction
In a single vertical move, we traverse a single cell in DOWNWARDS direction.
Below is the implementation of the above algorithm:
C++
Java
Python3
C#
PHP
// C++ program for traversing a matrix from column n-1#include <bits/stdc++.h>using namespace std; // Function used for traversing over the given matrixvoid traverseMatrix(vector<vector<int> > mat, int n){ for (int i = 0; i < n; i++) { if (i%2 == 1) for (int j = 0; j < n; j++) printf("%d ", mat[i][j]); else for (int j = n - 1; j >= 0; j--) printf("%d ", mat[i][j]); }} // Driver functionint main(){ // number of rows and columns int n = 5; // 5x5 matrix vector<vector<int> > mat{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; traverseMatrix(mat, n); return 0;}
// Java program for traversing a matrix from column n-1 class GFG { // Function used for traversing over the given matrix static void traverseMatrix(int[][] mat, int n) { for (int i = 0; i < n; i++) { if (i % 2 == 1) { for (int j = 0; j < n; j++) { System.out.print( Integer.toString(mat[i][j]) + " "); } } else { for (int j = n - 1; j >= 0; j--) { System.out.print( Integer.toString(mat[i][j]) + " "); } } } } // Driver function public static void main(String[] args) { // number of rows and columns int n = 5; // 5x5 matrix int[][] mat = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; traverseMatrix(mat, n); System.exit(0); }}
# Python3 program for traversing a matrix from column n-1import sys; # Function used for traversing over the given matrixdef traverseMatrix(mat, n): for i in range(n): if i & 1: for j in range(n): print(str(mat[i][j])+ "", end = " ") else: for j in range(n-1, -1, -1): print(str(mat[i][j])+ "", end = " ") # Driver functionif __name__ == '__main__': # number of rows and columns n = 5 # 5x5 matrix mat =[ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ] traverseMatrix(mat, n)
// CSHARP program for traversing a matrix from column n-1 using System;using System.Linq; class GFG { // Function used for traversing over the given matrix static void traverseMatrix(int[, ] mat, int n) { for (int i = 0; i < n; i++) { if (i % 2 == 1) { for (int j = 0; j < n; j++) { Console.Write(mat[i, j].ToString() + " "); } } else { for (int j = n - 1; j >= 0; j--) { Console.Write(mat[i, j].ToString() + " "); } } } } // Driver function public static void Main() { // number of rows and columns int n = 5; // 5x5 matrix int[, ] mat = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; traverseMatrix(mat, n); }}
<?php// PHP program for traversing a matrix from column n-1 # Function used for traversing over the given matrixfunction traverseMatrix($mat, $n){ for($i = 0; $i < $n; $i++) { if($i & 1) { for($j = 0; $j < $n; $j++) { print($mat[$i][$j]." "); } } else { for($j = $n - 1; $j >= 0; $j--) { print($mat[$i][$j]." "); } } }} // Driver function # number of rows and columns$n = 5; # 5x5 matrix$mat = array( array(1, 2, 3, 4, 5), array(6, 7, 8, 9, 10), array(11, 12, 13, 14, 15), array(16, 17, 18, 19, 20), array(21, 22, 23, 24, 25)); traverseMatrix($mat, $n); ?>
5 4 3 2 1 6 7 8 9 10 15 14 13 12 11 16 17 18 19 20 25 24 23 22 21
Time Complexity: O(N^2)Space Complexity: O(1)
sriharshanakka
pattern-printing
Competitive Programming
Matrix
School Programming
pattern-printing
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Breadth First Traversal ( BFS ) on a 2D array
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Runtime Errors
Most important type of Algorithms
Multistage Graph (Shortest Path)
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Sudoku | Backtracking-7
Rat in a Maze | Backtracking-2 | [
{
"code": null,
"e": 24736,
"s": 24708,
"text": "\n19 Dec, 2018"
},
{
"code": null,
"e": 24889,
"s": 24736,
"text": "Given a matrix of 2-Dimensional array of n rows and n columns. Print this matrix in snake fashion starting from column n-1 as shown in the figure below."
},
{
"code": null,
"e": 24899,
"s": 24889,
"text": "Examples:"
},
{
"code": null,
"e": 25073,
"s": 24899,
"text": "Input : mat[][] = \n1 2 3 \n4 5 6\n7 8 9\nOutput: 3 2 1 4 5 6 9 8 7\n\nInput: mat[][] = \n1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n13 14 15 16\nOutput: 4 3 2 1 5 6 7 8 12 11 10 9 13 14 15 16\n"
},
{
"code": null,
"e": 25084,
"s": 25073,
"text": "Algorithm:"
},
{
"code": null,
"e": 25601,
"s": 25084,
"text": "Start traversing from top right cell belonging to row 0 and column n-1.First move will always be a horizontal move towards LEFT(WEST) direction.Alternatively Horizontal and vertical moves are made during matrix traversal.In a single horizontal move, we traverse multiple cells till we reach any of the wall of the matrix.In a horizontal move, if the row is odd numbered, we move in RIGHT(EAST) direction else we move in LEFT(WEST) directionIn a single vertical move, we traverse a single cell in DOWNWARDS direction."
},
{
"code": null,
"e": 25673,
"s": 25601,
"text": "Start traversing from top right cell belonging to row 0 and column n-1."
},
{
"code": null,
"e": 25747,
"s": 25673,
"text": "First move will always be a horizontal move towards LEFT(WEST) direction."
},
{
"code": null,
"e": 25825,
"s": 25747,
"text": "Alternatively Horizontal and vertical moves are made during matrix traversal."
},
{
"code": null,
"e": 25926,
"s": 25825,
"text": "In a single horizontal move, we traverse multiple cells till we reach any of the wall of the matrix."
},
{
"code": null,
"e": 26046,
"s": 25926,
"text": "In a horizontal move, if the row is odd numbered, we move in RIGHT(EAST) direction else we move in LEFT(WEST) direction"
},
{
"code": null,
"e": 26123,
"s": 26046,
"text": "In a single vertical move, we traverse a single cell in DOWNWARDS direction."
},
{
"code": null,
"e": 26175,
"s": 26123,
"text": "Below is the implementation of the above algorithm:"
},
{
"code": null,
"e": 26179,
"s": 26175,
"text": "C++"
},
{
"code": null,
"e": 26184,
"s": 26179,
"text": "Java"
},
{
"code": null,
"e": 26192,
"s": 26184,
"text": "Python3"
},
{
"code": null,
"e": 26195,
"s": 26192,
"text": "C#"
},
{
"code": null,
"e": 26199,
"s": 26195,
"text": "PHP"
},
{
"code": "// C++ program for traversing a matrix from column n-1#include <bits/stdc++.h>using namespace std; // Function used for traversing over the given matrixvoid traverseMatrix(vector<vector<int> > mat, int n){ for (int i = 0; i < n; i++) { if (i%2 == 1) for (int j = 0; j < n; j++) printf(\"%d \", mat[i][j]); else for (int j = n - 1; j >= 0; j--) printf(\"%d \", mat[i][j]); }} // Driver functionint main(){ // number of rows and columns int n = 5; // 5x5 matrix vector<vector<int> > mat{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; traverseMatrix(mat, n); return 0;}",
"e": 26971,
"s": 26199,
"text": null
},
{
"code": "// Java program for traversing a matrix from column n-1 class GFG { // Function used for traversing over the given matrix static void traverseMatrix(int[][] mat, int n) { for (int i = 0; i < n; i++) { if (i % 2 == 1) { for (int j = 0; j < n; j++) { System.out.print( Integer.toString(mat[i][j]) + \" \"); } } else { for (int j = n - 1; j >= 0; j--) { System.out.print( Integer.toString(mat[i][j]) + \" \"); } } } } // Driver function public static void main(String[] args) { // number of rows and columns int n = 5; // 5x5 matrix int[][] mat = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; traverseMatrix(mat, n); System.exit(0); }}",
"e": 28014,
"s": 26971,
"text": null
},
{
"code": "# Python3 program for traversing a matrix from column n-1import sys; # Function used for traversing over the given matrixdef traverseMatrix(mat, n): for i in range(n): if i & 1: for j in range(n): print(str(mat[i][j])+ \"\", end = \" \") else: for j in range(n-1, -1, -1): print(str(mat[i][j])+ \"\", end = \" \") # Driver functionif __name__ == '__main__': # number of rows and columns n = 5 # 5x5 matrix mat =[ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ] traverseMatrix(mat, n)",
"e": 28690,
"s": 28014,
"text": null
},
{
"code": "// CSHARP program for traversing a matrix from column n-1 using System;using System.Linq; class GFG { // Function used for traversing over the given matrix static void traverseMatrix(int[, ] mat, int n) { for (int i = 0; i < n; i++) { if (i % 2 == 1) { for (int j = 0; j < n; j++) { Console.Write(mat[i, j].ToString() + \" \"); } } else { for (int j = n - 1; j >= 0; j--) { Console.Write(mat[i, j].ToString() + \" \"); } } } } // Driver function public static void Main() { // number of rows and columns int n = 5; // 5x5 matrix int[, ] mat = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; traverseMatrix(mat, n); }}",
"e": 29662,
"s": 28690,
"text": null
},
{
"code": "<?php// PHP program for traversing a matrix from column n-1 # Function used for traversing over the given matrixfunction traverseMatrix($mat, $n){ for($i = 0; $i < $n; $i++) { if($i & 1) { for($j = 0; $j < $n; $j++) { print($mat[$i][$j].\" \"); } } else { for($j = $n - 1; $j >= 0; $j--) { print($mat[$i][$j].\" \"); } } }} // Driver function # number of rows and columns$n = 5; # 5x5 matrix$mat = array( array(1, 2, 3, 4, 5), array(6, 7, 8, 9, 10), array(11, 12, 13, 14, 15), array(16, 17, 18, 19, 20), array(21, 22, 23, 24, 25)); traverseMatrix($mat, $n); ?>",
"e": 30371,
"s": 29662,
"text": null
},
{
"code": null,
"e": 30438,
"s": 30371,
"text": "5 4 3 2 1 6 7 8 9 10 15 14 13 12 11 16 17 18 19 20 25 24 23 22 21\n"
},
{
"code": null,
"e": 30484,
"s": 30438,
"text": "Time Complexity: O(N^2)Space Complexity: O(1)"
},
{
"code": null,
"e": 30499,
"s": 30484,
"text": "sriharshanakka"
},
{
"code": null,
"e": 30516,
"s": 30499,
"text": "pattern-printing"
},
{
"code": null,
"e": 30540,
"s": 30516,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30547,
"s": 30540,
"text": "Matrix"
},
{
"code": null,
"e": 30566,
"s": 30547,
"text": "School Programming"
},
{
"code": null,
"e": 30583,
"s": 30566,
"text": "pattern-printing"
},
{
"code": null,
"e": 30590,
"s": 30583,
"text": "Matrix"
},
{
"code": null,
"e": 30688,
"s": 30590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30697,
"s": 30688,
"text": "Comments"
},
{
"code": null,
"e": 30710,
"s": 30697,
"text": "Old Comments"
},
{
"code": null,
"e": 30756,
"s": 30710,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 30839,
"s": 30756,
"text": "Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]"
},
{
"code": null,
"e": 30854,
"s": 30839,
"text": "Runtime Errors"
},
{
"code": null,
"e": 30888,
"s": 30854,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 30921,
"s": 30888,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 30956,
"s": 30921,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 31000,
"s": 30956,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 31036,
"s": 31000,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 31060,
"s": 31036,
"text": "Sudoku | Backtracking-7"
}
] |
How to Find Armstrong Number in an Interval using Python? | If sum of cubes of individual digits in a number add up to the number itself, it is called armstrong number. for example 153=1**3+5**3+3**3
Following Python program find armstrong numbers between 100 to 1000
for num in range(100,1000):
temp=num
sum=0
while temp>0:
digit=temp%10
sum=sum+digit**3
temp=temp//10
if sum==num:
print (num)
The output is as follows −
153
370
371
407 | [
{
"code": null,
"e": 1202,
"s": 1062,
"text": "If sum of cubes of individual digits in a number add up to the number itself, it is called armstrong number. for example 153=1**3+5**3+3**3"
},
{
"code": null,
"e": 1270,
"s": 1202,
"text": "Following Python program find armstrong numbers between 100 to 1000"
},
{
"code": null,
"e": 1438,
"s": 1270,
"text": "for num in range(100,1000):\n temp=num\n sum=0\n while temp>0:\n digit=temp%10\n sum=sum+digit**3\n temp=temp//10\n if sum==num:\n print (num)"
},
{
"code": null,
"e": 1465,
"s": 1438,
"text": "The output is as follows −"
},
{
"code": null,
"e": 1481,
"s": 1465,
"text": "153\n370\n371\n407"
}
] |
Lexicographically smallest string formed by removing at most one character - GeeksforGeeks | 24 May, 2021
Given a string str, the task is to find the lexicographically smallest string that can be formed by removing at most one character from the given string.
Examples:
Input: str = "abcda"
Output: abca
One can remove 'd' to get "abca" which is
the lexicographically smallest string possible.
Input: str = "aaa'
Output: aa
Approach: Traverse the string and delete the i-th character at the first point where s[i]>s[i+1]. If in case there is no such character then delete the last character in the string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the lexicographically// smallest string by removing at most one character#include <bits/stdc++.h>using namespace std; // Function to return the smallest stringstring smallest(string s){ int l = s.length(); string ans = ""; // iterate the string for (int i = 0; i < l-1; i++) { // first point where s[i]>s[i+1] if (s[i] > s[i + 1]) { // append the string without // i-th character in it for (int j = 0; j < l; j++) { if (i != j) ans += s[j]; } return ans; } } // leave the last character ans = s.substr(0., l - 1); return ans;} // Driver Codeint main(){ string s = "abcda"; cout << smallest(s); return 0;}
// Java program to find the lexicographically// smallest String by removing at most one character class GFG { // Function to return the smallest String static String smallest(String s) { int l = s.length(); String ans = ""; // iterate the String for (int i = 0; i < l-1; i++) { // first point where s[i]>s[i+1] if (s.charAt(i) > s.charAt(i + 1)) { // append the String without // i-th character in it for (int j = 0; j < l; j++) { if (i != j) { ans += s.charAt(j); } } return ans; } } // leave the last character ans = s.substring(0, l - 1); return ans; } // Driver Code public static void main(String[] args) { String s = "abcda"; System.out.println(smallest(s)); }}/* This code is contributed by 29AjayKumar*/
# Python3 program to find the lexicographically# smallest string by removing at most one character # Function to return the smallest stringdef smallest(s): l = len(s) ans = "" # iterate the string for i in range (l-1): # first point where s[i]>s[i+1] if (s[i] > s[i + 1]): # append the string without # i-th character in it for j in range (l): if (i != j): ans += s[j] return ans # leave the last character ans = s[0: l - 1] return ans # Driver Codeif __name__ == "__main__": s = "abcda" print (smallest(s)) # This code is contributed by ita_c
// C# program to find the lexicographically// smallest String by removing at most// one characterusing System; class GFG{ // Function to return the// smallest Stringstatic String smallest(String s){ int l = s.Length; String ans = ""; // iterate the String for (int i = 0; i < l-1; i++) { // first point where s[i]>s[i+1] if (s[i] > s[i + 1]) { // append the String without // i-th character in it for (int j = 0; j < l; j++) { if (i != j) { ans += s[j]; } } return ans; } } // leave the last character ans = s.Substring(0, l - 1); return ans;} // Driver Codepublic static void Main(){ String s = "abcda"; Console.Write(smallest(s));}} // This code is contributed by 29AjayKumar
<script>// Javascript program to find the lexicographically// smallest String by removing at most one character // Function to return the smallest String function smallest(s) { let l = s.length; let ans = ""; // iterate the String for (let i = 0; i < l-1; i++) { // first point where s[i]>s[i+1] if (s[i] > s[i+1]) { // append the String without // i-th character in it for (let j = 0; j < l; j++) { if (i != j) { ans += s[j]; } } return ans; } } // leave the last character ans = s.substring(0, l - 1); return ans; } // Driver Code let s = "abcda"; document.write(smallest(s)); // This code is contributed by rag2127</script>
abca
29AjayKumar
ukasp
atishayjain13
recordable0711
rag2127
lexicographic-ordering
Technical Scripter 2018
Competitive Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bits manipulation (Important tactics)
Breadth First Traversal ( BFS ) on a 2D array
Remove all occurrences of a character in a string | Recursive approach
Container with Most Water
How to begin with Competitive Programming?
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types | [
{
"code": null,
"e": 25199,
"s": 25171,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 25354,
"s": 25199,
"text": "Given a string str, the task is to find the lexicographically smallest string that can be formed by removing at most one character from the given string. "
},
{
"code": null,
"e": 25365,
"s": 25354,
"text": "Examples: "
},
{
"code": null,
"e": 25525,
"s": 25365,
"text": "Input: str = \"abcda\" \nOutput: abca\nOne can remove 'd' to get \"abca\" which is \nthe lexicographically smallest string possible. \n\nInput: str = \"aaa' \nOutput: aa"
},
{
"code": null,
"e": 25708,
"s": 25525,
"text": "Approach: Traverse the string and delete the i-th character at the first point where s[i]>s[i+1]. If in case there is no such character then delete the last character in the string. "
},
{
"code": null,
"e": 25760,
"s": 25708,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25764,
"s": 25760,
"text": "C++"
},
{
"code": null,
"e": 25769,
"s": 25764,
"text": "Java"
},
{
"code": null,
"e": 25777,
"s": 25769,
"text": "Python3"
},
{
"code": null,
"e": 25780,
"s": 25777,
"text": "C#"
},
{
"code": null,
"e": 25791,
"s": 25780,
"text": "Javascript"
},
{
"code": "// C++ program to find the lexicographically// smallest string by removing at most one character#include <bits/stdc++.h>using namespace std; // Function to return the smallest stringstring smallest(string s){ int l = s.length(); string ans = \"\"; // iterate the string for (int i = 0; i < l-1; i++) { // first point where s[i]>s[i+1] if (s[i] > s[i + 1]) { // append the string without // i-th character in it for (int j = 0; j < l; j++) { if (i != j) ans += s[j]; } return ans; } } // leave the last character ans = s.substr(0., l - 1); return ans;} // Driver Codeint main(){ string s = \"abcda\"; cout << smallest(s); return 0;}",
"e": 26568,
"s": 25791,
"text": null
},
{
"code": "// Java program to find the lexicographically// smallest String by removing at most one character class GFG { // Function to return the smallest String static String smallest(String s) { int l = s.length(); String ans = \"\"; // iterate the String for (int i = 0; i < l-1; i++) { // first point where s[i]>s[i+1] if (s.charAt(i) > s.charAt(i + 1)) { // append the String without // i-th character in it for (int j = 0; j < l; j++) { if (i != j) { ans += s.charAt(j); } } return ans; } } // leave the last character ans = s.substring(0, l - 1); return ans; } // Driver Code public static void main(String[] args) { String s = \"abcda\"; System.out.println(smallest(s)); }}/* This code is contributed by 29AjayKumar*/",
"e": 27536,
"s": 26568,
"text": null
},
{
"code": "# Python3 program to find the lexicographically# smallest string by removing at most one character # Function to return the smallest stringdef smallest(s): l = len(s) ans = \"\" # iterate the string for i in range (l-1): # first point where s[i]>s[i+1] if (s[i] > s[i + 1]): # append the string without # i-th character in it for j in range (l): if (i != j): ans += s[j] return ans # leave the last character ans = s[0: l - 1] return ans # Driver Codeif __name__ == \"__main__\": s = \"abcda\" print (smallest(s)) # This code is contributed by ita_c",
"e": 28219,
"s": 27536,
"text": null
},
{
"code": "// C# program to find the lexicographically// smallest String by removing at most// one characterusing System; class GFG{ // Function to return the// smallest Stringstatic String smallest(String s){ int l = s.Length; String ans = \"\"; // iterate the String for (int i = 0; i < l-1; i++) { // first point where s[i]>s[i+1] if (s[i] > s[i + 1]) { // append the String without // i-th character in it for (int j = 0; j < l; j++) { if (i != j) { ans += s[j]; } } return ans; } } // leave the last character ans = s.Substring(0, l - 1); return ans;} // Driver Codepublic static void Main(){ String s = \"abcda\"; Console.Write(smallest(s));}} // This code is contributed by 29AjayKumar",
"e": 29092,
"s": 28219,
"text": null
},
{
"code": "<script>// Javascript program to find the lexicographically// smallest String by removing at most one character // Function to return the smallest String function smallest(s) { let l = s.length; let ans = \"\"; // iterate the String for (let i = 0; i < l-1; i++) { // first point where s[i]>s[i+1] if (s[i] > s[i+1]) { // append the String without // i-th character in it for (let j = 0; j < l; j++) { if (i != j) { ans += s[j]; } } return ans; } } // leave the last character ans = s.substring(0, l - 1); return ans; } // Driver Code let s = \"abcda\"; document.write(smallest(s)); // This code is contributed by rag2127</script>",
"e": 29990,
"s": 29092,
"text": null
},
{
"code": null,
"e": 29995,
"s": 29990,
"text": "abca"
},
{
"code": null,
"e": 30007,
"s": 29995,
"text": "29AjayKumar"
},
{
"code": null,
"e": 30013,
"s": 30007,
"text": "ukasp"
},
{
"code": null,
"e": 30027,
"s": 30013,
"text": "atishayjain13"
},
{
"code": null,
"e": 30042,
"s": 30027,
"text": "recordable0711"
},
{
"code": null,
"e": 30050,
"s": 30042,
"text": "rag2127"
},
{
"code": null,
"e": 30073,
"s": 30050,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 30097,
"s": 30073,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30121,
"s": 30097,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30129,
"s": 30121,
"text": "Strings"
},
{
"code": null,
"e": 30137,
"s": 30129,
"text": "Strings"
},
{
"code": null,
"e": 30235,
"s": 30137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30244,
"s": 30235,
"text": "Comments"
},
{
"code": null,
"e": 30257,
"s": 30244,
"text": "Old Comments"
},
{
"code": null,
"e": 30295,
"s": 30257,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 30341,
"s": 30295,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 30412,
"s": 30341,
"text": "Remove all occurrences of a character in a string | Recursive approach"
},
{
"code": null,
"e": 30438,
"s": 30412,
"text": "Container with Most Water"
},
{
"code": null,
"e": 30481,
"s": 30438,
"text": "How to begin with Competitive Programming?"
},
{
"code": null,
"e": 30506,
"s": 30481,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30552,
"s": 30506,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 30586,
"s": 30552,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30646,
"s": 30586,
"text": "Write a program to print all permutations of a given string"
}
] |
Display video inside HTML5 canvas | You can try the following code snippet to display video inside HTML5 canvas.
var canvas1 = document.getElementById('canvas');
var context = canvas1.getContext('2d');
var video = document.getElementById('video');
video.addEventListener('play', function () {
var $this = this;
(function loop() {
if (!$this.paused && !$this.ended) {
context.drawImage($this, 0, 0);
setTimeout(loop, 1000 / 30);
}
})();
}, 0); | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "You can try the following code snippet to display video inside HTML5 canvas."
},
{
"code": null,
"e": 1508,
"s": 1139,
"text": "var canvas1 = document.getElementById('canvas');\nvar context = canvas1.getContext('2d');\nvar video = document.getElementById('video');\nvideo.addEventListener('play', function () {\n var $this = this;\n (function loop() {\n if (!$this.paused && !$this.ended) {\n context.drawImage($this, 0, 0);\n setTimeout(loop, 1000 / 30);\n }\n })();\n}, 0);"
}
] |
Sorting List in SAP UI5 project | Yes, you can. You can use the available sorter property available on the List. It lets you specify all the required details. For e.g. −
<List
Items="{
path: '/EmployeeCollection',
sorter: {
path: 'EmployeeName',
descending: true,
group: true
}
}"
headerText="Employees" />
I have specified the employee collection to be sorted on the basis of the name of the employee and specified that the sorting should be in descending manner. It should also consider grouping while sorting the data. | [
{
"code": null,
"e": 1198,
"s": 1062,
"text": "Yes, you can. You can use the available sorter property available on the List. It lets you specify all the required details. For e.g. −"
},
{
"code": null,
"e": 1353,
"s": 1198,
"text": "<List\nItems=\"{\n path: '/EmployeeCollection',\n sorter: {\n path: 'EmployeeName',\n descending: true,\n group: true\n }\n}\"\nheaderText=\"Employees\" />"
},
{
"code": null,
"e": 1568,
"s": 1353,
"text": "I have specified the employee collection to be sorted on the basis of the name of the employee and specified that the sorting should be in descending manner. It should also consider grouping while sorting the data."
}
] |
How do Python Generators Work? | Towards Data Science | In this article, I’ll attempt to provide an in-depth understanding of Python generators, and how they operate from the inside. It will include the how and why. Sections will be self-contained, and you are welcome to skip at your will. Without further ado, let us begin our journey. ⛵️
Added since Python 2.2, Generators are unique functions that can be paused, resumed and iterated over. Let’s take a look over an example:
By defining a function that contains the yield keyword, the function is marked as a generator. We then run the generator in the following order:
Initialize the generator and put it in g. At this point, we have a new generator object that didn’t run yet.Advance the generator by calling next() on it. This causes the generator to advance to the first yield keyword, printing “Hello” on the way.Advance the generator again. It prints “Goodbye”, and since it reached the end of the function, it raises a StopIteration exception and finishes.
Initialize the generator and put it in g. At this point, we have a new generator object that didn’t run yet.
Advance the generator by calling next() on it. This causes the generator to advance to the first yield keyword, printing “Hello” on the way.
Advance the generator again. It prints “Goodbye”, and since it reached the end of the function, it raises a StopIteration exception and finishes.
In order to understand these three simple steps, we first need to start from the very basics of how a function in Python runs.
Running a function involves two main steps: Initialization, and Evaluation.
Under the hood, CPython runs a function inside a frame object.
A frame object, sometimes called a stack-frame, consists of the following fields:
code object, which includes the function’s actual compiled code.
free stack space, called value-stack, for running the interpreter.
execution pointer for the current line of code being executed.
other fields like mappings of local variables.
A list of all frame fields can be seen in the code while a shorter list can be seen in the documentation.
When we initialize a function, a frame is created. In pseudo-code:
f = Frame()
The arguments we passed to the function are then assigned inside the frame:
f.f_locals["arg1"] = arg1f.f_locals["arg2"] = arg2
The execution point of the frame, is set to the first line of code in the function:
f.lasti = 0 # Last Instructionf.lineno = 0 # Function line number on file
At this point our function starts running.
Almost the entire Python interpreter can be summarized into one C-level function: PyEval_EvalFrameEx.
This function is the interpreter loop. Consisting of 3k lines of code, its job is to evaluate a frame, or in other words, run it. Every function in Python, every bytecode or opcode that the interpreter runs, goes through that function.
During “PyEval”, Python operates on the frame’s unique value-stack. This bit of information will be crucial later on.
In summary, when you enter a function, and run it, the interpreter creates a frame, and enters the interpreter loop.
A site called PythonTutor has a very nice interactive example of this mechanism.
Much like functions, running a generator involves the initialization step, and the evaluation step.
At this step we are creating the generator object. The generator object consists of the frame object and the code object. If you’re wondering, yes, the frame object also contains the code object inside it. In pseudo-code:
g = Generator()f = Frame() # Initialized as beforeg.gi_frame = fg.gi_code = f.f_code = Code() # The compiled function
At this point, our generator g is ready to run.
Every time we call next(g), the frame is evaluated using the same PyEval_EvalFrameEx.
The difference is, when running a generator, we can reach the yield keyword, at which point the frame evaluation stops, and the generator “pauses”.
A pointer in the frame is saved, marking our current stack position, in order to know exactly what was the generator state upon stopping.
It is important to remember, that unlike functions, when the evaluation stops the frame is not destroyed as it’s still attached to the generator object. This will allow us to load it later on.
PyEval returns and our calling function resumes.
When we advance the generator once more, the frame is loaded from gi_frame, and PyEval is called again on the same frame. It checks where we stopped, goes to our execution pointer, and uses the value-stack stored on the frame.
Since we’re using the same stack, and the frame also contains all of the local variables, we can continue from the exact same spot, as if the function never stopped.
When we reach the end of the generator, or return statement, StopIteration gets thrown, and the frame is deleted. gi_frame is then set to None.
Now that we know how a generator internally pauses and resumes, let’s dive into a few more features that make generators truly remarkable.
Generators can yield values, allowing them to be iterated over and return results in a lazy manner. For example:
Internally, yielding values is much like getting the result of a function. When PyEval reaches the YIELD_VALUE opcode, it pops the top value of the stack, and returns it. Quite simple, isn’t it?
Generators can use the return keyword to return a result:
As you can see, the return statement sets the StopIteration exception. Exceptions can have arguments, and here, the first argument sent to the StopIteration exception is the return value.
The return value can be retrieved by catching the exception, and getting its first argument:
We can also communicate with generators using .send() and .throw():
As you can see, we sent numbers to the generator using .send(), and they were the return value of the yield keyword.
Internally, .send() works by putting the value at the top of the generator’s stack. It then evaluates the frame, and pops the top value of the stack, putting it in our local variable.
Similarly, .throw() works by sending a throwflag to PyEval stating an exception occurred. It then handles the exception normally. If the generator did not catch it, the exception is propagated outwards, just like a normal function.
Generators can be nested (or “delegated”) using the yield from keyword:
As you can see, using yield from creates a way to communicate between the innermost generator, all the way out.
Internally, it works by using the gi_yieldfrom field of the generator object. It points to the inner generator, and when you use .send() it will go all the way in.
When the inner generator returns, it goes up the chain, and sets yield from's return value accordingly.
In this article, I provided some insight into the inner workings of the CPython generator implementation. While the article is not beginner material, it only scratches the surface of this topic, and there is much more to understanding how the interpreter works. The full implementation is of course open source, so you are welcome to explore at your will. Enjoy 😉
Some rights reserved | [
{
"code": null,
"e": 456,
"s": 171,
"text": "In this article, I’ll attempt to provide an in-depth understanding of Python generators, and how they operate from the inside. It will include the how and why. Sections will be self-contained, and you are welcome to skip at your will. Without further ado, let us begin our journey. ⛵️"
},
{
"code": null,
"e": 594,
"s": 456,
"text": "Added since Python 2.2, Generators are unique functions that can be paused, resumed and iterated over. Let’s take a look over an example:"
},
{
"code": null,
"e": 739,
"s": 594,
"text": "By defining a function that contains the yield keyword, the function is marked as a generator. We then run the generator in the following order:"
},
{
"code": null,
"e": 1133,
"s": 739,
"text": "Initialize the generator and put it in g. At this point, we have a new generator object that didn’t run yet.Advance the generator by calling next() on it. This causes the generator to advance to the first yield keyword, printing “Hello” on the way.Advance the generator again. It prints “Goodbye”, and since it reached the end of the function, it raises a StopIteration exception and finishes."
},
{
"code": null,
"e": 1242,
"s": 1133,
"text": "Initialize the generator and put it in g. At this point, we have a new generator object that didn’t run yet."
},
{
"code": null,
"e": 1383,
"s": 1242,
"text": "Advance the generator by calling next() on it. This causes the generator to advance to the first yield keyword, printing “Hello” on the way."
},
{
"code": null,
"e": 1529,
"s": 1383,
"text": "Advance the generator again. It prints “Goodbye”, and since it reached the end of the function, it raises a StopIteration exception and finishes."
},
{
"code": null,
"e": 1656,
"s": 1529,
"text": "In order to understand these three simple steps, we first need to start from the very basics of how a function in Python runs."
},
{
"code": null,
"e": 1732,
"s": 1656,
"text": "Running a function involves two main steps: Initialization, and Evaluation."
},
{
"code": null,
"e": 1795,
"s": 1732,
"text": "Under the hood, CPython runs a function inside a frame object."
},
{
"code": null,
"e": 1877,
"s": 1795,
"text": "A frame object, sometimes called a stack-frame, consists of the following fields:"
},
{
"code": null,
"e": 1942,
"s": 1877,
"text": "code object, which includes the function’s actual compiled code."
},
{
"code": null,
"e": 2009,
"s": 1942,
"text": "free stack space, called value-stack, for running the interpreter."
},
{
"code": null,
"e": 2072,
"s": 2009,
"text": "execution pointer for the current line of code being executed."
},
{
"code": null,
"e": 2119,
"s": 2072,
"text": "other fields like mappings of local variables."
},
{
"code": null,
"e": 2225,
"s": 2119,
"text": "A list of all frame fields can be seen in the code while a shorter list can be seen in the documentation."
},
{
"code": null,
"e": 2292,
"s": 2225,
"text": "When we initialize a function, a frame is created. In pseudo-code:"
},
{
"code": null,
"e": 2304,
"s": 2292,
"text": "f = Frame()"
},
{
"code": null,
"e": 2380,
"s": 2304,
"text": "The arguments we passed to the function are then assigned inside the frame:"
},
{
"code": null,
"e": 2431,
"s": 2380,
"text": "f.f_locals[\"arg1\"] = arg1f.f_locals[\"arg2\"] = arg2"
},
{
"code": null,
"e": 2515,
"s": 2431,
"text": "The execution point of the frame, is set to the first line of code in the function:"
},
{
"code": null,
"e": 2590,
"s": 2515,
"text": "f.lasti = 0 # Last Instructionf.lineno = 0 # Function line number on file"
},
{
"code": null,
"e": 2633,
"s": 2590,
"text": "At this point our function starts running."
},
{
"code": null,
"e": 2735,
"s": 2633,
"text": "Almost the entire Python interpreter can be summarized into one C-level function: PyEval_EvalFrameEx."
},
{
"code": null,
"e": 2971,
"s": 2735,
"text": "This function is the interpreter loop. Consisting of 3k lines of code, its job is to evaluate a frame, or in other words, run it. Every function in Python, every bytecode or opcode that the interpreter runs, goes through that function."
},
{
"code": null,
"e": 3089,
"s": 2971,
"text": "During “PyEval”, Python operates on the frame’s unique value-stack. This bit of information will be crucial later on."
},
{
"code": null,
"e": 3206,
"s": 3089,
"text": "In summary, when you enter a function, and run it, the interpreter creates a frame, and enters the interpreter loop."
},
{
"code": null,
"e": 3287,
"s": 3206,
"text": "A site called PythonTutor has a very nice interactive example of this mechanism."
},
{
"code": null,
"e": 3387,
"s": 3287,
"text": "Much like functions, running a generator involves the initialization step, and the evaluation step."
},
{
"code": null,
"e": 3609,
"s": 3387,
"text": "At this step we are creating the generator object. The generator object consists of the frame object and the code object. If you’re wondering, yes, the frame object also contains the code object inside it. In pseudo-code:"
},
{
"code": null,
"e": 3728,
"s": 3609,
"text": "g = Generator()f = Frame() # Initialized as beforeg.gi_frame = fg.gi_code = f.f_code = Code() # The compiled function"
},
{
"code": null,
"e": 3776,
"s": 3728,
"text": "At this point, our generator g is ready to run."
},
{
"code": null,
"e": 3862,
"s": 3776,
"text": "Every time we call next(g), the frame is evaluated using the same PyEval_EvalFrameEx."
},
{
"code": null,
"e": 4010,
"s": 3862,
"text": "The difference is, when running a generator, we can reach the yield keyword, at which point the frame evaluation stops, and the generator “pauses”."
},
{
"code": null,
"e": 4148,
"s": 4010,
"text": "A pointer in the frame is saved, marking our current stack position, in order to know exactly what was the generator state upon stopping."
},
{
"code": null,
"e": 4341,
"s": 4148,
"text": "It is important to remember, that unlike functions, when the evaluation stops the frame is not destroyed as it’s still attached to the generator object. This will allow us to load it later on."
},
{
"code": null,
"e": 4390,
"s": 4341,
"text": "PyEval returns and our calling function resumes."
},
{
"code": null,
"e": 4617,
"s": 4390,
"text": "When we advance the generator once more, the frame is loaded from gi_frame, and PyEval is called again on the same frame. It checks where we stopped, goes to our execution pointer, and uses the value-stack stored on the frame."
},
{
"code": null,
"e": 4783,
"s": 4617,
"text": "Since we’re using the same stack, and the frame also contains all of the local variables, we can continue from the exact same spot, as if the function never stopped."
},
{
"code": null,
"e": 4927,
"s": 4783,
"text": "When we reach the end of the generator, or return statement, StopIteration gets thrown, and the frame is deleted. gi_frame is then set to None."
},
{
"code": null,
"e": 5066,
"s": 4927,
"text": "Now that we know how a generator internally pauses and resumes, let’s dive into a few more features that make generators truly remarkable."
},
{
"code": null,
"e": 5179,
"s": 5066,
"text": "Generators can yield values, allowing them to be iterated over and return results in a lazy manner. For example:"
},
{
"code": null,
"e": 5374,
"s": 5179,
"text": "Internally, yielding values is much like getting the result of a function. When PyEval reaches the YIELD_VALUE opcode, it pops the top value of the stack, and returns it. Quite simple, isn’t it?"
},
{
"code": null,
"e": 5432,
"s": 5374,
"text": "Generators can use the return keyword to return a result:"
},
{
"code": null,
"e": 5620,
"s": 5432,
"text": "As you can see, the return statement sets the StopIteration exception. Exceptions can have arguments, and here, the first argument sent to the StopIteration exception is the return value."
},
{
"code": null,
"e": 5713,
"s": 5620,
"text": "The return value can be retrieved by catching the exception, and getting its first argument:"
},
{
"code": null,
"e": 5781,
"s": 5713,
"text": "We can also communicate with generators using .send() and .throw():"
},
{
"code": null,
"e": 5898,
"s": 5781,
"text": "As you can see, we sent numbers to the generator using .send(), and they were the return value of the yield keyword."
},
{
"code": null,
"e": 6082,
"s": 5898,
"text": "Internally, .send() works by putting the value at the top of the generator’s stack. It then evaluates the frame, and pops the top value of the stack, putting it in our local variable."
},
{
"code": null,
"e": 6314,
"s": 6082,
"text": "Similarly, .throw() works by sending a throwflag to PyEval stating an exception occurred. It then handles the exception normally. If the generator did not catch it, the exception is propagated outwards, just like a normal function."
},
{
"code": null,
"e": 6386,
"s": 6314,
"text": "Generators can be nested (or “delegated”) using the yield from keyword:"
},
{
"code": null,
"e": 6498,
"s": 6386,
"text": "As you can see, using yield from creates a way to communicate between the innermost generator, all the way out."
},
{
"code": null,
"e": 6662,
"s": 6498,
"text": "Internally, it works by using the gi_yieldfrom field of the generator object. It points to the inner generator, and when you use .send() it will go all the way in."
},
{
"code": null,
"e": 6766,
"s": 6662,
"text": "When the inner generator returns, it goes up the chain, and sets yield from's return value accordingly."
},
{
"code": null,
"e": 7130,
"s": 6766,
"text": "In this article, I provided some insight into the inner workings of the CPython generator implementation. While the article is not beginner material, it only scratches the surface of this topic, and there is much more to understanding how the interpreter works. The full implementation is of course open source, so you are welcome to explore at your will. Enjoy 😉"
}
] |
How can I get a list of locally installed Python modules? | There are multiple ways to get a list of locally installed Python modules. Easiest way is using the Python shell, for example,
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
BaseHTTPServer brain_nose markupbase stat
Bastion brain_numpy marshal statvfs
CGIHTTPServer brain_pkg_resources math string
Canvas brain_pytest matplotlib stringold
...
...
If you want to get the list of installed modules in your terminal, you can use the Python package manager, pip. For example,
$ pip freeze
You will get the output:
asn1crypto==0.22.0
astroid==1.5.2
attrs==16.3.0
Automat==0.5.0
backports.functools-lru-cache==1.3
cffi==1.10.0
...
If you have pip version >= 1.3, you can also use pip list. For example,
$ pip list
asn1crypto (0.22.0)
astroid (1.5.2)
attrs (16.3.0)
Automat (0.5.0)
backports.functools-lru-cache (1.3)
...
... | [
{
"code": null,
"e": 1189,
"s": 1062,
"text": "There are multiple ways to get a list of locally installed Python modules. Easiest way is using the Python shell, for example,"
},
{
"code": null,
"e": 1558,
"s": 1189,
"text": ">>> help('modules')\nPlease wait a moment while I gather a list of all available modules...\nBaseHTTPServer brain_nose markupbase stat\nBastion brain_numpy marshal statvfs\nCGIHTTPServer brain_pkg_resources math string\nCanvas brain_pytest matplotlib stringold\n...\n..."
},
{
"code": null,
"e": 1683,
"s": 1558,
"text": "If you want to get the list of installed modules in your terminal, you can use the Python package manager, pip. For example,"
},
{
"code": null,
"e": 1696,
"s": 1683,
"text": "$ pip freeze"
},
{
"code": null,
"e": 1721,
"s": 1696,
"text": "You will get the output:"
},
{
"code": null,
"e": 1836,
"s": 1721,
"text": "asn1crypto==0.22.0\nastroid==1.5.2\nattrs==16.3.0\nAutomat==0.5.0\nbackports.functools-lru-cache==1.3\ncffi==1.10.0\n..."
},
{
"code": null,
"e": 1908,
"s": 1836,
"text": "If you have pip version >= 1.3, you can also use pip list. For example,"
},
{
"code": null,
"e": 2030,
"s": 1908,
"text": "$ pip list\nasn1crypto (0.22.0)\nastroid (1.5.2)\nattrs (16.3.0)\nAutomat (0.5.0)\nbackports.functools-lru-cache (1.3)\n...\n..."
}
] |
Aggregation in MongoDB - GeeksforGeeks | 23 Mar, 2022
In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result. It is similar to the aggregate function of SQL.
MongoDB provides three ways to perform aggregation
Aggregation pipeline
Map-reduce function
Single-purpose aggregation
In MongoDB, the aggregation pipeline consists of stages and each stage transforms the document. Or in other words, the aggregation pipeline is a multi-stage pipeline, so in each state, the documents taken as input and produce the resultant set of documents now in the next stage(id available) the resultant documents taken as input and produce output, this process is going on till the last stage. The basic pipeline stages provide filters that will perform like queries and the document transformation modifies the resultant document and the other pipeline provides tools for grouping and sorting documents. You can also use the aggregation pipeline in sharded collection.
Let us discuss the aggregation pipeline with the help of an example:
In the above example of a collection of train fares in the first stage. Here, the $match stage filters the documents by the value in class field i.e. class: “first-class” and passes the document to the second stage. In the Second Stage, the $group stage groups the documents by the id field to calculate the sum of fare for each unique id.
Here, the aggregate() function is used to perform aggregation it can have three operators stages, expression and accumulator.
Stages: Each stage starts from stage operators which are:
$match: It is used for filtering the documents can reduce the amount of documents that are given as input to the next stage.
$project: It is used to select some specific fields from a collection.
$group: It is used to group documents based on some value.
$sort: It is used to sort the document that is rearranging them
$skip: It is used to skip n number of documents and passes the remaining documents
$limit: It is used to pass first n number of documents thus limiting them.
$unwind: It is used to unwind documents that are using arrays i.e. it deconstructs an array field in the documents to return documents for each element.
$out: It is used to write resulting documents to a new collection
Expressions: It refers to the name of the field in input documents for e.g. { $group : { _id : “$id“, total:{$sum:”$fare“}}} here $id and $fare are expressions.
Accumulators: These are basically used in the group stage
sum: It sums numeric values for the documents in each group
count: It counts total numbers of documents
avg: It calculates the average of all given values from all documents
min: It gets the minimum value from all the documents
max: It gets the maximum value from all the documents
first: It gets the first document from the grouping
last: It gets the last document from the grouping
Note:
in $group _id is Mandatory field
$out must be the last stage in the pipeline
$sum:1 will count the number of documents and $sum:”$fare” will give the sum of total fare generated per id.
Examples:
In the following examples, we are working with:
Database: GeeksForGeeks
Collection: students
Documents: Seven documents that contain the details of the students in the form of field-value pairs.
Displaying the total number of students in one section only
db.students.aggregate([{$match:{sec:"B"}},{$count:"Total student in sec:B"}])
In this example, for taking a count of the number of students in section B we first filter the documents using the $match operator, and then we use the $count accumulator to count the total number of documents that are passed after filtering from the $match.
Displaying the total number of students in both the sections and maximum age from both section
db.students.aggregate([{$group: {_id:"$sec", total_st: {$sum:1}, max_age:{$max:"$age"} } }])
In this example, we use $group to group, so that we can count for every other section in the documents, here $sum sums up the document in each group and $max accumulator is applied on age expression which will find the maximum age in each document.
Displaying details of students whose age is greater than 30 using match stage
db.students.aggregate([{$match:{age:{$gt:30}}}])
In this example, we display students whose age is greater than 30. So we use the $match operator to filter out the documents.
Sorting the students on the basis of age
db.students.aggregate([{'$sort': {'age': 1}}])
In this example, we are using the $sort operator to sort in ascending order we provide ‘age’:1 if we want to sort in descending order we can simply change 1 to -1 i.e. ‘age’:-1.
Displaying details of a student having the largest age in the section – B
db.students.aggregate([{$match:{sec:"B"}},{'$sort': {'age': -1}},{$limit:1}])
In this example, first, we only select those documents that have section B, so for that, we use the $match operator then we sort the documents in descending order using $sort by setting ‘age’:-1 and then to only show the topmost result we use $limit.
Unwinding students on the basis of subject
Unwinding works on array here in our collection we have array of subjects (which consists of different subjects inside it like math, physics, English, etc) so unwinding will be done on that i.e. the array will be deconstructed and the output will have only one subject not an array of subjects which were there earlier.
db.students.aggregate([{$unwind:"$subject"}])
Map reduce is used for aggregating results for the large volume of data. Map reduce has two main functions one is a map that groups all the documents and the second one is the reduce which performs operation on the grouped data.
Syntax:
db.collectionName.mapReduce(mappingFunction, reduceFunction, {out:'Result'});
Example:
In the following example, we are working with:
Database: GeeksForGeeks
Collection: studentsMark
Documents: Seven documents that contain the details of the students in the form of field-value pairs.
var mapfunction = function(){emit(this.age, this.marks)}
var reducefunction = function(key, values){return Array.sum(values)}
db.studentsMarks.mapReduce(mapfunction, reducefunction, {'out':'Result'})
Now, we will group the documents on the basis of age and find total marks in each age group. So, we will create two variables first mapfunction which will emit age as a key (expressed as “_id” in the output) and marks as value this emitted data is passed to our reducefunction, which takes key and value as grouped data, and then it performs operations over it. After performing reduction the results are stored in a collection here in this case the collection is Results.
It is used when we need simple access to document like counting the number of documents or for finding all distinct values in a document. It simply provides the access to the common aggregation process using the count(), distinct(), and estimatedDocumentCount() methods, so due to which it lacks the flexibility and capabilities of the pipeline.
Example:
In the following example, we are working with:
Database: GeeksForGeeks
Collection: studentsMark
Documents: Seven documents that contain the details of the students in the form of field-value pairs.
Displaying distinct names and ages (non-repeating)
db.studentsMarks.distinct("name")
Here, we use a distinct() method that finds distinct values of the specified field(i.e., name).
Counting the total numbers of documents
db.studentsMarks.count()
Here, we use count() to find the total number of the document, unlike find() method it does not find all the document rather it counts them and return a number.
rkbhola5
MongoDB
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
MongoDB - Distinct() Method
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Update() Method
Create user and add role in MongoDB
MongoDB - sort() Method | [
{
"code": null,
"e": 23859,
"s": 23831,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 24212,
"s": 23859,
"text": "In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result. It is similar to the aggregate function of SQL."
},
{
"code": null,
"e": 24263,
"s": 24212,
"text": "MongoDB provides three ways to perform aggregation"
},
{
"code": null,
"e": 24284,
"s": 24263,
"text": "Aggregation pipeline"
},
{
"code": null,
"e": 24304,
"s": 24284,
"text": "Map-reduce function"
},
{
"code": null,
"e": 24331,
"s": 24304,
"text": "Single-purpose aggregation"
},
{
"code": null,
"e": 25005,
"s": 24331,
"text": "In MongoDB, the aggregation pipeline consists of stages and each stage transforms the document. Or in other words, the aggregation pipeline is a multi-stage pipeline, so in each state, the documents taken as input and produce the resultant set of documents now in the next stage(id available) the resultant documents taken as input and produce output, this process is going on till the last stage. The basic pipeline stages provide filters that will perform like queries and the document transformation modifies the resultant document and the other pipeline provides tools for grouping and sorting documents. You can also use the aggregation pipeline in sharded collection."
},
{
"code": null,
"e": 25074,
"s": 25005,
"text": "Let us discuss the aggregation pipeline with the help of an example:"
},
{
"code": null,
"e": 25415,
"s": 25074,
"text": "In the above example of a collection of train fares in the first stage. Here, the $match stage filters the documents by the value in class field i.e. class: “first-class” and passes the document to the second stage. In the Second Stage, the $group stage groups the documents by the id field to calculate the sum of fare for each unique id. "
},
{
"code": null,
"e": 25541,
"s": 25415,
"text": "Here, the aggregate() function is used to perform aggregation it can have three operators stages, expression and accumulator."
},
{
"code": null,
"e": 25599,
"s": 25541,
"text": "Stages: Each stage starts from stage operators which are:"
},
{
"code": null,
"e": 25724,
"s": 25599,
"text": "$match: It is used for filtering the documents can reduce the amount of documents that are given as input to the next stage."
},
{
"code": null,
"e": 25795,
"s": 25724,
"text": "$project: It is used to select some specific fields from a collection."
},
{
"code": null,
"e": 25854,
"s": 25795,
"text": "$group: It is used to group documents based on some value."
},
{
"code": null,
"e": 25918,
"s": 25854,
"text": "$sort: It is used to sort the document that is rearranging them"
},
{
"code": null,
"e": 26001,
"s": 25918,
"text": "$skip: It is used to skip n number of documents and passes the remaining documents"
},
{
"code": null,
"e": 26076,
"s": 26001,
"text": "$limit: It is used to pass first n number of documents thus limiting them."
},
{
"code": null,
"e": 26229,
"s": 26076,
"text": "$unwind: It is used to unwind documents that are using arrays i.e. it deconstructs an array field in the documents to return documents for each element."
},
{
"code": null,
"e": 26295,
"s": 26229,
"text": "$out: It is used to write resulting documents to a new collection"
},
{
"code": null,
"e": 26456,
"s": 26295,
"text": "Expressions: It refers to the name of the field in input documents for e.g. { $group : { _id : “$id“, total:{$sum:”$fare“}}} here $id and $fare are expressions."
},
{
"code": null,
"e": 26514,
"s": 26456,
"text": "Accumulators: These are basically used in the group stage"
},
{
"code": null,
"e": 26574,
"s": 26514,
"text": "sum: It sums numeric values for the documents in each group"
},
{
"code": null,
"e": 26618,
"s": 26574,
"text": "count: It counts total numbers of documents"
},
{
"code": null,
"e": 26688,
"s": 26618,
"text": "avg: It calculates the average of all given values from all documents"
},
{
"code": null,
"e": 26742,
"s": 26688,
"text": "min: It gets the minimum value from all the documents"
},
{
"code": null,
"e": 26796,
"s": 26742,
"text": "max: It gets the maximum value from all the documents"
},
{
"code": null,
"e": 26848,
"s": 26796,
"text": "first: It gets the first document from the grouping"
},
{
"code": null,
"e": 26898,
"s": 26848,
"text": "last: It gets the last document from the grouping"
},
{
"code": null,
"e": 26904,
"s": 26898,
"text": "Note:"
},
{
"code": null,
"e": 26937,
"s": 26904,
"text": "in $group _id is Mandatory field"
},
{
"code": null,
"e": 26981,
"s": 26937,
"text": "$out must be the last stage in the pipeline"
},
{
"code": null,
"e": 27090,
"s": 26981,
"text": "$sum:1 will count the number of documents and $sum:”$fare” will give the sum of total fare generated per id."
},
{
"code": null,
"e": 27100,
"s": 27090,
"text": "Examples:"
},
{
"code": null,
"e": 27148,
"s": 27100,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 27172,
"s": 27148,
"text": "Database: GeeksForGeeks"
},
{
"code": null,
"e": 27193,
"s": 27172,
"text": "Collection: students"
},
{
"code": null,
"e": 27295,
"s": 27193,
"text": "Documents: Seven documents that contain the details of the students in the form of field-value pairs."
},
{
"code": null,
"e": 27356,
"s": 27295,
"text": "Displaying the total number of students in one section only "
},
{
"code": null,
"e": 27434,
"s": 27356,
"text": "db.students.aggregate([{$match:{sec:\"B\"}},{$count:\"Total student in sec:B\"}])"
},
{
"code": null,
"e": 27693,
"s": 27434,
"text": "In this example, for taking a count of the number of students in section B we first filter the documents using the $match operator, and then we use the $count accumulator to count the total number of documents that are passed after filtering from the $match."
},
{
"code": null,
"e": 27788,
"s": 27693,
"text": "Displaying the total number of students in both the sections and maximum age from both section"
},
{
"code": null,
"e": 27881,
"s": 27788,
"text": "db.students.aggregate([{$group: {_id:\"$sec\", total_st: {$sum:1}, max_age:{$max:\"$age\"} } }])"
},
{
"code": null,
"e": 28131,
"s": 27881,
"text": "In this example, we use $group to group, so that we can count for every other section in the documents, here $sum sums up the document in each group and $max accumulator is applied on age expression which will find the maximum age in each document. "
},
{
"code": null,
"e": 28210,
"s": 28131,
"text": "Displaying details of students whose age is greater than 30 using match stage "
},
{
"code": null,
"e": 28259,
"s": 28210,
"text": "db.students.aggregate([{$match:{age:{$gt:30}}}])"
},
{
"code": null,
"e": 28385,
"s": 28259,
"text": "In this example, we display students whose age is greater than 30. So we use the $match operator to filter out the documents."
},
{
"code": null,
"e": 28427,
"s": 28385,
"text": "Sorting the students on the basis of age "
},
{
"code": null,
"e": 28474,
"s": 28427,
"text": "db.students.aggregate([{'$sort': {'age': 1}}])"
},
{
"code": null,
"e": 28652,
"s": 28474,
"text": "In this example, we are using the $sort operator to sort in ascending order we provide ‘age’:1 if we want to sort in descending order we can simply change 1 to -1 i.e. ‘age’:-1."
},
{
"code": null,
"e": 28727,
"s": 28652,
"text": "Displaying details of a student having the largest age in the section – B "
},
{
"code": null,
"e": 28805,
"s": 28727,
"text": "db.students.aggregate([{$match:{sec:\"B\"}},{'$sort': {'age': -1}},{$limit:1}])"
},
{
"code": null,
"e": 29056,
"s": 28805,
"text": "In this example, first, we only select those documents that have section B, so for that, we use the $match operator then we sort the documents in descending order using $sort by setting ‘age’:-1 and then to only show the topmost result we use $limit."
},
{
"code": null,
"e": 29100,
"s": 29056,
"text": "Unwinding students on the basis of subject "
},
{
"code": null,
"e": 29420,
"s": 29100,
"text": "Unwinding works on array here in our collection we have array of subjects (which consists of different subjects inside it like math, physics, English, etc) so unwinding will be done on that i.e. the array will be deconstructed and the output will have only one subject not an array of subjects which were there earlier."
},
{
"code": null,
"e": 29467,
"s": 29420,
"text": "db.students.aggregate([{$unwind:\"$subject\"}]) "
},
{
"code": null,
"e": 29696,
"s": 29467,
"text": "Map reduce is used for aggregating results for the large volume of data. Map reduce has two main functions one is a map that groups all the documents and the second one is the reduce which performs operation on the grouped data."
},
{
"code": null,
"e": 29704,
"s": 29696,
"text": "Syntax:"
},
{
"code": null,
"e": 29782,
"s": 29704,
"text": "db.collectionName.mapReduce(mappingFunction, reduceFunction, {out:'Result'});"
},
{
"code": null,
"e": 29791,
"s": 29782,
"text": "Example:"
},
{
"code": null,
"e": 29838,
"s": 29791,
"text": "In the following example, we are working with:"
},
{
"code": null,
"e": 29862,
"s": 29838,
"text": "Database: GeeksForGeeks"
},
{
"code": null,
"e": 29887,
"s": 29862,
"text": "Collection: studentsMark"
},
{
"code": null,
"e": 29989,
"s": 29887,
"text": "Documents: Seven documents that contain the details of the students in the form of field-value pairs."
},
{
"code": null,
"e": 30189,
"s": 29989,
"text": "var mapfunction = function(){emit(this.age, this.marks)}\nvar reducefunction = function(key, values){return Array.sum(values)}\ndb.studentsMarks.mapReduce(mapfunction, reducefunction, {'out':'Result'})"
},
{
"code": null,
"e": 30662,
"s": 30189,
"text": "Now, we will group the documents on the basis of age and find total marks in each age group. So, we will create two variables first mapfunction which will emit age as a key (expressed as “_id” in the output) and marks as value this emitted data is passed to our reducefunction, which takes key and value as grouped data, and then it performs operations over it. After performing reduction the results are stored in a collection here in this case the collection is Results."
},
{
"code": null,
"e": 31008,
"s": 30662,
"text": "It is used when we need simple access to document like counting the number of documents or for finding all distinct values in a document. It simply provides the access to the common aggregation process using the count(), distinct(), and estimatedDocumentCount() methods, so due to which it lacks the flexibility and capabilities of the pipeline."
},
{
"code": null,
"e": 31017,
"s": 31008,
"text": "Example:"
},
{
"code": null,
"e": 31064,
"s": 31017,
"text": "In the following example, we are working with:"
},
{
"code": null,
"e": 31088,
"s": 31064,
"text": "Database: GeeksForGeeks"
},
{
"code": null,
"e": 31113,
"s": 31088,
"text": "Collection: studentsMark"
},
{
"code": null,
"e": 31215,
"s": 31113,
"text": "Documents: Seven documents that contain the details of the students in the form of field-value pairs."
},
{
"code": null,
"e": 31267,
"s": 31215,
"text": "Displaying distinct names and ages (non-repeating) "
},
{
"code": null,
"e": 31301,
"s": 31267,
"text": "db.studentsMarks.distinct(\"name\")"
},
{
"code": null,
"e": 31397,
"s": 31301,
"text": "Here, we use a distinct() method that finds distinct values of the specified field(i.e., name)."
},
{
"code": null,
"e": 31437,
"s": 31397,
"text": "Counting the total numbers of documents"
},
{
"code": null,
"e": 31462,
"s": 31437,
"text": "db.studentsMarks.count()"
},
{
"code": null,
"e": 31623,
"s": 31462,
"text": "Here, we use count() to find the total number of the document, unlike find() method it does not find all the document rather it counts them and return a number."
},
{
"code": null,
"e": 31632,
"s": 31623,
"text": "rkbhola5"
},
{
"code": null,
"e": 31640,
"s": 31632,
"text": "MongoDB"
},
{
"code": null,
"e": 31647,
"s": 31640,
"text": "Picked"
},
{
"code": null,
"e": 31655,
"s": 31647,
"text": "MongoDB"
},
{
"code": null,
"e": 31753,
"s": 31655,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31762,
"s": 31753,
"text": "Comments"
},
{
"code": null,
"e": 31775,
"s": 31762,
"text": "Old Comments"
},
{
"code": null,
"e": 31803,
"s": 31775,
"text": "MongoDB - Distinct() Method"
},
{
"code": null,
"e": 31841,
"s": 31803,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 31866,
"s": 31841,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 31893,
"s": 31866,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 31950,
"s": 31893,
"text": "MongoDB insertMany() Method - db.Collection.insertMany()"
},
{
"code": null,
"e": 32005,
"s": 31950,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 32031,
"s": 32005,
"text": "MongoDB - Update() Method"
},
{
"code": null,
"e": 32067,
"s": 32031,
"text": "Create user and add role in MongoDB"
}
] |
Order By date ASC in MySQL? | You can use STR_TO_DATE() function. Let us first create a table −
mysql> create table DemoTable
(
AdmissionDate varchar(200)
);
Query OK, 0 rows affected (1.19 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values('12-01-2019');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('14-12-2016');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('26-04-2018');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable values('31-05-2013');
Query OK, 1 row affected (0.30 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+---------------+
| AdmissionDate |
+---------------+
| 12-01-2019 |
| 14-12-2016 |
| 26-04-2018 |
| 31-05-2013 |
+---------------+
4 rows in set (0.00 sec)
Following is the query to sort order by date ASC −
mysql> select *from DemoTable ORDER BY STR_TO_DATE(AdmissionDate,'%d-%m-%Y') ASC;
This will produce the following output −
+---------------+
| AdmissionDate |
+---------------+
| 31-05-2013 |
| 14-12-2016 |
| 26-04-2018 |
| 12-01-2019 |
+---------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1128,
"s": 1062,
"text": "You can use STR_TO_DATE() function. Let us first create a table −"
},
{
"code": null,
"e": 1236,
"s": 1128,
"text": "mysql> create table DemoTable\n (\n AdmissionDate varchar(200)\n );\nQuery OK, 0 rows affected (1.19 sec)"
},
{
"code": null,
"e": 1287,
"s": 1236,
"text": "Insert records in the table using insert command −"
},
{
"code": null,
"e": 1635,
"s": 1287,
"text": "mysql> insert into DemoTable values('12-01-2019');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('14-12-2016');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('26-04-2018');\nQuery OK, 1 row affected (0.34 sec)\nmysql> insert into DemoTable values('31-05-2013');\nQuery OK, 1 row affected (0.30 sec)"
},
{
"code": null,
"e": 1695,
"s": 1635,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1727,
"s": 1695,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 1768,
"s": 1727,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1937,
"s": 1768,
"text": "+---------------+\n| AdmissionDate |\n+---------------+\n| 12-01-2019 |\n| 14-12-2016 |\n| 26-04-2018 |\n| 31-05-2013 |\n+---------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1988,
"s": 1937,
"text": "Following is the query to sort order by date ASC −"
},
{
"code": null,
"e": 2070,
"s": 1988,
"text": "mysql> select *from DemoTable ORDER BY STR_TO_DATE(AdmissionDate,'%d-%m-%Y') ASC;"
},
{
"code": null,
"e": 2111,
"s": 2070,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2280,
"s": 2111,
"text": "+---------------+\n| AdmissionDate |\n+---------------+\n| 31-05-2013 |\n| 14-12-2016 |\n| 26-04-2018 |\n| 12-01-2019 |\n+---------------+\n4 rows in set (0.00 sec)"
}
] |
Java - The ArrayList Class | The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
Following is the list of the constructors provided by the ArrayList class.
ArrayList( )
This constructor builds an empty array list.
ArrayList(Collection c)
This constructor builds an array list that is initialized with the elements of the collection c.
ArrayList(int capacity)
This constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.
Apart from the methods inherited from its parent classes, ArrayList defines the following methods −
void add(int index, Object element)
Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()).
boolean add(Object o)
Appends the specified element to the end of this list.
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException, if the specified collection is null.
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
void clear()
Removes all of the elements from this list.
Object clone()
Returns a shallow copy of this ArrayList.
boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
void ensureCapacity(int minCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
Object get(int index)
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).
int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Object remove(int index)
Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if the index out is of range (index < 0 || index >= size()).
protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.
Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).
int size()
Returns the number of elements in this list.
Object[] toArray()
Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.
void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
The following program illustrates several of the methods supported by ArrayList −
import java.util.*;
public class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
This will produce the following result −
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2512,
"s": 2377,
"text": "The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed."
},
{
"code": null,
"e": 2690,
"s": 2512,
"text": "Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold."
},
{
"code": null,
"e": 2857,
"s": 2690,
"text": "Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk."
},
{
"code": null,
"e": 2932,
"s": 2857,
"text": "Following is the list of the constructors provided by the ArrayList class."
},
{
"code": null,
"e": 2945,
"s": 2932,
"text": "ArrayList( )"
},
{
"code": null,
"e": 2990,
"s": 2945,
"text": "This constructor builds an empty array list."
},
{
"code": null,
"e": 3014,
"s": 2990,
"text": "ArrayList(Collection c)"
},
{
"code": null,
"e": 3111,
"s": 3014,
"text": "This constructor builds an array list that is initialized with the elements of the collection c."
},
{
"code": null,
"e": 3135,
"s": 3111,
"text": "ArrayList(int capacity)"
},
{
"code": null,
"e": 3372,
"s": 3135,
"text": "This constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list."
},
{
"code": null,
"e": 3472,
"s": 3372,
"text": "Apart from the methods inherited from its parent classes, ArrayList defines the following methods −"
},
{
"code": null,
"e": 3508,
"s": 3472,
"text": "void add(int index, Object element)"
},
{
"code": null,
"e": 3688,
"s": 3508,
"text": "Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size())."
},
{
"code": null,
"e": 3710,
"s": 3688,
"text": "boolean add(Object o)"
},
{
"code": null,
"e": 3765,
"s": 3710,
"text": "Appends the specified element to the end of this list."
},
{
"code": null,
"e": 3794,
"s": 3765,
"text": "boolean addAll(Collection c)"
},
{
"code": null,
"e": 4017,
"s": 3794,
"text": "Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException, if the specified collection is null."
},
{
"code": null,
"e": 4057,
"s": 4017,
"text": "boolean addAll(int index, Collection c)"
},
{
"code": null,
"e": 4230,
"s": 4057,
"text": "Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null."
},
{
"code": null,
"e": 4243,
"s": 4230,
"text": "void clear()"
},
{
"code": null,
"e": 4287,
"s": 4243,
"text": "Removes all of the elements from this list."
},
{
"code": null,
"e": 4302,
"s": 4287,
"text": "Object clone()"
},
{
"code": null,
"e": 4344,
"s": 4302,
"text": "Returns a shallow copy of this ArrayList."
},
{
"code": null,
"e": 4371,
"s": 4344,
"text": "boolean contains(Object o)"
},
{
"code": null,
"e": 4559,
"s": 4371,
"text": "Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))."
},
{
"code": null,
"e": 4596,
"s": 4559,
"text": "void ensureCapacity(int minCapacity)"
},
{
"code": null,
"e": 4764,
"s": 4596,
"text": "Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument."
},
{
"code": null,
"e": 4786,
"s": 4764,
"text": "Object get(int index)"
},
{
"code": null,
"e": 4951,
"s": 4786,
"text": " Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size())."
},
{
"code": null,
"e": 4973,
"s": 4951,
"text": "int indexOf(Object o)"
},
{
"code": null,
"e": 5103,
"s": 4973,
"text": "Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element."
},
{
"code": null,
"e": 5129,
"s": 5103,
"text": "int lastIndexOf(Object o)"
},
{
"code": null,
"e": 5258,
"s": 5129,
"text": "Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element."
},
{
"code": null,
"e": 5283,
"s": 5258,
"text": "Object remove(int index)"
},
{
"code": null,
"e": 5437,
"s": 5283,
"text": "Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if the index out is of range (index < 0 || index >= size())."
},
{
"code": null,
"e": 5493,
"s": 5437,
"text": "protected void removeRange(int fromIndex, int toIndex)"
},
{
"code": null,
"e": 5604,
"s": 5493,
"text": "Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive."
},
{
"code": null,
"e": 5642,
"s": 5604,
"text": "Object set(int index, Object element)"
},
{
"code": null,
"e": 5834,
"s": 5642,
"text": "Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size())."
},
{
"code": null,
"e": 5845,
"s": 5834,
"text": "int size()"
},
{
"code": null,
"e": 5890,
"s": 5845,
"text": "Returns the number of elements in this list."
},
{
"code": null,
"e": 5909,
"s": 5890,
"text": "Object[] toArray()"
},
{
"code": null,
"e": 6052,
"s": 5909,
"text": "Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null."
},
{
"code": null,
"e": 6081,
"s": 6052,
"text": "Object[] toArray(Object[] a)"
},
{
"code": null,
"e": 6236,
"s": 6081,
"text": " Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array."
},
{
"code": null,
"e": 6254,
"s": 6236,
"text": "void trimToSize()"
},
{
"code": null,
"e": 6331,
"s": 6254,
"text": "Trims the capacity of this ArrayList instance to be the list's current size."
},
{
"code": null,
"e": 6413,
"s": 6331,
"text": "The following program illustrates several of the methods supported by ArrayList −"
},
{
"code": null,
"e": 7185,
"s": 6413,
"text": "import java.util.*;\npublic class ArrayListDemo {\n\n public static void main(String args[]) {\n // create an array list\n ArrayList al = new ArrayList();\n System.out.println(\"Initial size of al: \" + al.size());\n\n // add elements to the array list\n al.add(\"C\");\n al.add(\"A\");\n al.add(\"E\");\n al.add(\"B\");\n al.add(\"D\");\n al.add(\"F\");\n al.add(1, \"A2\");\n System.out.println(\"Size of al after additions: \" + al.size());\n\n // display the array list\n System.out.println(\"Contents of al: \" + al);\n\n // Remove elements from the array list\n al.remove(\"F\");\n al.remove(2);\n System.out.println(\"Size of al after deletions: \" + al.size());\n System.out.println(\"Contents of al: \" + al);\n }\n}"
},
{
"code": null,
"e": 7226,
"s": 7185,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 7381,
"s": 7226,
"text": "Initial size of al: 0\nSize of al after additions: 7\nContents of al: [C, A2, A, E, B, D, F]\nSize of al after deletions: 5\nContents of al: [C, A2, E, B, D]\n"
},
{
"code": null,
"e": 7414,
"s": 7381,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7430,
"s": 7414,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7463,
"s": 7430,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7479,
"s": 7463,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7514,
"s": 7479,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7528,
"s": 7514,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7562,
"s": 7528,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7576,
"s": 7562,
"text": " Tushar Kale"
},
{
"code": null,
"e": 7613,
"s": 7576,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7628,
"s": 7613,
"text": " Monica Mittal"
},
{
"code": null,
"e": 7661,
"s": 7628,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7680,
"s": 7661,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7687,
"s": 7680,
"text": " Print"
},
{
"code": null,
"e": 7698,
"s": 7687,
"text": " Add Notes"
}
] |
How to convert Unicode values to characters in JavaScript? | To convert Unicode values to characters in JavaScript, use the fromCharCode() string method.
You can try to run the following code to convert Unicode to character −
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var a = String.fromCharCode(72);
document.write("Character: "+a);
</script>
</body>
</html> | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To convert Unicode values to characters in JavaScript, use the fromCharCode() string method."
},
{
"code": null,
"e": 1227,
"s": 1155,
"text": "You can try to run the following code to convert Unicode to character −"
},
{
"code": null,
"e": 1237,
"s": 1227,
"text": "Live Demo"
},
{
"code": null,
"e": 1404,
"s": 1237,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n var a = String.fromCharCode(72);\n document.write(\"Character: \"+a);\n </script>\n </body>\n</html>"
}
] |
Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java - GeeksforGeeks | 08 Mar, 2021
In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHashSet, and TreeSet in java.
Differences Between HashSet, LinkedHashSet, and TreeSet:
Features
HashSet
LinkedHashSet
TreeSet
Internal Working
HashSet internally uses HashMap for storing objects
LinkedHashSet uses LinkedHashMap internally to store objects
TreeSet uses TreeMap internally to store objects
When To Use
If you don’t want to maintain insertion order but want to store unique objects
If you want to maintain the insertion order of elements then you can use LinkedHashSet
If you want to sort the elements according to some Comparator then use TreeSet
Order
HashSet does not maintain insertion order
LinkedHashSet maintains the insertion order of objects
While TreeSet orders the elements according to supplied Comparator. By default, objects will be placed according to their natural ascending order.
Complexity of Operations
HashSet gives O(1) complexity for insertion, removing, and retrieving objects
LinkedHashSet gives insertion, removing, and retrieving operations performance in order O(1).
While TreeSet gives the performance of order O(log(n)) for insertion, removing, and retrieving operations.
Performance
The performance of HashSet is better when compared to LinkedHashSet and TreeSet.
The performance of LinkedHashSet is slower than TreeSet. It is almost similar to HashSet but slower because LinkedHashSet internally maintains LinkedList to maintain the insertion order of elements
TreeSet performance is better than LinkedHashSet except for insertion and removal operations because it has to sort the elements after each insertion and removal operation.
Compare
HashSet uses equals() and hashCode() methods to compare the objects
LinkedHashSet uses equals() and hashCode() methods to compare it’s objects
TreeSet uses compare() and compareTo() methods to compare the objects
Null Elements
HashSet allows only one null value.
LinkedHashSet allows only one null value.
TreeSet does not permit null value. If you insert null value into TreeSet, it will throw NullPointerException.
Syntax
HashSet obj = new HashSet();
LinkedHashSet obj = new LinkedHashSet();
TreeSet obj = new TreeSet();
Differences Between HashSet, LinkedHashSet, and TreeSet According to Insertion Order and Time Taken:
Java
// Java program to demonstrate difference between// HashSet, LinkedHashSet and TreeSet according// to insertion order and insertion time import java.util.Arrays;import java.util.HashSet;import java.util.LinkedHashSet;import java.util.TreeSet; class GFG1 { // Function show insertion order of // LinkedHashSet, TreeSet and HashSet private static void insertionOrder() { LinkedHashSet<String> geekLinkSet = new LinkedHashSet<>(); TreeSet<String> geekTreeSet = new TreeSet<>(); HashSet<String> geekHashSet = new HashSet<String>(); // Add three object in // LinkedHashSet and TreeSet for (String str : Arrays.asList("Geek2", "Geek1", "Geek3", "Geek1")) { geekLinkSet.add(str); geekTreeSet.add(str); geekHashSet.add(str); } // should be sorted order HashSet // stores element in sorted order System.out.println("Insertion Order" + " of objects in HashSet :" + geekHashSet); // insertion order or elements LinkedHashSet // storeds elements as insertion System.out.println("Insertion Order of " + "objects in LinkedHashSet :" + geekLinkSet); // should be sorted order TreeSet // stores element in sorted order System.out.println("Insertion Order of" + " objects in TreeSet :" + geekTreeSet); } // Function calculate insertion time of // 1000 objects of LinkedHashSet, // TreeSet and HashSet private static void insertionTime() { // HashSet performance Test // inserting 1000 elements HashSet<Integer> numbersHS = new HashSet<>(); long startTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { numbersHS.add(i); } long endTime = System.nanoTime(); System.out.println("Total time to insert" + " 1000 elements in" + " HashSet in nanoseconds: " + (endTime - startTime)); // LinkedHashSet performance Test // inserting 1000 elements LinkedHashSet<Integer> numbersLLS = new LinkedHashSet<>(); startTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { numbersLLS.add(i); } endTime = System.nanoTime(); System.out.println("Total time to insert" + " 1000 elements in" + " LinkedHashSet nanoseconds: " + (endTime - startTime)); // TreeSet performance Test inserting 1000 objects TreeSet<Integer> numbersTS = new TreeSet<>(); startTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { numbersTS.add(i); } endTime = System.nanoTime(); System.out.println("Total time to insert" + " 1000 elements in" + " TreeSet in nanoseconds: " + (endTime - startTime)); } // Function calculate deletion time // of 1000 objects LinkedHashSet, // TreeSet and HashSet // Deletion time always vary private static void deletion() { // HashSet performance Test inserting // and deletion 1000 elements HashSet<Integer> deletionHS = new HashSet<>(); for (int i = 0; i < 1000; i++) { deletionHS.add(i); } long startingTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { deletionHS.remove(i); } long endedTime = System.nanoTime(); System.out.println( "Total time to Deletion " + "1000 elements in HashSet in nanoseconds: " + Math.abs(startingTime - endedTime)); // LinkedHashSet performance Test inserting // and deletion 1000 elements LinkedHashSet<Integer> deletionLLS = new LinkedHashSet<>(); for (int i = 0; i < 1000; i++) { deletionLLS.add(i); } startingTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { deletionLLS.remove(i); } endedTime = System.nanoTime(); System.out.println( "Total time to Deletion 1000" + " elements in LinkedHashSet in nanoseconds: " + Math.abs(startingTime - endedTime)); // TreeSet performance Test inserting // and deletion 1000 elements TreeSet<Integer> deletionTS = new TreeSet<>(); for (int i = 0; i < 1000; i++) { deletionTS.add(i); } startingTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { deletionTS.remove(i); } endedTime = System.nanoTime(); System.out.println( "Total time to Deletion 1000" + " elements in TreeSet in nanoseconds: " + Math.abs(startingTime - endedTime)); } public static void main(String args[]) { insertionOrder(); insertionTime(); deletion(); }}
Insertion Order of objects in HashSet :[Geek3, Geek2, Geek1]
Insertion Order of objects in LinkedHashSet :[Geek2, Geek1, Geek3]
Insertion Order of objects in TreeSet :[Geek1, Geek2, Geek3]
Total time to insert 1000 elements in HashSet in nanoseconds: 791869
Total time to insert 1000 elements in LinkedHashSet nanoseconds: 882417
Total time to insert 1000 elements in TreeSet in nanoseconds: 11797657
Total time to Deletion 1000 elements in HashSet in nanoseconds: 834509
Total time to Deletion 1000 elements in LinkedHashSet in nanoseconds: 898922
Total time to Deletion 1000 elements in TreeSet in nanoseconds: 7437577
Similarities Between HashSet, LinkedHashSet, and TreeSet:
Duplicates: HashSet, LinkedHashSet and TreeSet are implements Set interface, so they are not allowed to store duplicates objects.
Thread-safe: If we want to use HashSet, LinkedHashSet, and TreeSet in a multi-threading environment then first we make it externally synchronized because both LinkedHashSet and TreeSet are not thread-safe.
All three are Cloneable and Serializable.
When to use HashSet, TreeSet, and LinkedHashSet in Java:
HashSet: If you don’t want to maintain insertion order but want to store unique objects. LinkedHashSet: If you want to maintain the insertion order of elements then you can use LinkedHashSet. TreeSet: If you want to sort the elements according to some Comparator then use TreeSet.
HashSet: If you don’t want to maintain insertion order but want to store unique objects.
LinkedHashSet: If you want to maintain the insertion order of elements then you can use LinkedHashSet.
TreeSet: If you want to sort the elements according to some Comparator then use TreeSet.
So as you see the output of the above program according to that and according to your requirements, you can choose anyone from HashSet, TreeSet, and LinkedHashSet.
07lokeshsharma
taruntomar
Java - util package
Java-Collections
java-hashset
java-LinkedHashSet
Java-Set-Programs
java-treeset
Technical Scripter 2018
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
HashMap in Java with Examples
Arrays.sort() in Java with examples
Interfaces in Java
How to iterate any Map in Java | [
{
"code": null,
"e": 25184,
"s": 25156,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 25512,
"s": 25184,
"text": "In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHashSet, and TreeSet in java."
},
{
"code": null,
"e": 25570,
"s": 25512,
"text": "Differences Between HashSet, LinkedHashSet, and TreeSet: "
},
{
"code": null,
"e": 25579,
"s": 25570,
"text": "Features"
},
{
"code": null,
"e": 25587,
"s": 25579,
"text": "HashSet"
},
{
"code": null,
"e": 25601,
"s": 25587,
"text": "LinkedHashSet"
},
{
"code": null,
"e": 25609,
"s": 25601,
"text": "TreeSet"
},
{
"code": null,
"e": 25626,
"s": 25609,
"text": "Internal Working"
},
{
"code": null,
"e": 25678,
"s": 25626,
"text": "HashSet internally uses HashMap for storing objects"
},
{
"code": null,
"e": 25739,
"s": 25678,
"text": "LinkedHashSet uses LinkedHashMap internally to store objects"
},
{
"code": null,
"e": 25788,
"s": 25739,
"text": "TreeSet uses TreeMap internally to store objects"
},
{
"code": null,
"e": 25800,
"s": 25788,
"text": "When To Use"
},
{
"code": null,
"e": 25879,
"s": 25800,
"text": "If you don’t want to maintain insertion order but want to store unique objects"
},
{
"code": null,
"e": 25966,
"s": 25879,
"text": "If you want to maintain the insertion order of elements then you can use LinkedHashSet"
},
{
"code": null,
"e": 26045,
"s": 25966,
"text": "If you want to sort the elements according to some Comparator then use TreeSet"
},
{
"code": null,
"e": 26051,
"s": 26045,
"text": "Order"
},
{
"code": null,
"e": 26093,
"s": 26051,
"text": "HashSet does not maintain insertion order"
},
{
"code": null,
"e": 26148,
"s": 26093,
"text": "LinkedHashSet maintains the insertion order of objects"
},
{
"code": null,
"e": 26295,
"s": 26148,
"text": "While TreeSet orders the elements according to supplied Comparator. By default, objects will be placed according to their natural ascending order."
},
{
"code": null,
"e": 26320,
"s": 26295,
"text": "Complexity of Operations"
},
{
"code": null,
"e": 26398,
"s": 26320,
"text": "HashSet gives O(1) complexity for insertion, removing, and retrieving objects"
},
{
"code": null,
"e": 26492,
"s": 26398,
"text": "LinkedHashSet gives insertion, removing, and retrieving operations performance in order O(1)."
},
{
"code": null,
"e": 26599,
"s": 26492,
"text": "While TreeSet gives the performance of order O(log(n)) for insertion, removing, and retrieving operations."
},
{
"code": null,
"e": 26611,
"s": 26599,
"text": "Performance"
},
{
"code": null,
"e": 26692,
"s": 26611,
"text": "The performance of HashSet is better when compared to LinkedHashSet and TreeSet."
},
{
"code": null,
"e": 26890,
"s": 26692,
"text": "The performance of LinkedHashSet is slower than TreeSet. It is almost similar to HashSet but slower because LinkedHashSet internally maintains LinkedList to maintain the insertion order of elements"
},
{
"code": null,
"e": 27063,
"s": 26890,
"text": "TreeSet performance is better than LinkedHashSet except for insertion and removal operations because it has to sort the elements after each insertion and removal operation."
},
{
"code": null,
"e": 27071,
"s": 27063,
"text": "Compare"
},
{
"code": null,
"e": 27139,
"s": 27071,
"text": "HashSet uses equals() and hashCode() methods to compare the objects"
},
{
"code": null,
"e": 27214,
"s": 27139,
"text": "LinkedHashSet uses equals() and hashCode() methods to compare it’s objects"
},
{
"code": null,
"e": 27284,
"s": 27214,
"text": "TreeSet uses compare() and compareTo() methods to compare the objects"
},
{
"code": null,
"e": 27298,
"s": 27284,
"text": "Null Elements"
},
{
"code": null,
"e": 27334,
"s": 27298,
"text": "HashSet allows only one null value."
},
{
"code": null,
"e": 27376,
"s": 27334,
"text": "LinkedHashSet allows only one null value."
},
{
"code": null,
"e": 27487,
"s": 27376,
"text": "TreeSet does not permit null value. If you insert null value into TreeSet, it will throw NullPointerException."
},
{
"code": null,
"e": 27494,
"s": 27487,
"text": "Syntax"
},
{
"code": null,
"e": 27523,
"s": 27494,
"text": "HashSet obj = new HashSet();"
},
{
"code": null,
"e": 27564,
"s": 27523,
"text": "LinkedHashSet obj = new LinkedHashSet();"
},
{
"code": null,
"e": 27593,
"s": 27564,
"text": "TreeSet obj = new TreeSet();"
},
{
"code": null,
"e": 27695,
"s": 27593,
"text": "Differences Between HashSet, LinkedHashSet, and TreeSet According to Insertion Order and Time Taken: "
},
{
"code": null,
"e": 27700,
"s": 27695,
"text": "Java"
},
{
"code": "// Java program to demonstrate difference between// HashSet, LinkedHashSet and TreeSet according// to insertion order and insertion time import java.util.Arrays;import java.util.HashSet;import java.util.LinkedHashSet;import java.util.TreeSet; class GFG1 { // Function show insertion order of // LinkedHashSet, TreeSet and HashSet private static void insertionOrder() { LinkedHashSet<String> geekLinkSet = new LinkedHashSet<>(); TreeSet<String> geekTreeSet = new TreeSet<>(); HashSet<String> geekHashSet = new HashSet<String>(); // Add three object in // LinkedHashSet and TreeSet for (String str : Arrays.asList(\"Geek2\", \"Geek1\", \"Geek3\", \"Geek1\")) { geekLinkSet.add(str); geekTreeSet.add(str); geekHashSet.add(str); } // should be sorted order HashSet // stores element in sorted order System.out.println(\"Insertion Order\" + \" of objects in HashSet :\" + geekHashSet); // insertion order or elements LinkedHashSet // storeds elements as insertion System.out.println(\"Insertion Order of \" + \"objects in LinkedHashSet :\" + geekLinkSet); // should be sorted order TreeSet // stores element in sorted order System.out.println(\"Insertion Order of\" + \" objects in TreeSet :\" + geekTreeSet); } // Function calculate insertion time of // 1000 objects of LinkedHashSet, // TreeSet and HashSet private static void insertionTime() { // HashSet performance Test // inserting 1000 elements HashSet<Integer> numbersHS = new HashSet<>(); long startTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { numbersHS.add(i); } long endTime = System.nanoTime(); System.out.println(\"Total time to insert\" + \" 1000 elements in\" + \" HashSet in nanoseconds: \" + (endTime - startTime)); // LinkedHashSet performance Test // inserting 1000 elements LinkedHashSet<Integer> numbersLLS = new LinkedHashSet<>(); startTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { numbersLLS.add(i); } endTime = System.nanoTime(); System.out.println(\"Total time to insert\" + \" 1000 elements in\" + \" LinkedHashSet nanoseconds: \" + (endTime - startTime)); // TreeSet performance Test inserting 1000 objects TreeSet<Integer> numbersTS = new TreeSet<>(); startTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { numbersTS.add(i); } endTime = System.nanoTime(); System.out.println(\"Total time to insert\" + \" 1000 elements in\" + \" TreeSet in nanoseconds: \" + (endTime - startTime)); } // Function calculate deletion time // of 1000 objects LinkedHashSet, // TreeSet and HashSet // Deletion time always vary private static void deletion() { // HashSet performance Test inserting // and deletion 1000 elements HashSet<Integer> deletionHS = new HashSet<>(); for (int i = 0; i < 1000; i++) { deletionHS.add(i); } long startingTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { deletionHS.remove(i); } long endedTime = System.nanoTime(); System.out.println( \"Total time to Deletion \" + \"1000 elements in HashSet in nanoseconds: \" + Math.abs(startingTime - endedTime)); // LinkedHashSet performance Test inserting // and deletion 1000 elements LinkedHashSet<Integer> deletionLLS = new LinkedHashSet<>(); for (int i = 0; i < 1000; i++) { deletionLLS.add(i); } startingTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { deletionLLS.remove(i); } endedTime = System.nanoTime(); System.out.println( \"Total time to Deletion 1000\" + \" elements in LinkedHashSet in nanoseconds: \" + Math.abs(startingTime - endedTime)); // TreeSet performance Test inserting // and deletion 1000 elements TreeSet<Integer> deletionTS = new TreeSet<>(); for (int i = 0; i < 1000; i++) { deletionTS.add(i); } startingTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { deletionTS.remove(i); } endedTime = System.nanoTime(); System.out.println( \"Total time to Deletion 1000\" + \" elements in TreeSet in nanoseconds: \" + Math.abs(startingTime - endedTime)); } public static void main(String args[]) { insertionOrder(); insertionTime(); deletion(); }}",
"e": 32892,
"s": 27700,
"text": null
},
{
"code": null,
"e": 33513,
"s": 32892,
"text": "Insertion Order of objects in HashSet :[Geek3, Geek2, Geek1]\nInsertion Order of objects in LinkedHashSet :[Geek2, Geek1, Geek3]\nInsertion Order of objects in TreeSet :[Geek1, Geek2, Geek3]\nTotal time to insert 1000 elements in HashSet in nanoseconds: 791869\nTotal time to insert 1000 elements in LinkedHashSet nanoseconds: 882417\nTotal time to insert 1000 elements in TreeSet in nanoseconds: 11797657\nTotal time to Deletion 1000 elements in HashSet in nanoseconds: 834509\nTotal time to Deletion 1000 elements in LinkedHashSet in nanoseconds: 898922\nTotal time to Deletion 1000 elements in TreeSet in nanoseconds: 7437577"
},
{
"code": null,
"e": 33571,
"s": 33513,
"text": "Similarities Between HashSet, LinkedHashSet, and TreeSet:"
},
{
"code": null,
"e": 33702,
"s": 33571,
"text": "Duplicates: HashSet, LinkedHashSet and TreeSet are implements Set interface, so they are not allowed to store duplicates objects. "
},
{
"code": null,
"e": 33910,
"s": 33702,
"text": "Thread-safe: If we want to use HashSet, LinkedHashSet, and TreeSet in a multi-threading environment then first we make it externally synchronized because both LinkedHashSet and TreeSet are not thread-safe. "
},
{
"code": null,
"e": 33952,
"s": 33910,
"text": "All three are Cloneable and Serializable."
},
{
"code": null,
"e": 34010,
"s": 33952,
"text": "When to use HashSet, TreeSet, and LinkedHashSet in Java: "
},
{
"code": null,
"e": 34291,
"s": 34010,
"text": "HashSet: If you don’t want to maintain insertion order but want to store unique objects. LinkedHashSet: If you want to maintain the insertion order of elements then you can use LinkedHashSet. TreeSet: If you want to sort the elements according to some Comparator then use TreeSet."
},
{
"code": null,
"e": 34381,
"s": 34291,
"text": "HashSet: If you don’t want to maintain insertion order but want to store unique objects. "
},
{
"code": null,
"e": 34485,
"s": 34381,
"text": "LinkedHashSet: If you want to maintain the insertion order of elements then you can use LinkedHashSet. "
},
{
"code": null,
"e": 34574,
"s": 34485,
"text": "TreeSet: If you want to sort the elements according to some Comparator then use TreeSet."
},
{
"code": null,
"e": 34738,
"s": 34574,
"text": "So as you see the output of the above program according to that and according to your requirements, you can choose anyone from HashSet, TreeSet, and LinkedHashSet."
},
{
"code": null,
"e": 34753,
"s": 34738,
"text": "07lokeshsharma"
},
{
"code": null,
"e": 34764,
"s": 34753,
"text": "taruntomar"
},
{
"code": null,
"e": 34784,
"s": 34764,
"text": "Java - util package"
},
{
"code": null,
"e": 34801,
"s": 34784,
"text": "Java-Collections"
},
{
"code": null,
"e": 34814,
"s": 34801,
"text": "java-hashset"
},
{
"code": null,
"e": 34833,
"s": 34814,
"text": "java-LinkedHashSet"
},
{
"code": null,
"e": 34851,
"s": 34833,
"text": "Java-Set-Programs"
},
{
"code": null,
"e": 34864,
"s": 34851,
"text": "java-treeset"
},
{
"code": null,
"e": 34888,
"s": 34864,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 34893,
"s": 34888,
"text": "Java"
},
{
"code": null,
"e": 34912,
"s": 34893,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34917,
"s": 34912,
"text": "Java"
},
{
"code": null,
"e": 34934,
"s": 34917,
"text": "Java-Collections"
},
{
"code": null,
"e": 35032,
"s": 34934,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35047,
"s": 35032,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35091,
"s": 35047,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35113,
"s": 35091,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 35128,
"s": 35113,
"text": "Stream In Java"
},
{
"code": null,
"e": 35179,
"s": 35128,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 35204,
"s": 35179,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35234,
"s": 35204,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 35270,
"s": 35234,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 35289,
"s": 35270,
"text": "Interfaces in Java"
}
] |
What are the differences between the BLOB and TEXT datatypes in MySQL? | BLOB stands for Binary Large Objects and as its name suggests, it can be used for storing binary data while TEXT is used for storing large number of strings. BLOB can be used to store binary data that means we can store pictures, videos, sounds and programs also.
For example, the following image can be stored into BLOB because the image has binary data.
BLOB values behave like byte string and BLOB does not have a character set. Therefore, comparison and sorting is fully dependent upon numeric values of bytes.
TEXT values behave like non-binary string or character string. TEXT has a character set and the comparison/ sorting fully depends upon the collection of character set.
mysql> create table TextTableDemo
-> (
-> Address TEXT
-> );
Query OK, 0 rows affected (0.58 sec)
To describe tables with the help of DESC command.
mysql> DESC TextTableDemo;
The following is the output.
+---------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+------+------+-----+---------+-------+
| Address | TEXT | YES | | NULL | |
+---------+------+------+-----+---------+-------+
1 row in set (0.08 sec)
In the above output, “Type” is telling the data type, which is TEXT.
mysql> create table BlobTableDemo
-> (
-> Images BLOB
-> );
Query OK, 0 rows affected (0.51 sec)
Let us get the description of the table with the help of DESC command.
mysql> desc BlobTableDemo;
The following is the output.
+--------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------+------+-----+---------+-------+
| Images | BLOB | YES | | NULL | |
+--------+------+------+-----+---------+-------+
1 row in set (0.04 sec)
In the sample output, “Type” is telling the data type which is BLOB. | [
{
"code": null,
"e": 1326,
"s": 1062,
"text": "BLOB stands for Binary Large Objects and as its name suggests, it can be used for storing binary data while TEXT is used for storing large number of strings. BLOB can be used to store binary data that means we can store pictures, videos, sounds and programs also."
},
{
"code": null,
"e": 1418,
"s": 1326,
"text": "For example, the following image can be stored into BLOB because the image has binary data."
},
{
"code": null,
"e": 1577,
"s": 1418,
"text": "BLOB values behave like byte string and BLOB does not have a character set. Therefore, comparison and sorting is fully dependent upon numeric values of bytes."
},
{
"code": null,
"e": 1745,
"s": 1577,
"text": "TEXT values behave like non-binary string or character string. TEXT has a character set and the comparison/ sorting fully depends upon the collection of character set."
},
{
"code": null,
"e": 1852,
"s": 1745,
"text": "mysql> create table TextTableDemo\n -> (\n -> Address TEXT\n -> );\nQuery OK, 0 rows affected (0.58 sec)"
},
{
"code": null,
"e": 1902,
"s": 1852,
"text": "To describe tables with the help of DESC command."
},
{
"code": null,
"e": 1929,
"s": 1902,
"text": "mysql> DESC TextTableDemo;"
},
{
"code": null,
"e": 1958,
"s": 1929,
"text": "The following is the output."
},
{
"code": null,
"e": 2233,
"s": 1958,
"text": "+---------+------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+---------+------+------+-----+---------+-------+\n| Address | TEXT | YES | | NULL | |\n+---------+------+------+-----+---------+-------+\n1 row in set (0.08 sec)\n"
},
{
"code": null,
"e": 2302,
"s": 2233,
"text": "In the above output, “Type” is telling the data type, which is TEXT."
},
{
"code": null,
"e": 2408,
"s": 2302,
"text": "mysql> create table BlobTableDemo\n -> (\n -> Images BLOB\n -> );\nQuery OK, 0 rows affected (0.51 sec)"
},
{
"code": null,
"e": 2479,
"s": 2408,
"text": "Let us get the description of the table with the help of DESC command."
},
{
"code": null,
"e": 2506,
"s": 2479,
"text": "mysql> desc BlobTableDemo;"
},
{
"code": null,
"e": 2535,
"s": 2506,
"text": "The following is the output."
},
{
"code": null,
"e": 2805,
"s": 2535,
"text": "+--------+------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------+------+------+-----+---------+-------+\n| Images | BLOB | YES | | NULL | |\n+--------+------+------+-----+---------+-------+\n1 row in set (0.04 sec)\n"
},
{
"code": null,
"e": 2874,
"s": 2805,
"text": "In the sample output, “Type” is telling the data type which is BLOB."
}
] |
Java Program for Rabin-Karp Algorithm for Pattern Searching - GeeksforGeeks | 11 Dec, 2018
Examples:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10
Input: txt[] = "AABAACAADAABAABA"
pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match.Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings.
1) Pattern itself.2) All the substrings of text of length m.
Java
// Following program is a Java implementation// of Rabin Karp Algorithm given in the CLRS book public class Main { // d is the number of characters in the input alphabet public final static int d = 256; /* pat -> pattern txt -> text q -> A prime number */ static void search(String pat, String txt, int q) { int M = pat.length(); int N = txt.length(); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be "pow(d, M-1)%q" for (i = 0; i < M - 1; i++) h = (h * d) % q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d * p + pat.charAt(i)) % q; t = (d * t + txt.charAt(i)) % q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters on by one if (p == t) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt.charAt(i + j) != pat.charAt(j)) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) System.out.println("Pattern found at index " + i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if (i < N - M) { t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + M)) % q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } } } /* Driver program to test above function */ public static void main(String[] args) { String txt = "GEEKS FOR GEEKS"; String pat = "GEEK"; int q = 101; // A prime number search(pat, txt, q); }} // This code is contributed by nuclode
Pattern found at index 0
Pattern found at index 10
Please refer complete article on Rabin-Karp Algorithm for Pattern Searching for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Java Programming Examples
How to Iterate HashMap in Java?
Iterate through List in Java
Min Heap in Java
Traverse Through a HashMap in Java
Java Program to Remove Duplicate Elements From the Array
Dijkstra's shortest path algorithm in Java using PriorityQueue
Iterate Over the Characters of a String in Java
Java program to count the occurrence of each character in a string using Hashmap
Hashing in Java | [
{
"code": null,
"e": 24824,
"s": 24796,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 24834,
"s": 24824,
"text": "Examples:"
},
{
"code": null,
"e": 25092,
"s": 24834,
"text": "Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\nOutput: Pattern found at index 10\n\nInput: txt[] = \"AABAACAADAABAABA\"\n pat[] = \"AABA\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12\n\n"
},
{
"code": null,
"e": 25663,
"s": 25092,
"text": "The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match.Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings."
},
{
"code": null,
"e": 25724,
"s": 25663,
"text": "1) Pattern itself.2) All the substrings of text of length m."
},
{
"code": null,
"e": 25729,
"s": 25724,
"text": "Java"
},
{
"code": "// Following program is a Java implementation// of Rabin Karp Algorithm given in the CLRS book public class Main { // d is the number of characters in the input alphabet public final static int d = 256; /* pat -> pattern txt -> text q -> A prime number */ static void search(String pat, String txt, int q) { int M = pat.length(); int N = txt.length(); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be \"pow(d, M-1)%q\" for (i = 0; i < M - 1; i++) h = (h * d) % q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d * p + pat.charAt(i)) % q; t = (d * t + txt.charAt(i)) % q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters on by one if (p == t) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt.charAt(i + j) != pat.charAt(j)) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) System.out.println(\"Pattern found at index \" + i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if (i < N - M) { t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + M)) % q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } } } /* Driver program to test above function */ public static void main(String[] args) { String txt = \"GEEKS FOR GEEKS\"; String pat = \"GEEK\"; int q = 101; // A prime number search(pat, txt, q); }} // This code is contributed by nuclode",
"e": 27920,
"s": 25729,
"text": null
},
{
"code": null,
"e": 27972,
"s": 27920,
"text": "Pattern found at index 0\nPattern found at index 10\n"
},
{
"code": null,
"e": 28066,
"s": 27972,
"text": "Please refer complete article on Rabin-Karp Algorithm for Pattern Searching for more details!"
},
{
"code": null,
"e": 28080,
"s": 28066,
"text": "Java Programs"
},
{
"code": null,
"e": 28178,
"s": 28080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28187,
"s": 28178,
"text": "Comments"
},
{
"code": null,
"e": 28200,
"s": 28187,
"text": "Old Comments"
},
{
"code": null,
"e": 28226,
"s": 28200,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28258,
"s": 28226,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 28287,
"s": 28258,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 28304,
"s": 28287,
"text": "Min Heap in Java"
},
{
"code": null,
"e": 28339,
"s": 28304,
"text": "Traverse Through a HashMap in Java"
},
{
"code": null,
"e": 28396,
"s": 28339,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 28459,
"s": 28396,
"text": "Dijkstra's shortest path algorithm in Java using PriorityQueue"
},
{
"code": null,
"e": 28507,
"s": 28459,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 28588,
"s": 28507,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
}
] |
Design a Logistics System - GeeksforGeeks | 28 Jun, 2021
Design a Logistics System (Object Oriented Design). Tell about the different classes and their relationships with each-other. It is not a System Design question, so scope of this question is only to define different classes (with it’s attributes and methods)Asked In: AdobeSolution: Let’s assume we want to design a Logistics System with following basic functionality:• The system can take an order to deliver it to a given destination. • The order will be a list of items and there is a cost of each order to process. • User has to register himself / herself to use this system. • User can track his / her order. • Orders will be shipped by bike or truck, but only a single order will be shipped by a single vehicle.These type of questions are asked in interviews to Judge the Object Oriented Design skill of a candidate. So, first of all we should think about the classes.The main classes will be:1. User 2. Item 3. Vehicle 4. Location 5. payment details 6. Order 7. LogisticsSystemThe User class is for users/clients/customers, who will be charged to get their items delivered.
Java
public class User { private int userId; private String name; private Location address; private String mobNo; private String emailId; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Location getAddress() { return address; } public void setAddress(Location address) { this.address = address; } public String getMobNo() { return mobNo; } public void setMobNo(String mobNo) { this.mobNo = mobNo; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; }}
Item class represents an item which will be shipped. An order will contain a list of items.
Java
public class Item { private String name; private int price; private int volume; private int weight; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getVolume() { return volume; } public void setVolume(int volume) { this.volume = volume; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; }}
Location class simply represents the address.
Java
public class Location { private Double longitude; private Double latitude; public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; }}
The Vehicle class represents the vehicle which will be used to ship/deliver an order. It will be of two types: 1. Bike and 2. Truck
Java
public class Vehicle { private int id; private String vehicleNo; private int capacity; private Location currentPosition; private VehicleStatus currentStatus; public Vehicle(int id, String vehicleNo, int capacity) { this.id = id; this.vehicleNo = vehicleNo; this.capacity = capacity; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getVehicleNo() { return vehicleNo; } public void setVehicleNo(String vehicleNo) { this.vehicleNo = vehicleNo; } public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } public Location getCurrentPosition() { return currentPosition; } public void setCurrentPosition(Location currentPosition) { this.currentPosition = currentPosition; } public VehicleStatus getCurrentStatus() { return currentStatus; } public void setCurrentStatus(VehicleStatus currentStatus) { this.currentStatus = currentStatus; }}
The bike has only 10 unit of capacity.
Java
public class Bike extends Vehicle { private final static int capacityofBike = 10; public Bike(int id, String vehicleNo) { super(id, vehicleNo, capacityofBike); }}
The truck has only 100 unit of capacity (10 times more than bike).
Java
public class Truck extends Vehicle { private final static int capacityofTruck = 100; public Truck(int id, String vehicleNo) { super(id, vehicleNo, capacityofTruck); }}
Enum for current status of a vehicle:
Java
public enum VehicleStatus { FREE, BUSY, NOT_WORKING;}
Enum for OrderPriority:
Java
public enum OrderPriority { LOW, MEDIUM, HIGH;}
Enum for OrderStatus:
Java
public enum OrderStatus { DELIVERED, PROCESSING, CANCELLED;}
Enum for PaymentMode:
Java
public enum PaymentMode { NET_BANKING, CREDIT_CARD, DEBIT_CARD;}
Enum for PaymentStatus:
Java
public enum PaymentStatus { PAID, UNPAID;}
The PaymentDetails class contains the information of payment related things so that in any case the order is cancelled, it can be refunded easily.
Java
public class PaymentDetails { private PaymentMode paymentMode; private String transactionId; private int amount; private PaymentStatus paymentStatus; private String cardNumber; public PaymentMode getPaymentMode() { return paymentMode; } public void setPaymentMode(PaymentMode paymentMode) { this.paymentMode = paymentMode; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public PaymentStatus getPaymentStatus() { return paymentStatus; } public void setPaymentStatus(PaymentStatus paymentStatus) { this.paymentStatus = paymentStatus; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; }}
The Order class contains all the information of an order. All fields are self-explanatory.
Java
import java.util.Date;import java.util.List; public class Order { private int orderId; private OrderPriority priority_of_order; private User sender; private Location destination; private PaymentDetails paymentDetails; private List<Item> items; private Long totalWeight; private OrderStatus currentStatus; private Date timeOfOrderPlaced; private Date timeOfOrderDelivery; private Vehicle vehicleOfThisOrder; public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public OrderPriority getPriority_of_order() { return priority_of_order; } public void setPriority_of_order(OrderPriority priority_of_order) { this.priority_of_order = priority_of_order; } public User getSender() { return sender; } public void setSender(User sender) { this.sender = sender; } public Location getDestination() { return destination; } public void setDestination(Location destination) { this.destination = destination; } public PaymentDetails getPaymentDetails() { return paymentDetails; } public void setPaymentDetails(PaymentDetails paymentDetails) { this.paymentDetails = paymentDetails; } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } public Long getTotalWeight() { return totalWeight; } public void setTotalWeight(Long totalWeight) { this.totalWeight = totalWeight; } public OrderStatus getCurrentStatus() { return currentStatus; } public void setCurrentStatus(OrderStatus currentStatus) { this.currentStatus = currentStatus; } public Date getTimeOfOrderPlaced() { return timeOfOrderPlaced; } public void setTimeOfOrderPlaced(Date timeOfOrderPlaced) { this.timeOfOrderPlaced = timeOfOrderPlaced; } public Date getTimeOfOrderDelivery() { return timeOfOrderDelivery; } public void setTimeOfOrderDelivery(Date timeOfOrderDelivery) { this.timeOfOrderDelivery = timeOfOrderDelivery; } public Vehicle getVehicleOfThisOrder() { return vehicleOfThisOrder; } public void setVehicleOfThisOrder(Vehicle vehicleOfThisOrder) { this.vehicleOfThisOrder = vehicleOfThisOrder; }}
The main class (LogisticsSystem) which stores all the information of users, orders and vehicles. It has the methods like takeAnOrder(), processOrder() etc.
Java
import java.util.ArrayList;import java.util.List; public class LogisticsSystem { private List<Order> orders; private List<Vehicle> vehicles; private List<User> users; public LogisticsSystem() { this.orders = new ArrayList<Order>(); this.vehicles = new ArrayList<Vehicle>(); this.users = new ArrayList<User>(); } public void takeAnOrder(Order order) { System.out.println("Adding an order to the system"); orders.add(order); } public void processOrder(Order order) { System.out.println("Processing an order of the system"); } public Location trackOrder(int orderId) { System.out.println("Tracking an order of the system"); Location location = null; // location = findLocationOfGivenOrder(); return location; } public void cacelOrder(Order order) { System.out.println("Going to cancell an order of the system"); } public void registerNewUser(User user) { System.out.println("Registering a new user to the system"); users.add(user); } public List<Order> getOrders() { return orders; } public void setOrders(List<Order> orders) { this.orders = orders; } public List<Vehicle> getVehicles() { return vehicles; } public void setVehicles(List<Vehicle> vehicles) { this.vehicles = vehicles; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; }}
This is the test class to test the application.
Java
package com.shashi.oodesign; import java.util.ArrayList;import java.util.Date;import java.util.List; public class Apptest { public static void main(String[] args) { User user = new User(); user.setUserId(1); user.setName("Shashi"); user.setEmailId("[email protected]"); Item item1 = new Item(); item1.setName("item1"); item1.setPrice(20); Item item2 = new Item(); item2.setName("item2"); item2.setPrice(40); List<Item> items = new ArrayList<Item>(); items.add(item1); items.add(item2); PaymentDetails paymentDetails = new PaymentDetails(); paymentDetails.setAmount(100); paymentDetails.setPaymentMode(PaymentMode.CREDIT_CARD); paymentDetails.setCardNumber("12345678"); Location destination = new Location(); destination.setLatitude(73.23); destination.setLongitude(132.34); Order order = new Order(); order.setOrderId(1); order.setItems(items); order.setCurrentStatus(OrderStatus.PROCESSING); order.setDestination(destination); order.setPaymentDetails(paymentDetails); order.setTimeOfOrderDelivery(new Date()); LogisticsSystem logisticsSystem = new LogisticsSystem(); logisticsSystem.registerNewUser(user); logisticsSystem.takeAnOrder(order); logisticsSystem.processOrder(order); }}
clintra
Adobe
Object-Oriented-Design
Technical Scripter 2018
Design Pattern
Adobe
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
Factory method design pattern in Java
Builder Design Pattern
MVC Design Pattern
Java Singleton Design Pattern Practices with Examples
Unified Modeling Language (UML) | An Introduction
Adapter Pattern
Unified Modeling Language (UML) | Activity Diagrams
Introduction of Programming Paradigms
How to prevent Singleton Pattern from Reflection, Serialization and Cloning? | [
{
"code": null,
"e": 25068,
"s": 25040,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26150,
"s": 25068,
"text": "Design a Logistics System (Object Oriented Design). Tell about the different classes and their relationships with each-other. It is not a System Design question, so scope of this question is only to define different classes (with it’s attributes and methods)Asked In: AdobeSolution: Let’s assume we want to design a Logistics System with following basic functionality:• The system can take an order to deliver it to a given destination. • The order will be a list of items and there is a cost of each order to process. • User has to register himself / herself to use this system. • User can track his / her order. • Orders will be shipped by bike or truck, but only a single order will be shipped by a single vehicle.These type of questions are asked in interviews to Judge the Object Oriented Design skill of a candidate. So, first of all we should think about the classes.The main classes will be:1. User 2. Item 3. Vehicle 4. Location 5. payment details 6. Order 7. LogisticsSystemThe User class is for users/clients/customers, who will be charged to get their items delivered. "
},
{
"code": null,
"e": 26155,
"s": 26150,
"text": "Java"
},
{
"code": "public class User { private int userId; private String name; private Location address; private String mobNo; private String emailId; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Location getAddress() { return address; } public void setAddress(Location address) { this.address = address; } public String getMobNo() { return mobNo; } public void setMobNo(String mobNo) { this.mobNo = mobNo; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; }}",
"e": 27007,
"s": 26155,
"text": null
},
{
"code": null,
"e": 27100,
"s": 27007,
"text": "Item class represents an item which will be shipped. An order will contain a list of items. "
},
{
"code": null,
"e": 27105,
"s": 27100,
"text": "Java"
},
{
"code": "public class Item { private String name; private int price; private int volume; private int weight; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getVolume() { return volume; } public void setVolume(int volume) { this.volume = volume; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; }}",
"e": 27751,
"s": 27105,
"text": null
},
{
"code": null,
"e": 27799,
"s": 27751,
"text": "Location class simply represents the address. "
},
{
"code": null,
"e": 27804,
"s": 27799,
"text": "Java"
},
{
"code": "public class Location { private Double longitude; private Double latitude; public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; }}",
"e": 28201,
"s": 27804,
"text": null
},
{
"code": null,
"e": 28334,
"s": 28201,
"text": "The Vehicle class represents the vehicle which will be used to ship/deliver an order. It will be of two types: 1. Bike and 2. Truck "
},
{
"code": null,
"e": 28339,
"s": 28334,
"text": "Java"
},
{
"code": "public class Vehicle { private int id; private String vehicleNo; private int capacity; private Location currentPosition; private VehicleStatus currentStatus; public Vehicle(int id, String vehicleNo, int capacity) { this.id = id; this.vehicleNo = vehicleNo; this.capacity = capacity; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getVehicleNo() { return vehicleNo; } public void setVehicleNo(String vehicleNo) { this.vehicleNo = vehicleNo; } public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } public Location getCurrentPosition() { return currentPosition; } public void setCurrentPosition(Location currentPosition) { this.currentPosition = currentPosition; } public VehicleStatus getCurrentStatus() { return currentStatus; } public void setCurrentStatus(VehicleStatus currentStatus) { this.currentStatus = currentStatus; }}",
"e": 29490,
"s": 28339,
"text": null
},
{
"code": null,
"e": 29530,
"s": 29490,
"text": "The bike has only 10 unit of capacity. "
},
{
"code": null,
"e": 29535,
"s": 29530,
"text": "Java"
},
{
"code": "public class Bike extends Vehicle { private final static int capacityofBike = 10; public Bike(int id, String vehicleNo) { super(id, vehicleNo, capacityofBike); }}",
"e": 29720,
"s": 29535,
"text": null
},
{
"code": null,
"e": 29788,
"s": 29720,
"text": "The truck has only 100 unit of capacity (10 times more than bike). "
},
{
"code": null,
"e": 29793,
"s": 29788,
"text": "Java"
},
{
"code": "public class Truck extends Vehicle { private final static int capacityofTruck = 100; public Truck(int id, String vehicleNo) { super(id, vehicleNo, capacityofTruck); }}",
"e": 29982,
"s": 29793,
"text": null
},
{
"code": null,
"e": 30021,
"s": 29982,
"text": "Enum for current status of a vehicle: "
},
{
"code": null,
"e": 30026,
"s": 30021,
"text": "Java"
},
{
"code": "public enum VehicleStatus { FREE, BUSY, NOT_WORKING;}",
"e": 30089,
"s": 30026,
"text": null
},
{
"code": null,
"e": 30114,
"s": 30089,
"text": "Enum for OrderPriority: "
},
{
"code": null,
"e": 30119,
"s": 30114,
"text": "Java"
},
{
"code": "public enum OrderPriority { LOW, MEDIUM, HIGH;}",
"e": 30176,
"s": 30119,
"text": null
},
{
"code": null,
"e": 30199,
"s": 30176,
"text": "Enum for OrderStatus: "
},
{
"code": null,
"e": 30204,
"s": 30199,
"text": "Java"
},
{
"code": "public enum OrderStatus { DELIVERED, PROCESSING, CANCELLED;}",
"e": 30274,
"s": 30204,
"text": null
},
{
"code": null,
"e": 30297,
"s": 30274,
"text": "Enum for PaymentMode: "
},
{
"code": null,
"e": 30302,
"s": 30297,
"text": "Java"
},
{
"code": "public enum PaymentMode { NET_BANKING, CREDIT_CARD, DEBIT_CARD;}",
"e": 30377,
"s": 30302,
"text": null
},
{
"code": null,
"e": 30402,
"s": 30377,
"text": "Enum for PaymentStatus: "
},
{
"code": null,
"e": 30407,
"s": 30402,
"text": "Java"
},
{
"code": "public enum PaymentStatus { PAID, UNPAID;}",
"e": 30456,
"s": 30407,
"text": null
},
{
"code": null,
"e": 30604,
"s": 30456,
"text": "The PaymentDetails class contains the information of payment related things so that in any case the order is cancelled, it can be refunded easily. "
},
{
"code": null,
"e": 30609,
"s": 30604,
"text": "Java"
},
{
"code": "public class PaymentDetails { private PaymentMode paymentMode; private String transactionId; private int amount; private PaymentStatus paymentStatus; private String cardNumber; public PaymentMode getPaymentMode() { return paymentMode; } public void setPaymentMode(PaymentMode paymentMode) { this.paymentMode = paymentMode; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public PaymentStatus getPaymentStatus() { return paymentStatus; } public void setPaymentStatus(PaymentStatus paymentStatus) { this.paymentStatus = paymentStatus; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; }}",
"e": 31668,
"s": 30609,
"text": null
},
{
"code": null,
"e": 31760,
"s": 31668,
"text": "The Order class contains all the information of an order. All fields are self-explanatory. "
},
{
"code": null,
"e": 31765,
"s": 31760,
"text": "Java"
},
{
"code": "import java.util.Date;import java.util.List; public class Order { private int orderId; private OrderPriority priority_of_order; private User sender; private Location destination; private PaymentDetails paymentDetails; private List<Item> items; private Long totalWeight; private OrderStatus currentStatus; private Date timeOfOrderPlaced; private Date timeOfOrderDelivery; private Vehicle vehicleOfThisOrder; public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public OrderPriority getPriority_of_order() { return priority_of_order; } public void setPriority_of_order(OrderPriority priority_of_order) { this.priority_of_order = priority_of_order; } public User getSender() { return sender; } public void setSender(User sender) { this.sender = sender; } public Location getDestination() { return destination; } public void setDestination(Location destination) { this.destination = destination; } public PaymentDetails getPaymentDetails() { return paymentDetails; } public void setPaymentDetails(PaymentDetails paymentDetails) { this.paymentDetails = paymentDetails; } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } public Long getTotalWeight() { return totalWeight; } public void setTotalWeight(Long totalWeight) { this.totalWeight = totalWeight; } public OrderStatus getCurrentStatus() { return currentStatus; } public void setCurrentStatus(OrderStatus currentStatus) { this.currentStatus = currentStatus; } public Date getTimeOfOrderPlaced() { return timeOfOrderPlaced; } public void setTimeOfOrderPlaced(Date timeOfOrderPlaced) { this.timeOfOrderPlaced = timeOfOrderPlaced; } public Date getTimeOfOrderDelivery() { return timeOfOrderDelivery; } public void setTimeOfOrderDelivery(Date timeOfOrderDelivery) { this.timeOfOrderDelivery = timeOfOrderDelivery; } public Vehicle getVehicleOfThisOrder() { return vehicleOfThisOrder; } public void setVehicleOfThisOrder(Vehicle vehicleOfThisOrder) { this.vehicleOfThisOrder = vehicleOfThisOrder; }}",
"e": 34233,
"s": 31765,
"text": null
},
{
"code": null,
"e": 34390,
"s": 34233,
"text": "The main class (LogisticsSystem) which stores all the information of users, orders and vehicles. It has the methods like takeAnOrder(), processOrder() etc. "
},
{
"code": null,
"e": 34395,
"s": 34390,
"text": "Java"
},
{
"code": "import java.util.ArrayList;import java.util.List; public class LogisticsSystem { private List<Order> orders; private List<Vehicle> vehicles; private List<User> users; public LogisticsSystem() { this.orders = new ArrayList<Order>(); this.vehicles = new ArrayList<Vehicle>(); this.users = new ArrayList<User>(); } public void takeAnOrder(Order order) { System.out.println(\"Adding an order to the system\"); orders.add(order); } public void processOrder(Order order) { System.out.println(\"Processing an order of the system\"); } public Location trackOrder(int orderId) { System.out.println(\"Tracking an order of the system\"); Location location = null; // location = findLocationOfGivenOrder(); return location; } public void cacelOrder(Order order) { System.out.println(\"Going to cancell an order of the system\"); } public void registerNewUser(User user) { System.out.println(\"Registering a new user to the system\"); users.add(user); } public List<Order> getOrders() { return orders; } public void setOrders(List<Order> orders) { this.orders = orders; } public List<Vehicle> getVehicles() { return vehicles; } public void setVehicles(List<Vehicle> vehicles) { this.vehicles = vehicles; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; }}",
"e": 35952,
"s": 34395,
"text": null
},
{
"code": null,
"e": 36001,
"s": 35952,
"text": "This is the test class to test the application. "
},
{
"code": null,
"e": 36006,
"s": 36001,
"text": "Java"
},
{
"code": "package com.shashi.oodesign; import java.util.ArrayList;import java.util.Date;import java.util.List; public class Apptest { public static void main(String[] args) { User user = new User(); user.setUserId(1); user.setName(\"Shashi\"); user.setEmailId(\"[email protected]\"); Item item1 = new Item(); item1.setName(\"item1\"); item1.setPrice(20); Item item2 = new Item(); item2.setName(\"item2\"); item2.setPrice(40); List<Item> items = new ArrayList<Item>(); items.add(item1); items.add(item2); PaymentDetails paymentDetails = new PaymentDetails(); paymentDetails.setAmount(100); paymentDetails.setPaymentMode(PaymentMode.CREDIT_CARD); paymentDetails.setCardNumber(\"12345678\"); Location destination = new Location(); destination.setLatitude(73.23); destination.setLongitude(132.34); Order order = new Order(); order.setOrderId(1); order.setItems(items); order.setCurrentStatus(OrderStatus.PROCESSING); order.setDestination(destination); order.setPaymentDetails(paymentDetails); order.setTimeOfOrderDelivery(new Date()); LogisticsSystem logisticsSystem = new LogisticsSystem(); logisticsSystem.registerNewUser(user); logisticsSystem.takeAnOrder(order); logisticsSystem.processOrder(order); }}",
"e": 37423,
"s": 36006,
"text": null
},
{
"code": null,
"e": 37431,
"s": 37423,
"text": "clintra"
},
{
"code": null,
"e": 37437,
"s": 37431,
"text": "Adobe"
},
{
"code": null,
"e": 37460,
"s": 37437,
"text": "Object-Oriented-Design"
},
{
"code": null,
"e": 37484,
"s": 37460,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 37499,
"s": 37484,
"text": "Design Pattern"
},
{
"code": null,
"e": 37505,
"s": 37499,
"text": "Adobe"
},
{
"code": null,
"e": 37603,
"s": 37505,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37652,
"s": 37603,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 37690,
"s": 37652,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 37713,
"s": 37690,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 37732,
"s": 37713,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 37786,
"s": 37732,
"text": "Java Singleton Design Pattern Practices with Examples"
},
{
"code": null,
"e": 37836,
"s": 37786,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 37852,
"s": 37836,
"text": "Adapter Pattern"
},
{
"code": null,
"e": 37904,
"s": 37852,
"text": "Unified Modeling Language (UML) | Activity Diagrams"
},
{
"code": null,
"e": 37942,
"s": 37904,
"text": "Introduction of Programming Paradigms"
}
] |
JavaScript TypeError - Invalid assignment to const "X" - GeeksforGeeks | 31 Jul, 2020
This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared.
Message:
TypeError: invalid assignment to const "x" (Firefox)
TypeError: Assignment to constant variable. (Chrome)
TypeError: Assignment to const (Edge)
TypeError: Redeclaration of const 'x' (IE)
Error Type:
TypeError
Cause of Error: A const value in JavaScript is changed by the program which can not be altered during normal execution.
Example 1: In this example, the value of the variable(‘GFG’) is changed, So the error has occurred.
HTML
<script> const GFG = "This is GFG"; // Error here GFG = "This is GeeksForGeeks"; </script>
Output(in console):
TypeError: Assignment to const
Example 2: In this example, the value of the object(‘GFG_Obj’) is changed, So the error has occurred.
HTML
<script> const GFG_Obj = {key: 'val1'}; // Error here GFG_Obj = {key: 'val2'}; </script>
Output:
TypeError: Assignment to const
JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
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
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24984,
"s": 24956,
"text": "\n31 Jul, 2020"
},
{
"code": null,
"e": 25161,
"s": 24984,
"text": "This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared."
},
{
"code": null,
"e": 25170,
"s": 25161,
"text": "Message:"
},
{
"code": null,
"e": 25358,
"s": 25170,
"text": "TypeError: invalid assignment to const \"x\" (Firefox)\nTypeError: Assignment to constant variable. (Chrome)\nTypeError: Assignment to const (Edge)\nTypeError: Redeclaration of const 'x' (IE)\n"
},
{
"code": null,
"e": 25370,
"s": 25358,
"text": "Error Type:"
},
{
"code": null,
"e": 25381,
"s": 25370,
"text": "TypeError\n"
},
{
"code": null,
"e": 25502,
"s": 25381,
"text": "Cause of Error: A const value in JavaScript is changed by the program which can not be altered during normal execution. "
},
{
"code": null,
"e": 25602,
"s": 25502,
"text": "Example 1: In this example, the value of the variable(‘GFG’) is changed, So the error has occurred."
},
{
"code": null,
"e": 25607,
"s": 25602,
"text": "HTML"
},
{
"code": "<script> const GFG = \"This is GFG\"; // Error here GFG = \"This is GeeksForGeeks\"; </script>",
"e": 25707,
"s": 25607,
"text": null
},
{
"code": null,
"e": 25727,
"s": 25707,
"text": "Output(in console):"
},
{
"code": null,
"e": 25759,
"s": 25727,
"text": "TypeError: Assignment to const\n"
},
{
"code": null,
"e": 25861,
"s": 25759,
"text": "Example 2: In this example, the value of the object(‘GFG_Obj’) is changed, So the error has occurred."
},
{
"code": null,
"e": 25866,
"s": 25861,
"text": "HTML"
},
{
"code": "<script> const GFG_Obj = {key: 'val1'}; // Error here GFG_Obj = {key: 'val2'}; </script>",
"e": 25964,
"s": 25866,
"text": null
},
{
"code": null,
"e": 25972,
"s": 25964,
"text": "Output:"
},
{
"code": null,
"e": 26004,
"s": 25972,
"text": "TypeError: Assignment to const\n"
},
{
"code": null,
"e": 26022,
"s": 26004,
"text": "JavaScript-Errors"
},
{
"code": null,
"e": 26033,
"s": 26022,
"text": "JavaScript"
},
{
"code": null,
"e": 26050,
"s": 26033,
"text": "Web Technologies"
},
{
"code": null,
"e": 26148,
"s": 26050,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26193,
"s": 26148,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26254,
"s": 26193,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26326,
"s": 26254,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26372,
"s": 26326,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26413,
"s": 26372,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26455,
"s": 26413,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26488,
"s": 26455,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26531,
"s": 26488,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26593,
"s": 26531,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How to combine two arrays into an array of objects in JavaScript? | Let’s say the following are our two arrays −
var firstArray = ['John', 'David', 'Bob'];
var secondArray = ['Mike','Sam','Carol'];
To combine two arrays into an array of objects, use map() from JavaScript.
var firstArray = ['John', 'David', 'Bob'];
var secondArray = ['Mike','Sam','Carol'];
var arrayOfObject = firstArray.map(function (value, index){
return [value, secondArray[index]]
});
console.log("The First Array=");
console.log(firstArray);
console.log("The Second Array=");
console.log(secondArray);
console.log("The mix Of array object=");
console.log(arrayOfObject);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo190.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo190.js
The First Array=
[ 'John', 'David', 'Bob' ]
The Second Array=
[ 'Mike', 'Sam', 'Carol' ]
The mix Of array object=
[ [ 'John', 'Mike' ], [ 'David', 'Sam' ], [ 'Bob', 'Carol' ] ] | [
{
"code": null,
"e": 1107,
"s": 1062,
"text": "Let’s say the following are our two arrays −"
},
{
"code": null,
"e": 1192,
"s": 1107,
"text": "var firstArray = ['John', 'David', 'Bob'];\nvar secondArray = ['Mike','Sam','Carol'];"
},
{
"code": null,
"e": 1267,
"s": 1192,
"text": "To combine two arrays into an array of objects, use map() from JavaScript."
},
{
"code": null,
"e": 1641,
"s": 1267,
"text": "var firstArray = ['John', 'David', 'Bob'];\nvar secondArray = ['Mike','Sam','Carol'];\nvar arrayOfObject = firstArray.map(function (value, index){\n return [value, secondArray[index]]\n});\nconsole.log(\"The First Array=\");\nconsole.log(firstArray);\nconsole.log(\"The Second Array=\");\nconsole.log(secondArray);\nconsole.log(\"The mix Of array object=\");\nconsole.log(arrayOfObject);"
},
{
"code": null,
"e": 1707,
"s": 1641,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1725,
"s": 1707,
"text": "node fileName.js."
},
{
"code": null,
"e": 1759,
"s": 1725,
"text": "Here, my file name is demo190.js."
},
{
"code": null,
"e": 1800,
"s": 1759,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2027,
"s": 1800,
"text": "PS C:\\Users\\Amit\\javascript-code> node demo190.js\nThe First Array=\n[ 'John', 'David', 'Bob' ]\nThe Second Array=\n[ 'Mike', 'Sam', 'Carol' ]\nThe mix Of array object=\n[ [ 'John', 'Mike' ], [ 'David', 'Sam' ], [ 'Bob', 'Carol' ] ]"
}
] |
Junk File Organizer in Python? | This might seem very useful for a lazy python programmer who keeps most of the files and folders at one location and sometimes at confused what all files are there and surely he is too lazy to do it manually. So below is a python program to organize or simplify everything in appropriate folder in the single go and remove empty directories.
So we have a directory path where lots of files of different types are present (like below) and our program we segregate each file type into their respective folders (like below).
Input folder structure
Desired Output
First create different folders based on types of files we are going to segregate into different folders:
DIRECTORIES = {
"HTML": [".html5", ".html", ".htm", ".xhtml"],
"IMAGES": [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg",
".heif", ".psd"],
"VIDEOS": [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng",
".qt", ".mpg", ".mpeg", ".3gp"],
"DOCUMENTS": [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods",
".odt", ".pwi", ".xsn", ".xps", ".dotx", ".docm", ".dox",
".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx", ".ppt",
"pptx"],
"ARCHIVES": [".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", ".7z",
".dmg", ".rar", ".xar", ".zip"],
"AUDIO": [".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3",
".msv", "ogg", "oga", ".raw", ".vox", ".wav", ".wma"],
"PLAINTEXT": [".txt", ".in", ".out"],
"PDF": [".pdf"],
"PYTHON": [".py"],
"XML": [".xml"],
"EXE": [".exe"],
"SHELL": [".sh"]
}
Secondly, create the map of file type into their respective folders:
FILE_FORMATS = {file_format: directory
for directory, file_formats in DIRECTORIES.items()
for file_format in file_formats}
def organise_folder():
for entry in os.scandir():
if entry.is_dir():
continue
file_path = Path(entry)
file_format = file_path.suffix.lower()
if file_format in FILE_FORMATS:
directory_path = Path(FILE_FORMATS[file_format])
directory_path.mkdir(exist_ok=True)
file_path.rename(directory_path.joinpath(file_path))
try:
os.mkdir("OTHER-FILES")
except:
pass
for dir in os.scandir():
try:
if dir.is_dir():
os.rmdir(dir)
else:
os.rename(os.getcwd() + '/' + str(Path(dir)), os.getcwd() + '/OTHER-FILES/' + str(Path(dir)))
except:
pass
That’s it, below is our final script to filter file types into their respective folders.
#Python Lazy Junk Files Organizer
#Import important libraries
import os
from pathlib import Path
#
DIRECTORIES = {
"HTML": [".html5", ".html", ".htm", ".xhtml"],
"IMAGES": [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg",
".heif", ".psd"],
"VIDEOS": [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng",
".qt", ".mpg", ".mpeg", ".3gp"],
"DOCUMENTS": [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods",
".odt", ".pwi", ".xsn", ".xps", ".dotx", ".docm", ".dox",
".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx", ".ppt",
"pptx"],
"ARCHIVES": [".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", ".7z",
".dmg", ".rar", ".xar", ".zip"],
"AUDIO": [".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3",
".msv", "ogg", "oga", ".raw", ".vox", ".wav", ".wma"],
"PLAINTEXT": [".txt", ".in", ".out"],
"PDF": [".pdf"],
"PYTHON": [".py"],
"XML": [".xml"],
"EXE": [".exe"],
"SHELL": [".sh"]
}
FILE_FORMATS = {file_format: directory
for directory, file_formats in DIRECTORIES.items()
for file_format in file_formats}
def organise_folder():
for entry in os.scandir():
if entry.is_dir():
continue
file_path = Path(entry)
file_format = file_path.suffix.lower()
if file_format in FILE_FORMATS:
directory_path = Path(FILE_FORMATS[file_format])
directory_path.mkdir(exist_ok=True)
file_path.rename(directory_path.joinpath(file_path))
try:
os.mkdir("OTHER-FILES")
except:
pass
for dir in os.scandir():
try:
if dir.is_dir():
os.rmdir(dir)
else:
os.rename(os.getcwd() + '/' + str(Path(dir)), os.getcwd() + '/OTHER-FILES/' + str(Path(dir)))
except:
pass
if __name__ == "__main__":
organise_folder()
After running above script from a particular directory path, we’ll get output something like, | [
{
"code": null,
"e": 1404,
"s": 1062,
"text": "This might seem very useful for a lazy python programmer who keeps most of the files and folders at one location and sometimes at confused what all files are there and surely he is too lazy to do it manually. So below is a python program to organize or simplify everything in appropriate folder in the single go and remove empty directories."
},
{
"code": null,
"e": 1584,
"s": 1404,
"text": "So we have a directory path where lots of files of different types are present (like below) and our program we segregate each file type into their respective folders (like below)."
},
{
"code": null,
"e": 1607,
"s": 1584,
"text": "Input folder structure"
},
{
"code": null,
"e": 1622,
"s": 1607,
"text": "Desired Output"
},
{
"code": null,
"e": 1727,
"s": 1622,
"text": "First create different folders based on types of files we are going to segregate into different folders:"
},
{
"code": null,
"e": 2610,
"s": 1727,
"text": "DIRECTORIES = {\n \"HTML\": [\".html5\", \".html\", \".htm\", \".xhtml\"],\n \"IMAGES\": [\".jpeg\", \".jpg\", \".tiff\", \".gif\", \".bmp\", \".png\", \".bpg\", \"svg\",\n \".heif\", \".psd\"],\n \"VIDEOS\": [\".avi\", \".flv\", \".wmv\", \".mov\", \".mp4\", \".webm\", \".vob\", \".mng\",\n \".qt\", \".mpg\", \".mpeg\", \".3gp\"],\n \"DOCUMENTS\": [\".oxps\", \".epub\", \".pages\", \".docx\", \".doc\", \".fdf\", \".ods\",\n \".odt\", \".pwi\", \".xsn\", \".xps\", \".dotx\", \".docm\", \".dox\",\n \".rvg\", \".rtf\", \".rtfd\", \".wpd\", \".xls\", \".xlsx\", \".ppt\",\n \"pptx\"],\n \"ARCHIVES\": [\".a\", \".ar\", \".cpio\", \".iso\", \".tar\", \".gz\", \".rz\", \".7z\",\n \".dmg\", \".rar\", \".xar\", \".zip\"],\n \"AUDIO\": [\".aac\", \".aa\", \".aac\", \".dvf\", \".m4a\", \".m4b\", \".m4p\", \".mp3\",\n \".msv\", \"ogg\", \"oga\", \".raw\", \".vox\", \".wav\", \".wma\"],\n \"PLAINTEXT\": [\".txt\", \".in\", \".out\"],\n \"PDF\": [\".pdf\"],\n \"PYTHON\": [\".py\"],\n \"XML\": [\".xml\"],\n \"EXE\": [\".exe\"],\n \"SHELL\": [\".sh\"]\n}"
},
{
"code": null,
"e": 2679,
"s": 2610,
"text": "Secondly, create the map of file type into their respective folders:"
},
{
"code": null,
"e": 3475,
"s": 2679,
"text": "FILE_FORMATS = {file_format: directory\n for directory, file_formats in DIRECTORIES.items()\n for file_format in file_formats}\ndef organise_folder():\n for entry in os.scandir():\n if entry.is_dir():\n continue\n file_path = Path(entry)\n file_format = file_path.suffix.lower()\n if file_format in FILE_FORMATS:\n directory_path = Path(FILE_FORMATS[file_format])\n directory_path.mkdir(exist_ok=True)\n file_path.rename(directory_path.joinpath(file_path))\n\n try:\n os.mkdir(\"OTHER-FILES\")\n except:\n pass\n\n for dir in os.scandir():\n try:\n if dir.is_dir():\n os.rmdir(dir)\n else:\n os.rename(os.getcwd() + '/' + str(Path(dir)), os.getcwd() + '/OTHER-FILES/' + str(Path(dir)))\n except:\npass"
},
{
"code": null,
"e": 3564,
"s": 3475,
"text": "That’s it, below is our final script to filter file types into their respective folders."
},
{
"code": null,
"e": 5402,
"s": 3564,
"text": "#Python Lazy Junk Files Organizer\n\n#Import important libraries\nimport os\nfrom pathlib import Path\n\n#\nDIRECTORIES = {\n \"HTML\": [\".html5\", \".html\", \".htm\", \".xhtml\"],\n \"IMAGES\": [\".jpeg\", \".jpg\", \".tiff\", \".gif\", \".bmp\", \".png\", \".bpg\", \"svg\",\n \".heif\", \".psd\"],\n \"VIDEOS\": [\".avi\", \".flv\", \".wmv\", \".mov\", \".mp4\", \".webm\", \".vob\", \".mng\",\n \".qt\", \".mpg\", \".mpeg\", \".3gp\"],\n \"DOCUMENTS\": [\".oxps\", \".epub\", \".pages\", \".docx\", \".doc\", \".fdf\", \".ods\",\n \".odt\", \".pwi\", \".xsn\", \".xps\", \".dotx\", \".docm\", \".dox\",\n \".rvg\", \".rtf\", \".rtfd\", \".wpd\", \".xls\", \".xlsx\", \".ppt\",\n \"pptx\"],\n \"ARCHIVES\": [\".a\", \".ar\", \".cpio\", \".iso\", \".tar\", \".gz\", \".rz\", \".7z\",\n \".dmg\", \".rar\", \".xar\", \".zip\"],\n \"AUDIO\": [\".aac\", \".aa\", \".aac\", \".dvf\", \".m4a\", \".m4b\", \".m4p\", \".mp3\",\n \".msv\", \"ogg\", \"oga\", \".raw\", \".vox\", \".wav\", \".wma\"],\n \"PLAINTEXT\": [\".txt\", \".in\", \".out\"],\n \"PDF\": [\".pdf\"],\n \"PYTHON\": [\".py\"],\n \"XML\": [\".xml\"],\n \"EXE\": [\".exe\"],\n \"SHELL\": [\".sh\"]\n}\n\nFILE_FORMATS = {file_format: directory\n for directory, file_formats in DIRECTORIES.items()\n for file_format in file_formats}\n\ndef organise_folder():\n for entry in os.scandir():\n if entry.is_dir():\n continue\n file_path = Path(entry)\n file_format = file_path.suffix.lower()\n if file_format in FILE_FORMATS:\n directory_path = Path(FILE_FORMATS[file_format])\n directory_path.mkdir(exist_ok=True)\n file_path.rename(directory_path.joinpath(file_path))\n try:\n os.mkdir(\"OTHER-FILES\")\n except:\n pass\n\n for dir in os.scandir():\n try:\n if dir.is_dir():\n os.rmdir(dir)\n else:\n os.rename(os.getcwd() + '/' + str(Path(dir)), os.getcwd() + '/OTHER-FILES/' + str(Path(dir)))\n except:\n pass\nif __name__ == \"__main__\":\n organise_folder()"
},
{
"code": null,
"e": 5496,
"s": 5402,
"text": "After running above script from a particular directory path, we’ll get output something like,"
}
] |
Introduction to Backtracking | Backtracking is a technique based on algorithm to solve problem. It uses recursive calling to find the solution by building a solution step by step increasing values with time. It removes the solutions that doesn't give rise to the solution of the problem based on the constraints given to solve the problem.
Backtracking algorithm is applied to some specific types of problems,
Decision problem used to find a feasible solution of the problem.
Decision problem used to find a feasible solution of the problem.
Optimisation problem used to find the best solution that can be applied.
Optimisation problem used to find the best solution that can be applied.
Enumeration problem used to find the set of all feasible solutions of the problem.
Enumeration problem used to find the set of all feasible solutions of the problem.
In backtracking problem, the algorithm tries to find a sequence path to the solution which has some small checkpoints from where the problem can backtrack if no feasible solution is found for the problem.
Example,
Here,
Green is the start point, blue is the intermediate point, red are points with no feasible solution, dark green is end solution.
Here, when the algorithm propagates to an end to check if it is a solution or not, if it is then returns the solution otherwise backtracks to the point one step behind it to find track to the next point to find solution.
Step 1 − if current_position is goal, return success
Step 2 − else,
Step 3 − if current_position is an end point, return failed.
Step 4 − else, if current_position is not end point, explore and repeat above steps.
Let’s use this backtracking problem to find the solution to N-Queen Problem.
In N-Queen problem, we are given an NxN chessboard and we have to place n queens on the board in such a way that no two queens attack each other. A queen will attack another queen if it is placed in horizontal, vertical or diagonal points in its way. Here, we will do 4-Queen problem.
Here, the solution is −
Here, the binary output for n queen problem with 1’s as queens to the positions are placed.
{0 , 1 , 0 , 0}
{0 , 0 , 0 , 1}
{1 , 0 , 0 , 0}
{0 , 0 , 1 , 0}
For solving n queens problem, we will try placing queen into different positions of one row. And checks if it clashes with other queens. If current positioning of queens if there are any two queens attacking each other. If they are attacking, we will backtrack to previous location of the queen and change its positions. And check clash of queen again.
Step 1 − Start from 1st position in the array.Step 2 − Place queens in the board and check. Do,
Step 2.1 − After placing the queen, mark the position as a part of the solution and then recursively check if this will lead to a solution.
Step 2.2 − Now, if placing the queen doesn’t lead to a solution and trackback and go to step (a) and place queens to other rows.
Step 2.3 − If placing queen returns a lead to solution return TRUE.
Step 3 − If all queens are placed return TRUE.
Step 4 − If all rows are tried and no solution is found, return FALSE.
Step 1 − Start from 1st position in the array.
Step 4 − If all rows are tried and no solution is found, return FALSE.
Now, Lets use backtracking to solve the Rat in a Maze problem −
In rat in a maze problem, we are with an NxN maze the first position of the maze i.e [0][0] and will end at position [n-1][n-1] of the array. In this path there are some dead roads which do not lead to a solution.
Using backtracking in this problem we will go down step by step to reach the final goal position in the maze.
The below 2D array displays how the problem seems.
Here the dashed lines show the path traveled. | [
{
"code": null,
"e": 1371,
"s": 1062,
"text": "Backtracking is a technique based on algorithm to solve problem. It uses recursive calling to find the solution by building a solution step by step increasing values with time. It removes the solutions that doesn't give rise to the solution of the problem based on the constraints given to solve the problem."
},
{
"code": null,
"e": 1441,
"s": 1371,
"text": "Backtracking algorithm is applied to some specific types of problems,"
},
{
"code": null,
"e": 1507,
"s": 1441,
"text": "Decision problem used to find a feasible solution of the problem."
},
{
"code": null,
"e": 1573,
"s": 1507,
"text": "Decision problem used to find a feasible solution of the problem."
},
{
"code": null,
"e": 1646,
"s": 1573,
"text": "Optimisation problem used to find the best solution that can be applied."
},
{
"code": null,
"e": 1719,
"s": 1646,
"text": "Optimisation problem used to find the best solution that can be applied."
},
{
"code": null,
"e": 1802,
"s": 1719,
"text": "Enumeration problem used to find the set of all feasible solutions of the problem."
},
{
"code": null,
"e": 1885,
"s": 1802,
"text": "Enumeration problem used to find the set of all feasible solutions of the problem."
},
{
"code": null,
"e": 2090,
"s": 1885,
"text": "In backtracking problem, the algorithm tries to find a sequence path to the solution which has some small checkpoints from where the problem can backtrack if no feasible solution is found for the problem."
},
{
"code": null,
"e": 2099,
"s": 2090,
"text": "Example,"
},
{
"code": null,
"e": 2105,
"s": 2099,
"text": "Here,"
},
{
"code": null,
"e": 2233,
"s": 2105,
"text": "Green is the start point, blue is the intermediate point, red are points with no feasible solution, dark green is end solution."
},
{
"code": null,
"e": 2454,
"s": 2233,
"text": "Here, when the algorithm propagates to an end to check if it is a solution or not, if it is then returns the solution otherwise backtracks to the point one step behind it to find track to the next point to find solution."
},
{
"code": null,
"e": 2668,
"s": 2454,
"text": "Step 1 − if current_position is goal, return success\nStep 2 − else,\nStep 3 − if current_position is an end point, return failed.\nStep 4 − else, if current_position is not end point, explore and repeat above steps."
},
{
"code": null,
"e": 2745,
"s": 2668,
"text": "Let’s use this backtracking problem to find the solution to N-Queen Problem."
},
{
"code": null,
"e": 3030,
"s": 2745,
"text": "In N-Queen problem, we are given an NxN chessboard and we have to place n queens on the board in such a way that no two queens attack each other. A queen will attack another queen if it is placed in horizontal, vertical or diagonal points in its way. Here, we will do 4-Queen problem."
},
{
"code": null,
"e": 3054,
"s": 3030,
"text": "Here, the solution is −"
},
{
"code": null,
"e": 3146,
"s": 3054,
"text": "Here, the binary output for n queen problem with 1’s as queens to the positions are placed."
},
{
"code": null,
"e": 3210,
"s": 3146,
"text": "{0 , 1 , 0 , 0}\n{0 , 0 , 0 , 1}\n{1 , 0 , 0 , 0}\n{0 , 0 , 1 , 0}"
},
{
"code": null,
"e": 3563,
"s": 3210,
"text": "For solving n queens problem, we will try placing queen into different positions of one row. And checks if it clashes with other queens. If current positioning of queens if there are any two queens attacking each other. If they are attacking, we will backtrack to previous location of the queen and change its positions. And check clash of queen again."
},
{
"code": null,
"e": 4123,
"s": 3563,
"text": "Step 1 − Start from 1st position in the array.Step 2 − Place queens in the board and check. Do,\n Step 2.1 − After placing the queen, mark the position as a part of the solution and then recursively check if this will lead to a solution.\n Step 2.2 − Now, if placing the queen doesn’t lead to a solution and trackback and go to step (a) and place queens to other rows.\n Step 2.3 − If placing queen returns a lead to solution return TRUE.\nStep 3 − If all queens are placed return TRUE.\nStep 4 − If all rows are tried and no solution is found, return FALSE."
},
{
"code": null,
"e": 4170,
"s": 4123,
"text": "Step 1 − Start from 1st position in the array."
},
{
"code": null,
"e": 4241,
"s": 4170,
"text": "Step 4 − If all rows are tried and no solution is found, return FALSE."
},
{
"code": null,
"e": 4305,
"s": 4241,
"text": "Now, Lets use backtracking to solve the Rat in a Maze problem −"
},
{
"code": null,
"e": 4519,
"s": 4305,
"text": "In rat in a maze problem, we are with an NxN maze the first position of the maze i.e [0][0] and will end at position [n-1][n-1] of the array. In this path there are some dead roads which do not lead to a solution."
},
{
"code": null,
"e": 4629,
"s": 4519,
"text": "Using backtracking in this problem we will go down step by step to reach the final goal position in the maze."
},
{
"code": null,
"e": 4680,
"s": 4629,
"text": "The below 2D array displays how the problem seems."
},
{
"code": null,
"e": 4726,
"s": 4680,
"text": "Here the dashed lines show the path traveled."
}
] |
C | Dynamic Memory Allocation | Question 2 - GeeksforGeeks | 28 Jun, 2021
Consider the following three C functions :
[PI] int * g (void) { int x= 10; return (&x); } [P2] int * g (void) { int * px; *px= 10; return px; } [P3] int *g (void) { int *px; px = (int *) malloc (sizeof(int)); *px= 10; return px; }
Which of the above three functions are likely to cause problems with pointers? (GATE 2001)(A) Only P3(B) Only P1 and P3(C) Only P1 and P2
(D) P1, P2 and P3Answer: (C)Explanation: In P1, pointer variable x is a local variable to g(), and g() returns pointer to this variable. x may vanish after g() has returned as x exists on stack. So, &x may become invalid.In P2, pointer variable px is being assigned a value without allocating memory to it.P3 works perfectly fine. Memory is allocated to pointer variable px using malloc(). So, px exists on heap, it’s existence will remain in memory even after return of g() as it is on heap.Quiz of this Question
C-Dynamic Memory Allocation
Dynamic Memory Allocation
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Command line arguments in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
Output of C programs | Set 64 (Pointers)
C | Structure & Union | Question 10
C | File Handling | Question 1 | [
{
"code": null,
"e": 24564,
"s": 24536,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24607,
"s": 24564,
"text": "Consider the following three C functions :"
},
{
"code": "[PI] int * g (void) { int x= 10; return (&x); } [P2] int * g (void) { int * px; *px= 10; return px; } [P3] int *g (void) { int *px; px = (int *) malloc (sizeof(int)); *px= 10; return px; }",
"e": 24823,
"s": 24607,
"text": null
},
{
"code": null,
"e": 24961,
"s": 24823,
"text": "Which of the above three functions are likely to cause problems with pointers? (GATE 2001)(A) Only P3(B) Only P1 and P3(C) Only P1 and P2"
},
{
"code": null,
"e": 25475,
"s": 24961,
"text": "(D) P1, P2 and P3Answer: (C)Explanation: In P1, pointer variable x is a local variable to g(), and g() returns pointer to this variable. x may vanish after g() has returned as x exists on stack. So, &x may become invalid.In P2, pointer variable px is being assigned a value without allocating memory to it.P3 works perfectly fine. Memory is allocated to pointer variable px using malloc(). So, px exists on heap, it’s existence will remain in memory even after return of g() as it is on heap.Quiz of this Question"
},
{
"code": null,
"e": 25503,
"s": 25475,
"text": "C-Dynamic Memory Allocation"
},
{
"code": null,
"e": 25529,
"s": 25503,
"text": "Dynamic Memory Allocation"
},
{
"code": null,
"e": 25540,
"s": 25529,
"text": "C Language"
},
{
"code": null,
"e": 25547,
"s": 25540,
"text": "C Quiz"
},
{
"code": null,
"e": 25645,
"s": 25547,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25673,
"s": 25645,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25719,
"s": 25673,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 25759,
"s": 25719,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 25771,
"s": 25759,
"text": "fork() in C"
},
{
"code": null,
"e": 25803,
"s": 25771,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25845,
"s": 25803,
"text": "Compiling a C program:- Behind the Scenes"
},
{
"code": null,
"e": 25888,
"s": 25845,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 25929,
"s": 25888,
"text": "Output of C programs | Set 64 (Pointers)"
},
{
"code": null,
"e": 25965,
"s": 25929,
"text": "C | Structure & Union | Question 10"
}
] |
How to check whether column value is NULL or having DEFAULT value in MySQL? | You can use the concept of IFNULL() for this. Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(100) DEFAULT 'Larry',
Age int DEFAULT NULL
);
Query OK, 0 rows affected (0.73 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(Name,Age) values('John',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Age) values(24);
Query OK, 1 row affected (0.13 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 −
+----+-------+------+
| Id | Name | Age |
+----+-------+------+
| 1 | John | 23 |
| 2 | Larry | NULL |
| 3 | David | NULL |
| 4 | Larry | 24 |
+----+-------+------+
4 rows in set (0.00 sec)
Following is the query to check whether column value is NULL or having DEFAULT value in MySQL.
mysql> select *from DemoTable WHERE IFNULL(Name, DEFAULT(Name)) <> DEFAULT(Name);
This will produce the following output −
+----+-------+------+
| Id | Name | Age |
+----+-------+------+
| 1 | John | 23 |
| 3 | David | NULL |
+----+-------+------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "You can use the concept of IFNULL() for this. Let us first create a table −"
},
{
"code": null,
"e": 1319,
"s": 1138,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Name varchar(100) DEFAULT 'Larry',\n Age int DEFAULT NULL\n);\nQuery OK, 0 rows affected (0.73 sec)"
},
{
"code": null,
"e": 1370,
"s": 1319,
"text": "Insert records in the table using insert command −"
},
{
"code": null,
"e": 1709,
"s": 1370,
"text": "mysql> insert into DemoTable(Name,Age) values('John',23);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values();\nQuery OK, 1 row affected (0.34 sec)\nmysql> insert into DemoTable(Name) values('David');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable(Age) values(24);\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1795,
"s": 1709,
"text": "Following is the query to display all records from the table using select statement −"
},
{
"code": null,
"e": 1826,
"s": 1795,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1867,
"s": 1826,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2068,
"s": 1867,
"text": "+----+-------+------+\n| Id | Name | Age |\n+----+-------+------+\n| 1 | John | 23 |\n| 2 | Larry | NULL |\n| 3 | David | NULL |\n| 4 | Larry | 24 |\n+----+-------+------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2163,
"s": 2068,
"text": "Following is the query to check whether column value is NULL or having DEFAULT value in MySQL."
},
{
"code": null,
"e": 2245,
"s": 2163,
"text": "mysql> select *from DemoTable WHERE IFNULL(Name, DEFAULT(Name)) <> DEFAULT(Name);"
},
{
"code": null,
"e": 2286,
"s": 2245,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2443,
"s": 2286,
"text": "+----+-------+------+\n| Id | Name | Age |\n+----+-------+------+\n| 1 | John | 23 |\n| 3 | David | NULL |\n+----+-------+------+\n2 rows in set (0.00 sec)"
}
] |
Is Flux Better Than Tensorflow?. Relax! Flux is a machine-learning... | by Emmett Boudreau | Towards Data Science | Fl ux is a machine-learning library for the multi-paradigm, fast, MIT-developed statistical programming language, Julia. Flux’s core feature is taking gradients of Julia code. In other words, Flux is able to take another Julia function and a set of arguments and return a gradient. Flux is a really cool package because it is able to do a lot of things that Google’s Tensorflow is able to do, but in a “ Developed by users” package. Additionally, Flux has the advantages of being written in Julia. While this also means that Flux suffers from the same disadvantages that other Julia packages do, the trade-of certainly isn’t terrible.
If you’d like to actually take a look at Flux, I have an introductory tutorial on batching and training a convolutional nueral network in Flux here.
Tensorflow is a classic tool in the data-science toolbox. People who don’t program at all even know what Tensorflow is, and this is for good reason:
Tensorflow is awesome.
Tensorflow was developed under the “ Google Brain Team,” and released under the Apache license in November of 2015. Tensorflow powers the gradient models behind a lot of modern machine-learning algorithms, including those used by Google, Nvidia, QualComm, Lenovo, and hundreds more. Tensorflow has become a staple in not only Python, but machine-learning as a whole.
Flux is a great machine-learning framework because it brings with it a lot of interesting ideas and some really cool and easy syntax. There is a lot of individualism in Flux, but generally, the benefits boil down to some key factors.
As you might already know, Flux is for Julia. Being written in Julia gives Flux a massive advantage over packages written in Python. Julia is a far faster language, and in my opinion, has better syntax than Python (which is my personal preference.)
This does, however, come with a significant trade-off. Julia, for the most part, is still a relatively new language and does not have anywhere near the user-base that Python has. In this situation, Julia loses a lot of the support that an enormous language like Python carries with it. This means that while Flux might be a better solution to some extent, it might not necessarily be in every case. This is because it can be really hard to find answers to any sort of hiccups you run in to. It can be difficult to find documentation in the first place to learn how to use the language and the packages, though this is steadily improving.
I stated before that I like Julia’s syntax far more than I do Python’s. While this is purely subjective, what is not subjective is just how mutable the Julia language can be, and with that comes an entirely different and really cool way to create gradient models inside of Julia:
Syntactical Expressions
These are really cool, and if you want to look into Julia, you should definitely take a good look at them. They are primarily used in two particular scenarios:
Looping
f(w) = v = v + 5 for v in w
Functional Operations
f(w) = w + 5 - 6
However, Syntactical Expressions in Julia can be used hundreds of other ways that are all interesting and make programmer both easier and more intuitive.
But how does this fit into Flux?
Flux absolutely takes advantages of these versatile expressions and uses them as the base for the entire library. Just take a look at this example from the Flux Documentation:
julia> using Fluxjulia> f(x) = 3x^2 + 2x + 1; julia> df(x) = gradient(f, x)[1]; # df/dx = 6x + 2 julia>df(2) 14 julia> d2f(x) = gradient(df, x)[1]; # d2f/dx2 = 6 julia> d2f(2) 6
Tensorflow has its own language advantage in an entirely different way, Python is both a very universal language in that most other high-level languages are able to interface it, and also that it is based in C. The shot to the Achilles heel for Flux and Julia, however, is definitely Tensorflow and Python’s popularity.
A benefit to using anything popular; just as demand grows with supply, usability grows with users. The more people using a product creates more conversations about the product, and this is absolutely instrumental for a tool like Tensorflow or Flux to be documented.
A big issue I can presume Data Scientists will have when trying to use Flux is that a lot of things are done in a very different way than how they are done anywhere else. Flux uses a very language-specific syntax that doesn’t conform to how high-level ML code is typically typed. On the other side of the hedge, however, is Tensorflow, who takes the exact opposite approach and tends to conform to what is established inside of the machine-learning already.
Without a doubt, Tensorflow has the notoriety. This makes sense because Tensorflow has not only been in the industry longer but is also backed by the data monster Google. At the end of the day, it is far easier for a business with millions of developers that use a tool to maintain the software and improve it than a few Github maintainers who could even have day-jobs they have to go to.
I think Flux is really cool, and I enjoy working in it a lot. Tensorflow has a special place in my heart, but it would definitely be interesting to see more people using Flux for their models. Flux has some really cool ideas that it brings to the table, and while that makes it great for being unique, it also comes with a terribly unfamiliar usage. Will Flux replace Tensorflow? Most likely it wouldn’t, and couldn’t, but could Flux replace Tensorflow for you?
Yes!
Julia is certainly still a baby, and lots of packages are teetering on the edge of being inclusive enough to be depended on, but regardless of its young age Julia definitely stands out as a great language for now and the future in Data Science. Who knows? In ten to fifteen years we could very likely see a surge of Julia usage, and with it, Flux usage. | [
{
"code": null,
"e": 682,
"s": 47,
"text": "Fl ux is a machine-learning library for the multi-paradigm, fast, MIT-developed statistical programming language, Julia. Flux’s core feature is taking gradients of Julia code. In other words, Flux is able to take another Julia function and a set of arguments and return a gradient. Flux is a really cool package because it is able to do a lot of things that Google’s Tensorflow is able to do, but in a “ Developed by users” package. Additionally, Flux has the advantages of being written in Julia. While this also means that Flux suffers from the same disadvantages that other Julia packages do, the trade-of certainly isn’t terrible."
},
{
"code": null,
"e": 831,
"s": 682,
"text": "If you’d like to actually take a look at Flux, I have an introductory tutorial on batching and training a convolutional nueral network in Flux here."
},
{
"code": null,
"e": 980,
"s": 831,
"text": "Tensorflow is a classic tool in the data-science toolbox. People who don’t program at all even know what Tensorflow is, and this is for good reason:"
},
{
"code": null,
"e": 1003,
"s": 980,
"text": "Tensorflow is awesome."
},
{
"code": null,
"e": 1370,
"s": 1003,
"text": "Tensorflow was developed under the “ Google Brain Team,” and released under the Apache license in November of 2015. Tensorflow powers the gradient models behind a lot of modern machine-learning algorithms, including those used by Google, Nvidia, QualComm, Lenovo, and hundreds more. Tensorflow has become a staple in not only Python, but machine-learning as a whole."
},
{
"code": null,
"e": 1604,
"s": 1370,
"text": "Flux is a great machine-learning framework because it brings with it a lot of interesting ideas and some really cool and easy syntax. There is a lot of individualism in Flux, but generally, the benefits boil down to some key factors."
},
{
"code": null,
"e": 1853,
"s": 1604,
"text": "As you might already know, Flux is for Julia. Being written in Julia gives Flux a massive advantage over packages written in Python. Julia is a far faster language, and in my opinion, has better syntax than Python (which is my personal preference.)"
},
{
"code": null,
"e": 2491,
"s": 1853,
"text": "This does, however, come with a significant trade-off. Julia, for the most part, is still a relatively new language and does not have anywhere near the user-base that Python has. In this situation, Julia loses a lot of the support that an enormous language like Python carries with it. This means that while Flux might be a better solution to some extent, it might not necessarily be in every case. This is because it can be really hard to find answers to any sort of hiccups you run in to. It can be difficult to find documentation in the first place to learn how to use the language and the packages, though this is steadily improving."
},
{
"code": null,
"e": 2771,
"s": 2491,
"text": "I stated before that I like Julia’s syntax far more than I do Python’s. While this is purely subjective, what is not subjective is just how mutable the Julia language can be, and with that comes an entirely different and really cool way to create gradient models inside of Julia:"
},
{
"code": null,
"e": 2795,
"s": 2771,
"text": "Syntactical Expressions"
},
{
"code": null,
"e": 2955,
"s": 2795,
"text": "These are really cool, and if you want to look into Julia, you should definitely take a good look at them. They are primarily used in two particular scenarios:"
},
{
"code": null,
"e": 2963,
"s": 2955,
"text": "Looping"
},
{
"code": null,
"e": 2991,
"s": 2963,
"text": "f(w) = v = v + 5 for v in w"
},
{
"code": null,
"e": 3013,
"s": 2991,
"text": "Functional Operations"
},
{
"code": null,
"e": 3030,
"s": 3013,
"text": "f(w) = w + 5 - 6"
},
{
"code": null,
"e": 3184,
"s": 3030,
"text": "However, Syntactical Expressions in Julia can be used hundreds of other ways that are all interesting and make programmer both easier and more intuitive."
},
{
"code": null,
"e": 3217,
"s": 3184,
"text": "But how does this fit into Flux?"
},
{
"code": null,
"e": 3393,
"s": 3217,
"text": "Flux absolutely takes advantages of these versatile expressions and uses them as the base for the entire library. Just take a look at this example from the Flux Documentation:"
},
{
"code": null,
"e": 3575,
"s": 3393,
"text": "julia> using Fluxjulia> f(x) = 3x^2 + 2x + 1; julia> df(x) = gradient(f, x)[1]; # df/dx = 6x + 2 julia>df(2) 14 julia> d2f(x) = gradient(df, x)[1]; # d2f/dx2 = 6 julia> d2f(2) 6"
},
{
"code": null,
"e": 3895,
"s": 3575,
"text": "Tensorflow has its own language advantage in an entirely different way, Python is both a very universal language in that most other high-level languages are able to interface it, and also that it is based in C. The shot to the Achilles heel for Flux and Julia, however, is definitely Tensorflow and Python’s popularity."
},
{
"code": null,
"e": 4161,
"s": 3895,
"text": "A benefit to using anything popular; just as demand grows with supply, usability grows with users. The more people using a product creates more conversations about the product, and this is absolutely instrumental for a tool like Tensorflow or Flux to be documented."
},
{
"code": null,
"e": 4619,
"s": 4161,
"text": "A big issue I can presume Data Scientists will have when trying to use Flux is that a lot of things are done in a very different way than how they are done anywhere else. Flux uses a very language-specific syntax that doesn’t conform to how high-level ML code is typically typed. On the other side of the hedge, however, is Tensorflow, who takes the exact opposite approach and tends to conform to what is established inside of the machine-learning already."
},
{
"code": null,
"e": 5008,
"s": 4619,
"text": "Without a doubt, Tensorflow has the notoriety. This makes sense because Tensorflow has not only been in the industry longer but is also backed by the data monster Google. At the end of the day, it is far easier for a business with millions of developers that use a tool to maintain the software and improve it than a few Github maintainers who could even have day-jobs they have to go to."
},
{
"code": null,
"e": 5470,
"s": 5008,
"text": "I think Flux is really cool, and I enjoy working in it a lot. Tensorflow has a special place in my heart, but it would definitely be interesting to see more people using Flux for their models. Flux has some really cool ideas that it brings to the table, and while that makes it great for being unique, it also comes with a terribly unfamiliar usage. Will Flux replace Tensorflow? Most likely it wouldn’t, and couldn’t, but could Flux replace Tensorflow for you?"
},
{
"code": null,
"e": 5475,
"s": 5470,
"text": "Yes!"
}
] |
How to create text node in JavaFX? | In JavaFX, the text node is represented by the javafx.scene.text.Text class. You can add text to a JavaFX window by instantiating this class.
Following are the basic properties of the text node −
X − This property represents x coordinate of the text. You can set value to this property using the setX() method.
X − This property represents x coordinate of the text. You can set value to this property using the setX() method.
Y − This property represents y coordinate of the text. You can set value to this property using the setY() method.
Y − This property represents y coordinate of the text. You can set value to this property using the setY() method.
text − This property represents the text that is to be displayed on the JavaFX window. You can set value to this property using the setText() method.
text − This property represents the text that is to be displayed on the JavaFX window. You can set value to this property using the setText() method.
To insert/display text in JavaFx window you need to −
Instantiate the Text class.
Instantiate the Text class.
Set the basic properties like position and text string, using the setter methods or, by passing them as arguments to the constructor.
Set the basic properties like position and text string, using the setter methods or, by passing them as arguments to the constructor.
Add the created node to the Group object.
Add the created node to the Group object.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Text;
public class CreatingText extends Application {
public void start(Stage stage) throws FileNotFoundException {
//Reading the contents of a text file.
InputStream inputStream = new FileInputStream("D:\\sample.txt");
Scanner sc = new Scanner(inputStream);
StringBuffer sb = new StringBuffer();
while(sc.hasNext()) {
sb.append(" "+sc.nextLine()+"\n");
}
String str = sb.toString();
//Creating a text object
Text text = new Text();
//Setting the properties of text
text.setText(str);
text.setWrappingWidth(580);
text.setX(10.0);
text.setY(25.0);
//Setting the stage
Group root = new Group(text);
Scene scene = new Scene(root, 595, 300, Color.BEIGE);
stage.setTitle("Displaying Text");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Assume following are the contents of the sample.txt file −
JavaFX is a Java library used to build Rich Internet Applications. The applications written using
this library can run consistently across multiple platforms. The applications developed using
JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc..
To develop GUI Applications using Java programming language, the programmers rely on libraries
such as Advanced Windowing Tool kit and Swing. After the advent of JavaFX, these Java programmers
can now develop GUI applications effectively with rich content. | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "In JavaFX, the text node is represented by the javafx.scene.text.Text class. You can add text to a JavaFX window by instantiating this class."
},
{
"code": null,
"e": 1258,
"s": 1204,
"text": "Following are the basic properties of the text node −"
},
{
"code": null,
"e": 1373,
"s": 1258,
"text": "X − This property represents x coordinate of the text. You can set value to this property using the setX() method."
},
{
"code": null,
"e": 1488,
"s": 1373,
"text": "X − This property represents x coordinate of the text. You can set value to this property using the setX() method."
},
{
"code": null,
"e": 1603,
"s": 1488,
"text": "Y − This property represents y coordinate of the text. You can set value to this property using the setY() method."
},
{
"code": null,
"e": 1718,
"s": 1603,
"text": "Y − This property represents y coordinate of the text. You can set value to this property using the setY() method."
},
{
"code": null,
"e": 1868,
"s": 1718,
"text": "text − This property represents the text that is to be displayed on the JavaFX window. You can set value to this property using the setText() method."
},
{
"code": null,
"e": 2018,
"s": 1868,
"text": "text − This property represents the text that is to be displayed on the JavaFX window. You can set value to this property using the setText() method."
},
{
"code": null,
"e": 2072,
"s": 2018,
"text": "To insert/display text in JavaFx window you need to −"
},
{
"code": null,
"e": 2100,
"s": 2072,
"text": "Instantiate the Text class."
},
{
"code": null,
"e": 2128,
"s": 2100,
"text": "Instantiate the Text class."
},
{
"code": null,
"e": 2262,
"s": 2128,
"text": "Set the basic properties like position and text string, using the setter methods or, by passing them as arguments to the constructor."
},
{
"code": null,
"e": 2396,
"s": 2262,
"text": "Set the basic properties like position and text string, using the setter methods or, by passing them as arguments to the constructor."
},
{
"code": null,
"e": 2438,
"s": 2396,
"text": "Add the created node to the Group object."
},
{
"code": null,
"e": 2480,
"s": 2438,
"text": "Add the created node to the Group object."
},
{
"code": null,
"e": 3712,
"s": 2480,
"text": "import java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\nimport java.util.Scanner;\nimport javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\nimport javafx.scene.text.Text;\npublic class CreatingText extends Application {\n public void start(Stage stage) throws FileNotFoundException {\n //Reading the contents of a text file.\n InputStream inputStream = new FileInputStream(\"D:\\\\sample.txt\");\n Scanner sc = new Scanner(inputStream);\n StringBuffer sb = new StringBuffer();\n while(sc.hasNext()) {\n sb.append(\" \"+sc.nextLine()+\"\\n\");\n }\n String str = sb.toString();\n //Creating a text object\n Text text = new Text();\n //Setting the properties of text\n text.setText(str);\n text.setWrappingWidth(580);\n text.setX(10.0);\n text.setY(25.0);\n //Setting the stage\n Group root = new Group(text);\n Scene scene = new Scene(root, 595, 300, Color.BEIGE);\n stage.setTitle(\"Displaying Text\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
},
{
"code": null,
"e": 3771,
"s": 3712,
"text": "Assume following are the contents of the sample.txt file −"
},
{
"code": null,
"e": 4319,
"s": 3771,
"text": "JavaFX is a Java library used to build Rich Internet Applications. The applications written using\nthis library can run consistently across multiple platforms. The applications developed using \nJavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc..\nTo develop GUI Applications using Java programming language, the programmers rely on libraries \nsuch as Advanced Windowing Tool kit and Swing. After the advent of JavaFX, these Java programmers \ncan now develop GUI applications effectively with rich content."
}
] |
PHP | image_type_to_extension() Function - GeeksforGeeks | 15 Nov, 2019
The image_type_to_extension() function is an inbuilt function in PHP which is used to get the file extension for an image type. This function can be found in any PHP version silimar or greater than 5.2.0.
Syntax:
string image_type_to_extension( int $imagetype, bool $include_dot )
Parameters: This function accepts two parameters as mentioned above and described below:
$imagetype: It takes an integer value as first parameter that is one of the IMAGETYPE_XXX constant. For example: IMAGETYPE_GIF, IMAGETYPE_JPEG etc.
$include_dot: The second parameter takes a boolean value to decide whether to prepend a dot to the extension or not. The default value is set to TRUE in the function.
Return Value: This function returns a string value associated with the extension corresponding to the given image type.
Below programs illustrate the image_type_to_extension() function in PHP:
Program 1:
<?php // Extension with dotecho image_type_to_extension(IMAGETYPE_PNG, TRUE) . "\n"; // Extension without dotecho image_type_to_extension(IMAGETYPE_PNG, FALSE); ?>
Output:
.png
png
Program 2:
<?php // Create image instance$image = imagecreatetruecolor(100, 100); // Creates an image with .png extensionimagepng($image, './test' . image_type_to_extension(IMAGETYPE_PNG)); // Free any memory associated with imageimagedestroy($image); ?>
Output:
Creates an image with name test.png
Reference: https://www.php.net/manual/en/function.image-type-to-extension.php
Image-Processing
PHP-function
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to generate PDF file using PHP ?
How to create admin login page using PHP?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 24972,
"s": 24944,
"text": "\n15 Nov, 2019"
},
{
"code": null,
"e": 25177,
"s": 24972,
"text": "The image_type_to_extension() function is an inbuilt function in PHP which is used to get the file extension for an image type. This function can be found in any PHP version silimar or greater than 5.2.0."
},
{
"code": null,
"e": 25185,
"s": 25177,
"text": "Syntax:"
},
{
"code": null,
"e": 25253,
"s": 25185,
"text": "string image_type_to_extension( int $imagetype, bool $include_dot )"
},
{
"code": null,
"e": 25342,
"s": 25253,
"text": "Parameters: This function accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25490,
"s": 25342,
"text": "$imagetype: It takes an integer value as first parameter that is one of the IMAGETYPE_XXX constant. For example: IMAGETYPE_GIF, IMAGETYPE_JPEG etc."
},
{
"code": null,
"e": 25657,
"s": 25490,
"text": "$include_dot: The second parameter takes a boolean value to decide whether to prepend a dot to the extension or not. The default value is set to TRUE in the function."
},
{
"code": null,
"e": 25777,
"s": 25657,
"text": "Return Value: This function returns a string value associated with the extension corresponding to the given image type."
},
{
"code": null,
"e": 25850,
"s": 25777,
"text": "Below programs illustrate the image_type_to_extension() function in PHP:"
},
{
"code": null,
"e": 25861,
"s": 25850,
"text": "Program 1:"
},
{
"code": "<?php // Extension with dotecho image_type_to_extension(IMAGETYPE_PNG, TRUE) . \"\\n\"; // Extension without dotecho image_type_to_extension(IMAGETYPE_PNG, FALSE); ?>",
"e": 26029,
"s": 25861,
"text": null
},
{
"code": null,
"e": 26037,
"s": 26029,
"text": "Output:"
},
{
"code": null,
"e": 26047,
"s": 26037,
"text": ".png\npng\n"
},
{
"code": null,
"e": 26058,
"s": 26047,
"text": "Program 2:"
},
{
"code": "<?php // Create image instance$image = imagecreatetruecolor(100, 100); // Creates an image with .png extensionimagepng($image, './test' . image_type_to_extension(IMAGETYPE_PNG)); // Free any memory associated with imageimagedestroy($image); ?>",
"e": 26315,
"s": 26058,
"text": null
},
{
"code": null,
"e": 26323,
"s": 26315,
"text": "Output:"
},
{
"code": null,
"e": 26359,
"s": 26323,
"text": "Creates an image with name test.png"
},
{
"code": null,
"e": 26437,
"s": 26359,
"text": "Reference: https://www.php.net/manual/en/function.image-type-to-extension.php"
},
{
"code": null,
"e": 26454,
"s": 26437,
"text": "Image-Processing"
},
{
"code": null,
"e": 26467,
"s": 26454,
"text": "PHP-function"
},
{
"code": null,
"e": 26474,
"s": 26467,
"text": "Picked"
},
{
"code": null,
"e": 26478,
"s": 26474,
"text": "PHP"
},
{
"code": null,
"e": 26495,
"s": 26478,
"text": "Web Technologies"
},
{
"code": null,
"e": 26499,
"s": 26495,
"text": "PHP"
},
{
"code": null,
"e": 26597,
"s": 26499,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26679,
"s": 26597,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 26730,
"s": 26679,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 26804,
"s": 26730,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 26841,
"s": 26804,
"text": "How to generate PDF file using PHP ?"
},
{
"code": null,
"e": 26883,
"s": 26841,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 26925,
"s": 26883,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26958,
"s": 26925,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27001,
"s": 26958,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27051,
"s": 27001,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Java program to print unique values from a list | To print unique values from a List in Java, the code is as follows −
Live Demo
import java.io.*;
public class Demo{
static void distinct_vals(int my_arr[], int len){
for (int i = 0; i < len; i++){
int j;
for (j = 0; j < i; j++)
if (my_arr[i] == my_arr[j])
break;
if (i == j)
System.out.print( my_arr[i] + " ");
}
}
public static void main (String[] args){
int my_arr[] = {55, 67, 99, 11, 54, 55, 88, 99, 1, 13, 45};
int arr_len = my_arr.length;
System.out.println("The distinct elements in the array are ");
distinct_vals(my_arr, arr_len);
}
}
The distinct elements in the array are
55 67 99 11 54 88 1 13 45
A class named Demo contains a function named ‘distinct_vals’ that takes in the array and the length of the array as parameters. It iterates over the array and checks for duplicate values and prints only the unique values of the array. In the main function, an array is defined and its length is stored in a variable. This ‘distinct_vals’ function is called with the defined array and length and the result is displayed on the console. | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "To print unique values from a List in Java, the code is as follows −"
},
{
"code": null,
"e": 1142,
"s": 1131,
"text": " Live Demo"
},
{
"code": null,
"e": 1712,
"s": 1142,
"text": "import java.io.*;\npublic class Demo{\n static void distinct_vals(int my_arr[], int len){\n for (int i = 0; i < len; i++){\n int j;\n for (j = 0; j < i; j++)\n if (my_arr[i] == my_arr[j])\n break;\n if (i == j)\n System.out.print( my_arr[i] + \" \");\n }\n }\n public static void main (String[] args){\n int my_arr[] = {55, 67, 99, 11, 54, 55, 88, 99, 1, 13, 45};\n int arr_len = my_arr.length;\n System.out.println(\"The distinct elements in the array are \");\n distinct_vals(my_arr, arr_len);\n }\n}"
},
{
"code": null,
"e": 1777,
"s": 1712,
"text": "The distinct elements in the array are\n55 67 99 11 54 88 1 13 45"
},
{
"code": null,
"e": 2212,
"s": 1777,
"text": "A class named Demo contains a function named ‘distinct_vals’ that takes in the array and the length of the array as parameters. It iterates over the array and checks for duplicate values and prints only the unique values of the array. In the main function, an array is defined and its length is stored in a variable. This ‘distinct_vals’ function is called with the defined array and length and the result is displayed on the console."
}
] |
Why do we use pandas in python? | Pandas has been one of the most commonly used tools for Data Science and Machine learning, which is used for data cleaning and analysis.
Here, Pandas is the best tool for handling this real-world messy data. And pandas is one of the open-source python packages built on top of NumPy.
Handling data using pandas is very fast and effective by using pandas Series and data frame, these two pandas data structures will help you to manipulate data in various ways.
Based on the features available in pandas we can say pandas is best for handling data. It can handle missing data, cleaning up the data and it supports multiple file formats. This means it can read or load data in many formats like CSV, Excel, SQL, etc.,
Let’s take an example and see how it’s gonna read CSV data.
data = pd.read_csv('world-happiness-report.csv')
print(data.shape)
data.head()
In the above code, variable data stores CSV data which is a world happiness report (downloaded from Kaggle datasets) by using the read_csv function available in the pandas package. data.shape is used to give you the columns and row count.
Country name year Life Ladder Log GDP per capita Social support \
0 Afghanistan 2008 3.724 7.370 0.451
1 Afghanistan 2009 4.402 7.540 0.552
2 Afghanistan 2010 4.758 7.647 0.539
3 Afghanistan 2011 3.832 7.620 0.521
4 Afghanistan 2012 3.783 7.705 0.521
Healthy life expectancy at birth Freedom to make life choices Generosity \
50.80 0.718 0.168
51.20 0.679 0.190
51.60 0.600 0.121
51.92 0.496 0.162
52.24 0.531 0.236
Perceptions of corruption Positive affect Negative affect
0.882 0.518 0.258
0.850 0.584 0.237
0.707 0.618 0.275
0.731 0.611 0.267
0.776 0.710 0.268
The above block has the top 5 rows of data in the world’s happiness report data set that can be displayed by pandas dataframe.head() function.
There are many more features that help us to deal with large data for both machine learning data science operations. Which are merging and joining data sets, Visualization, grouping, masking, and also is very helpful for performing mathematical operations on our data sets.
Let’s take another example and see how to create an output file using pandas.
file = data.to_json('output_file.json')
Data.to_json is a pandas function that is used to create a JSON file based on our pandas dataframe object (data).
The resultant JSON file will be created in our working directory with an extension of .json and the name of the file is output_file (for our above example).
These are some reasons why we need python pandas. | [
{
"code": null,
"e": 1199,
"s": 1062,
"text": "Pandas has been one of the most commonly used tools for Data Science and Machine learning, which is used for data cleaning and analysis."
},
{
"code": null,
"e": 1346,
"s": 1199,
"text": "Here, Pandas is the best tool for handling this real-world messy data. And pandas is one of the open-source python packages built on top of NumPy."
},
{
"code": null,
"e": 1522,
"s": 1346,
"text": "Handling data using pandas is very fast and effective by using pandas Series and data frame, these two pandas data structures will help you to manipulate data in various ways."
},
{
"code": null,
"e": 1777,
"s": 1522,
"text": "Based on the features available in pandas we can say pandas is best for handling data. It can handle missing data, cleaning up the data and it supports multiple file formats. This means it can read or load data in many formats like CSV, Excel, SQL, etc.,"
},
{
"code": null,
"e": 1837,
"s": 1777,
"text": "Let’s take an example and see how it’s gonna read CSV data."
},
{
"code": null,
"e": 1918,
"s": 1837,
"text": "data = pd.read_csv('world-happiness-report.csv') \nprint(data.shape) \ndata.head()"
},
{
"code": null,
"e": 2157,
"s": 1918,
"text": "In the above code, variable data stores CSV data which is a world happiness report (downloaded from Kaggle datasets) by using the read_csv function available in the pandas package. data.shape is used to give you the columns and row count."
},
{
"code": null,
"e": 3407,
"s": 2157,
"text": " Country name year Life Ladder Log GDP per capita Social support \\\n0 Afghanistan 2008 3.724 7.370 0.451\n1 Afghanistan 2009 4.402 7.540 0.552\n2 Afghanistan 2010 4.758 7.647 0.539\n3 Afghanistan 2011 3.832 7.620 0.521\n4 Afghanistan 2012 3.783 7.705 0.521\n\nHealthy life expectancy at birth Freedom to make life choices Generosity \\\n 50.80 0.718 0.168\n 51.20 0.679 0.190\n 51.60 0.600 0.121\n 51.92 0.496 0.162\n 52.24 0.531 0.236\n\nPerceptions of corruption Positive affect Negative affect\n 0.882 0.518 0.258\n 0.850 0.584 0.237\n 0.707 0.618 0.275\n 0.731 0.611 0.267\n 0.776 0.710 0.268\n\n"
},
{
"code": null,
"e": 3550,
"s": 3407,
"text": "The above block has the top 5 rows of data in the world’s happiness report data set that can be displayed by pandas dataframe.head() function."
},
{
"code": null,
"e": 3824,
"s": 3550,
"text": "There are many more features that help us to deal with large data for both machine learning data science operations. Which are merging and joining data sets, Visualization, grouping, masking, and also is very helpful for performing mathematical operations on our data sets."
},
{
"code": null,
"e": 3902,
"s": 3824,
"text": "Let’s take another example and see how to create an output file using pandas."
},
{
"code": null,
"e": 3942,
"s": 3902,
"text": "file = data.to_json('output_file.json')"
},
{
"code": null,
"e": 4056,
"s": 3942,
"text": "Data.to_json is a pandas function that is used to create a JSON file based on our pandas dataframe object (data)."
},
{
"code": null,
"e": 4213,
"s": 4056,
"text": "The resultant JSON file will be created in our working directory with an extension of .json and the name of the file is output_file (for our above example)."
},
{
"code": null,
"e": 4263,
"s": 4213,
"text": "These are some reasons why we need python pandas."
}
] |
Building Python source with OpenCV and OpenCV Contrib | by Ashish Bansal | Towards Data Science | Installing Python 3.7 on Ubuntu 14.0 LTS from Source
First, update the packages list and install the packages necessary to build Python3.7 from source:
First, update the packages list and install the packages necessary to build Python3.7 from source:
sudo apt updatesudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget
2. Download the latest release’s source code from the Python download page using the following wget command or Download it in the downloads folder.
wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz
3. Once the download is complete, extract the gzipped tarball:
cd Downloads/tar -xf Python-3.7.4.tgz
4. Next, navigate to the Python source directory and run the configure script which will perform a number of checks to make sure all of the dependencies on your system are present The enable -optimizations will optimize the Python binary by running multiple tests. This makes the build process slower.
cd Python-3.7.4 ./configure --enable-optimization
5. Start the Python build process using make:
make -j 8
For faster build time, modify the -j flag according to the processor. If you don't know the number of cores of your processor, you can find it by tying nproc command. The system uses 8 cores, so I am using -j 8 flags.
6. When the build is done, install the Python binaries by running the following command:
sudo make altinstall
Do not use the standard make install as it will overwrite the default system python3 binary.
7. That’s it. Python 3.7 has been installed and ready to be used. Verify it by typing:
python3.7 --version
The output will show the Python version:
Python 3.7.4
Installing OpenCV and OpenCV_contrib source with Python3.7 source
DownloadOpenCV DownloadOpenCV_contrib from Github open cv releases .
DownloadOpenCV DownloadOpenCV_contrib from Github open cv releases .
2. First, update the packages list and install the packages necessary to build OpenCV from source:
sudo apt-get install build-essential checkinstall yasmsudo apt-get install cmake git gfortran libgtk2.0-dev libgtk-3-dev pkg-config libavcodec-dev libavformat-dev libswscale-devsudo apt-get install libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev jasper libdc1394-22-devsudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-devsudo apt-get install libxvidcore-dev libx264-dev libx265-devsudo apt-get install libatlas-base-dev gfortransudo apt-get install libwebp-devsudo apt-get install cmake-curses-guisudo apt install qtcreatorsudo apt install qt5-defaultsudo apt-get install libgstreamer1.0-0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav gstreamer1.0-doc gstreamer1.0-tools gstreamer1.0-x gstreamer1.0-alsa gstreamer1.0-gl gstreamer1.0-gtk3 gstreamer1.0-qt5 gstreamer1.0-pulseaudiosudo apt -y install libtiff5-devsudo apt -y install libxine2-devsudo apt -y install libfaac-dev libmp3lame-dev libtheora-devsudo apt -y install libvorbis-devsudo apt -y install libopencore-amrnb-dev libopencore-amrwb-devsudo apt -y install libavresample-devsudo apt -y install x264 v4l-utilssudo apt -y install libprotobuf-dev protobuf-compilersudo apt -y install libgoogle-glog-dev libgflags-devsudo apt -y install libgphoto2-dev libeigen3-dev libhdf5-dev doxygensudo apt-get install libqt5x11extras5-dev qttools5-devsudo apt-get install openexr libopenexr-devsudo apt-get install libx11-dev libboost-python-dev
3. Go to the Downloads and unzip the OpenCV and OpenCV_contrib modules.
cd Downloads/tar -xf opencv-4.1.2.tar.gztar -xf opencv_contrib-4.1.2.tar.gz
4. Create a new folder named Development to have a virtual python environment.
cd ..mkdir Developmentcd Developmentpython3.7 -m venv OpenCV_Python3.7
Now check whether your Python Virtual environment has been created or not. Go to OpenCV_Python3.7/bin and look for activate
5. Activate the Python virtual environment
cdsource /home/anshu/Development/OpenCV_Python3.7/bin/activatepip install numpysudo apt-get update
cd Downloads/cd opencv-4.1.2/mkdir buildcd buildccmake ..
press enter and enter
OPENCV_EXTRA_MODULES_PATH = /home/anshu/Downloads/opencv_contrib-4.1.2/modules
press up arrow and down arrow to navigate through page
press c to configure
press g to generate and exit
make -j4 sudo make install
Now OpenCV with OpenCV_contrib modules has been successfully installed .Go to the /Downloads/opencv-4.1.2/build/lib/python3/ and look for cv2.cpython-37m-x86_64-linux-gnu.so file . Copy the .so file and paste it in /Home/Development/OpenCV_Python3.7/lib/python3.7/site_packages/ and rename it to cv2.so .
PyCharm Installation
PyCharm is now also available as a snap package. If you’re on Ubuntu 16.04 or later, you can install PyCharm from the command line:
sudo apt-get install snapsudo snap install pycharm-community — classic
Open your Pycharm and create a new project and set the path of the interpreter to your OpenCV_Python3.7 virtual environment
Now in the new Project create a test.py and test openCV library. Trying “TrackerMedianFlow”, which is missing from the main OpenCV build is now available.
Follow me on my Youtube Channel
https://www.youtube.com/channel/UCSp0BoeXI_EK2W0GzG7TxEw
Connect with me here:
Linkedin: https://www.linkedin.com/in/ashishban...
Github: https://github.com/Ashishb21
Medium: https://medium.com/@ashishb21
Website: http://techplanetai.com/
Email : [email protected] , [email protected] | [
{
"code": null,
"e": 225,
"s": 172,
"text": "Installing Python 3.7 on Ubuntu 14.0 LTS from Source"
},
{
"code": null,
"e": 324,
"s": 225,
"text": "First, update the packages list and install the packages necessary to build Python3.7 from source:"
},
{
"code": null,
"e": 423,
"s": 324,
"text": "First, update the packages list and install the packages necessary to build Python3.7 from source:"
},
{
"code": null,
"e": 565,
"s": 423,
"text": "sudo apt updatesudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget"
},
{
"code": null,
"e": 713,
"s": 565,
"text": "2. Download the latest release’s source code from the Python download page using the following wget command or Download it in the downloads folder."
},
{
"code": null,
"e": 775,
"s": 713,
"text": "wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz"
},
{
"code": null,
"e": 838,
"s": 775,
"text": "3. Once the download is complete, extract the gzipped tarball:"
},
{
"code": null,
"e": 876,
"s": 838,
"text": "cd Downloads/tar -xf Python-3.7.4.tgz"
},
{
"code": null,
"e": 1178,
"s": 876,
"text": "4. Next, navigate to the Python source directory and run the configure script which will perform a number of checks to make sure all of the dependencies on your system are present The enable -optimizations will optimize the Python binary by running multiple tests. This makes the build process slower."
},
{
"code": null,
"e": 1228,
"s": 1178,
"text": "cd Python-3.7.4 ./configure --enable-optimization"
},
{
"code": null,
"e": 1274,
"s": 1228,
"text": "5. Start the Python build process using make:"
},
{
"code": null,
"e": 1284,
"s": 1274,
"text": "make -j 8"
},
{
"code": null,
"e": 1502,
"s": 1284,
"text": "For faster build time, modify the -j flag according to the processor. If you don't know the number of cores of your processor, you can find it by tying nproc command. The system uses 8 cores, so I am using -j 8 flags."
},
{
"code": null,
"e": 1591,
"s": 1502,
"text": "6. When the build is done, install the Python binaries by running the following command:"
},
{
"code": null,
"e": 1612,
"s": 1591,
"text": "sudo make altinstall"
},
{
"code": null,
"e": 1705,
"s": 1612,
"text": "Do not use the standard make install as it will overwrite the default system python3 binary."
},
{
"code": null,
"e": 1792,
"s": 1705,
"text": "7. That’s it. Python 3.7 has been installed and ready to be used. Verify it by typing:"
},
{
"code": null,
"e": 1812,
"s": 1792,
"text": "python3.7 --version"
},
{
"code": null,
"e": 1853,
"s": 1812,
"text": "The output will show the Python version:"
},
{
"code": null,
"e": 1866,
"s": 1853,
"text": "Python 3.7.4"
},
{
"code": null,
"e": 1932,
"s": 1866,
"text": "Installing OpenCV and OpenCV_contrib source with Python3.7 source"
},
{
"code": null,
"e": 2001,
"s": 1932,
"text": "DownloadOpenCV DownloadOpenCV_contrib from Github open cv releases ."
},
{
"code": null,
"e": 2070,
"s": 2001,
"text": "DownloadOpenCV DownloadOpenCV_contrib from Github open cv releases ."
},
{
"code": null,
"e": 2169,
"s": 2070,
"text": "2. First, update the packages list and install the packages necessary to build OpenCV from source:"
},
{
"code": null,
"e": 3668,
"s": 2169,
"text": "sudo apt-get install build-essential checkinstall yasmsudo apt-get install cmake git gfortran libgtk2.0-dev libgtk-3-dev pkg-config libavcodec-dev libavformat-dev libswscale-devsudo apt-get install libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev jasper libdc1394-22-devsudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-devsudo apt-get install libxvidcore-dev libx264-dev libx265-devsudo apt-get install libatlas-base-dev gfortransudo apt-get install libwebp-devsudo apt-get install cmake-curses-guisudo apt install qtcreatorsudo apt install qt5-defaultsudo apt-get install libgstreamer1.0-0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav gstreamer1.0-doc gstreamer1.0-tools gstreamer1.0-x gstreamer1.0-alsa gstreamer1.0-gl gstreamer1.0-gtk3 gstreamer1.0-qt5 gstreamer1.0-pulseaudiosudo apt -y install libtiff5-devsudo apt -y install libxine2-devsudo apt -y install libfaac-dev libmp3lame-dev libtheora-devsudo apt -y install libvorbis-devsudo apt -y install libopencore-amrnb-dev libopencore-amrwb-devsudo apt -y install libavresample-devsudo apt -y install x264 v4l-utilssudo apt -y install libprotobuf-dev protobuf-compilersudo apt -y install libgoogle-glog-dev libgflags-devsudo apt -y install libgphoto2-dev libeigen3-dev libhdf5-dev doxygensudo apt-get install libqt5x11extras5-dev qttools5-devsudo apt-get install openexr libopenexr-devsudo apt-get install libx11-dev libboost-python-dev"
},
{
"code": null,
"e": 3740,
"s": 3668,
"text": "3. Go to the Downloads and unzip the OpenCV and OpenCV_contrib modules."
},
{
"code": null,
"e": 3816,
"s": 3740,
"text": "cd Downloads/tar -xf opencv-4.1.2.tar.gztar -xf opencv_contrib-4.1.2.tar.gz"
},
{
"code": null,
"e": 3895,
"s": 3816,
"text": "4. Create a new folder named Development to have a virtual python environment."
},
{
"code": null,
"e": 3966,
"s": 3895,
"text": "cd ..mkdir Developmentcd Developmentpython3.7 -m venv OpenCV_Python3.7"
},
{
"code": null,
"e": 4090,
"s": 3966,
"text": "Now check whether your Python Virtual environment has been created or not. Go to OpenCV_Python3.7/bin and look for activate"
},
{
"code": null,
"e": 4133,
"s": 4090,
"text": "5. Activate the Python virtual environment"
},
{
"code": null,
"e": 4232,
"s": 4133,
"text": "cdsource /home/anshu/Development/OpenCV_Python3.7/bin/activatepip install numpysudo apt-get update"
},
{
"code": null,
"e": 4290,
"s": 4232,
"text": "cd Downloads/cd opencv-4.1.2/mkdir buildcd buildccmake .."
},
{
"code": null,
"e": 4312,
"s": 4290,
"text": "press enter and enter"
},
{
"code": null,
"e": 4391,
"s": 4312,
"text": "OPENCV_EXTRA_MODULES_PATH = /home/anshu/Downloads/opencv_contrib-4.1.2/modules"
},
{
"code": null,
"e": 4446,
"s": 4391,
"text": "press up arrow and down arrow to navigate through page"
},
{
"code": null,
"e": 4467,
"s": 4446,
"text": "press c to configure"
},
{
"code": null,
"e": 4496,
"s": 4467,
"text": "press g to generate and exit"
},
{
"code": null,
"e": 4523,
"s": 4496,
"text": "make -j4 sudo make install"
},
{
"code": null,
"e": 4828,
"s": 4523,
"text": "Now OpenCV with OpenCV_contrib modules has been successfully installed .Go to the /Downloads/opencv-4.1.2/build/lib/python3/ and look for cv2.cpython-37m-x86_64-linux-gnu.so file . Copy the .so file and paste it in /Home/Development/OpenCV_Python3.7/lib/python3.7/site_packages/ and rename it to cv2.so ."
},
{
"code": null,
"e": 4849,
"s": 4828,
"text": "PyCharm Installation"
},
{
"code": null,
"e": 4981,
"s": 4849,
"text": "PyCharm is now also available as a snap package. If you’re on Ubuntu 16.04 or later, you can install PyCharm from the command line:"
},
{
"code": null,
"e": 5052,
"s": 4981,
"text": "sudo apt-get install snapsudo snap install pycharm-community — classic"
},
{
"code": null,
"e": 5176,
"s": 5052,
"text": "Open your Pycharm and create a new project and set the path of the interpreter to your OpenCV_Python3.7 virtual environment"
},
{
"code": null,
"e": 5331,
"s": 5176,
"text": "Now in the new Project create a test.py and test openCV library. Trying “TrackerMedianFlow”, which is missing from the main OpenCV build is now available."
},
{
"code": null,
"e": 5363,
"s": 5331,
"text": "Follow me on my Youtube Channel"
},
{
"code": null,
"e": 5420,
"s": 5363,
"text": "https://www.youtube.com/channel/UCSp0BoeXI_EK2W0GzG7TxEw"
},
{
"code": null,
"e": 5442,
"s": 5420,
"text": "Connect with me here:"
},
{
"code": null,
"e": 5493,
"s": 5442,
"text": "Linkedin: https://www.linkedin.com/in/ashishban..."
},
{
"code": null,
"e": 5530,
"s": 5493,
"text": "Github: https://github.com/Ashishb21"
},
{
"code": null,
"e": 5568,
"s": 5530,
"text": "Medium: https://medium.com/@ashishb21"
},
{
"code": null,
"e": 5602,
"s": 5568,
"text": "Website: http://techplanetai.com/"
}
] |
How will you handle alerts in Selenium with python? | We can handle alerts in Selenium with the help of numerous APIs. The alerts are basically the browser popups that are triggered for either dismissing or accepting the data entered.
All these actions are performed by Selenium with the help of class selenium.webdriver.common.alert.Alert(driver). It has the methods to extract the text on a particular alert, accepting and dismissing these pop ups of the browser.
The elements on the alert cannot be identified by simply spying them from the html code. This is because these are considered implemented by Javascript.
Selenium alert methods are listed below −
accept() – This method accepts an alert pop up.
accept() – This method accepts an alert pop up.
Syntax −
a = Alert(driver)
a.accept()
dismiss() – This method dismisses an alert pop up.
dismiss() – This method dismisses an alert pop up.
Syntax −
a = Alert(driver)
a.dismiss()
send_keys(value) – This method keys in text on alert pop up.
send_keys(value) – This method keys in text on alert pop up.
Syntax −
a = Alert(driver)
a.send_keys("Yes")
text – This method extracts text from the alert pop up.
text – This method extracts text from the alert pop up.
Syntax −
a = Alert(driver)
print(a.text)
switch_to.alert – This method switches focus to alert.
switch_to.alert – This method switches focus to alert.
Syntax −
a = driver.switch_to.alert
Code Implementation with alert methods.
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
#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/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
#click on submit button
driver.find_element_by_xpath("//button[@name='submit']").click()
# alert object creation and switching focus to alert
a = driver.switch_to.alert
# accept the alert
a.accept()
driver.close() | [
{
"code": null,
"e": 1243,
"s": 1062,
"text": "We can handle alerts in Selenium with the help of numerous APIs. The alerts are basically the browser popups that are triggered for either dismissing or accepting the data entered."
},
{
"code": null,
"e": 1474,
"s": 1243,
"text": "All these actions are performed by Selenium with the help of class selenium.webdriver.common.alert.Alert(driver). It has the methods to extract the text on a particular alert, accepting and dismissing these pop ups of the browser."
},
{
"code": null,
"e": 1627,
"s": 1474,
"text": "The elements on the alert cannot be identified by simply spying them from the html code. This is because these are considered implemented by Javascript."
},
{
"code": null,
"e": 1669,
"s": 1627,
"text": "Selenium alert methods are listed below −"
},
{
"code": null,
"e": 1717,
"s": 1669,
"text": "accept() – This method accepts an alert pop up."
},
{
"code": null,
"e": 1765,
"s": 1717,
"text": "accept() – This method accepts an alert pop up."
},
{
"code": null,
"e": 1774,
"s": 1765,
"text": "Syntax −"
},
{
"code": null,
"e": 1803,
"s": 1774,
"text": "a = Alert(driver)\na.accept()"
},
{
"code": null,
"e": 1854,
"s": 1803,
"text": "dismiss() – This method dismisses an alert pop up."
},
{
"code": null,
"e": 1905,
"s": 1854,
"text": "dismiss() – This method dismisses an alert pop up."
},
{
"code": null,
"e": 1914,
"s": 1905,
"text": "Syntax −"
},
{
"code": null,
"e": 1944,
"s": 1914,
"text": "a = Alert(driver)\na.dismiss()"
},
{
"code": null,
"e": 2005,
"s": 1944,
"text": "send_keys(value) – This method keys in text on alert pop up."
},
{
"code": null,
"e": 2066,
"s": 2005,
"text": "send_keys(value) – This method keys in text on alert pop up."
},
{
"code": null,
"e": 2075,
"s": 2066,
"text": "Syntax −"
},
{
"code": null,
"e": 2112,
"s": 2075,
"text": "a = Alert(driver)\na.send_keys(\"Yes\")"
},
{
"code": null,
"e": 2168,
"s": 2112,
"text": "text – This method extracts text from the alert pop up."
},
{
"code": null,
"e": 2224,
"s": 2168,
"text": "text – This method extracts text from the alert pop up."
},
{
"code": null,
"e": 2233,
"s": 2224,
"text": "Syntax −"
},
{
"code": null,
"e": 2265,
"s": 2233,
"text": "a = Alert(driver)\nprint(a.text)"
},
{
"code": null,
"e": 2320,
"s": 2265,
"text": "switch_to.alert – This method switches focus to alert."
},
{
"code": null,
"e": 2375,
"s": 2320,
"text": "switch_to.alert – This method switches focus to alert."
},
{
"code": null,
"e": 2384,
"s": 2375,
"text": "Syntax −"
},
{
"code": null,
"e": 2411,
"s": 2384,
"text": "a = driver.switch_to.alert"
},
{
"code": null,
"e": 2451,
"s": 2411,
"text": "Code Implementation with alert methods."
},
{
"code": null,
"e": 3161,
"s": 2451,
"text": "from selenium import webdriver\nfrom selenium.webdriver.common.alert import Alert\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/selenium/selenium_automation_practice.htm\")\n#to refresh the browser\ndriver.refresh()\n#click on submit button\ndriver.find_element_by_xpath(\"//button[@name='submit']\").click()\n# alert object creation and switching focus to alert\na = driver.switch_to.alert\n# accept the alert\na.accept()\ndriver.close()"
}
] |
Using signal processing to extract neural events in Python — Spike sorting | by Carsten Klein | Towards Data Science | Biological neural networks such as the human brain consist of specialized cells called neurons. There are various types of neurons but all of them are based on the same concept. Signaling molecules called neurotransmitters are released at the synapse, the connection point between two neurons. Neurotransmitters alter the membrane potential of the post-synaptic cell by interacting with ion channels within their cellular membrane. If the depolarization of the post-synaptic cell is strong enough an action potential is generated at the axon hillock. The action potential will travel along the axon and trigger the release of neurotransmitters into the synaptic cleft which will affect the membrane potential of the next neuron. This way a signal can be passed on from one cell to the next through the (entire) network with the action potential being the trigger for the release of neurotransmitters at the synapse. Neural communication is electro-chemical in nature and knowing when and under which conditions action potentials are generated can give valuable insights into the workings of the brain.
But studying the activity of individual neurons inside the living brain is a challenging task. There is no non-invasive method available through which neural activity can be monitored on a single cell level in real time. Usually an electrode is inserted into the brain to record the electrical activity in its near vicinity. In these kind of electrophysiological recordings an action potential appears as a fast high amplitude spike. But because neurons are densely packed inside the brain a recording electrode will typically pick up spikes from more than just one neuron at a time. So if we want to understand how individual neurons behave we need to extract the spikes from the recording and check if they were generated by one or potentially several neurons. Extracting and clustering spikes from the data is referred to as spike sorting. In the following we will outline the process of extracting individual spikes from raw data and preparing them for spike sorting.
So first we need data. There is a popular spike sorting algorithm available for Matlab called Wave Clus. In the data section of their web page they provide a test dataset which we will use here. According to the information provided on the web page the recording is about 30 minutes long and comes from an epilepsy patient. The data is stored in an .ncs file which is the data format of the company that manufactured the recording system. So if we want to read the recording into Python we need to understand how the data is stored. There is a detailed description about the .ncs file format on the companies web page which we can use to import the file:
>>> # Define data path>>> data_file = './UCLA_data/CSC4.Ncs'>>> # Header has 16 kilobytes length>>> header_size = 16 * 1024>>> # Open file>>> fid = open(data_file, 'rb')>>> # Skip header by shifting position by header size>>> fid.seek(header_size)>>> # Read data according to Neuralynx information>>> data_format = np.dtype([('TimeStamp', np.uint64),>>> ('ChannelNumber', np.uint32),>>> ('SampleFreq', np.uint32),>>> ('NumValidSamples', np.uint32),>>> ('Samples', np.int16, 512)])>>> raw = np.fromfile(fid, dtype=data_format)>>> # Close file>>> fid.close()>>> # Get sampling frequency>>> sf = raw['SampleFreq'][0]>>> # Create data vector>>> data = raw['Samples'].ravel()
As we can see in the above code the .ncs file also contains some additional information about the recording. Most importantly, the sampling frequency which tells us how many data points were recorded per second. With the sampling frequency and the number of samples in the data we can now create a time vector which allows us to plot the signal over time. The following code will do this and plot the first second of the signal.
>>> # Determine duration of recording in seconds>>> dur_sec = data.shape[0]/sf>>> # Create time vector>>> time = np.linspace(0, dur_sec,data.shape[0])>>> # Plot first second of data>>> fig, ax = plt.subplots(figsize=(15, 5))>>> ax.plot(time[0:sf], data[0:sf])>>> ax.set_title('Broadband; Sampling Frequency: {}Hz'.format(sf), >>> fontsize=23)>>> ax.set_xlim(0, time[sf])>>> ax.set_xlabel('time [s]', fontsize=20)>>> ax.set_ylabel('amplitude [uV]', fontsize=20)>>> plt.show()
Alright, so do we see spikes? ... No we don’t. But we do see some kind of rhythmic activity in the data. So is this a meaningful signal? Again the answer is no. If we were to count the number of peaks in this first second of data we would end up with a count of 60 peaks, meaning we are looking at a 60 Hz oscillation. We can further confirm this by plotting the power spectrum of the signal which shows a clear peak at 60 Hz.
So what are we looking at? On the web page where we got the data from it says that the recording is coming from Itzhak Fried’s lab at UCLA in he US. The power supply frequency in the United States is 60 Hz. So what we are looking at is actually electrical noise from the electronic devices that were in the room during the data collection.
Even though there is 60 Hz noise in the data we can still work with it. Lucky for us action potentials are fast events that only last for 1 to 2 milliseconds. So what we can do here is to filter the raw broadband signal in a range that excludes the 60 Hz noise. A typical filter setting is 500 to 9000 Hz and our Python implementation looks as follows:
>>> # Import libarys>>> from scipy.signal import butter, lfilter>>> def filter_data(data, low=500, high=9000, sf, order=2):>>> # Determine Nyquist frequency>>> nyq = sf/2>>> # Set bands>>> low = low/nyq>>> high = high/nyq>>> # Calculate coefficients>>> b, a = butter(order, [low, high], btype='band')>>> # Filter signal>>> filtered_data = lfilter(b, a, data)>>> >>> return filtered_data
Processing the data with the above function will give us the high frequency band, or spike channel, of the signal. Our expectation is that this spike channel contains the action potentials and has no 60 Hz noise anymore. So lets look at the filtered spike channel and compare it to the raw broad band signal.
As expected the spike channel shows no 60 Hz oscillation anymore. And most importantly we finally can see the first spike in the recording. Around 0.5 seconds into the recording it is clearly visible in the filtered data. Also, now that we now where to look, we can see it in the unfiltered data. However it is harder to spot because of the 60 Hz noise.
Now that we separated the high frequency spike band from the noisy low frequency band we can extract the individual spikes. For this we will write a simple function that does the following:
Find data points in the signal that are above a certain thresholdDefine a window around these events and “cut them out”Align them to their peak amplitude
Find data points in the signal that are above a certain threshold
Define a window around these events and “cut them out”
Align them to their peak amplitude
Additionally we will also define an upper threshold. Data points above this threshold will be rejected as they are likely high frequency artifacts. Such artifacts may arise through movements of the patient or might reflect electrical events like switching on or off a light bulb in the room. You can have a detailed look at the spike extraction function in the Jupyter Notebook. Here we will just have a look at 100 random spikes that were extracted form the signal with our function.
In the above plot we can see that there are at least two types of waveforms in the data. One group of spikes with a sharp high amplitude peak and a second group with a broader initial peak. So most likely these spikes were generated by more than one neuron. The next task therefore is to find a way to group the waveforms into different clusters. But since this cannot be coded or explained in two or three lines we will have a look at the spike sorting topic in the next post.
Meanwhile you can check out the complete code here, follow me on Twitter or connect via LinkedIn.
The code for this project can be found on Github. | [
{
"code": null,
"e": 1274,
"s": 172,
"text": "Biological neural networks such as the human brain consist of specialized cells called neurons. There are various types of neurons but all of them are based on the same concept. Signaling molecules called neurotransmitters are released at the synapse, the connection point between two neurons. Neurotransmitters alter the membrane potential of the post-synaptic cell by interacting with ion channels within their cellular membrane. If the depolarization of the post-synaptic cell is strong enough an action potential is generated at the axon hillock. The action potential will travel along the axon and trigger the release of neurotransmitters into the synaptic cleft which will affect the membrane potential of the next neuron. This way a signal can be passed on from one cell to the next through the (entire) network with the action potential being the trigger for the release of neurotransmitters at the synapse. Neural communication is electro-chemical in nature and knowing when and under which conditions action potentials are generated can give valuable insights into the workings of the brain."
},
{
"code": null,
"e": 2246,
"s": 1274,
"text": "But studying the activity of individual neurons inside the living brain is a challenging task. There is no non-invasive method available through which neural activity can be monitored on a single cell level in real time. Usually an electrode is inserted into the brain to record the electrical activity in its near vicinity. In these kind of electrophysiological recordings an action potential appears as a fast high amplitude spike. But because neurons are densely packed inside the brain a recording electrode will typically pick up spikes from more than just one neuron at a time. So if we want to understand how individual neurons behave we need to extract the spikes from the recording and check if they were generated by one or potentially several neurons. Extracting and clustering spikes from the data is referred to as spike sorting. In the following we will outline the process of extracting individual spikes from raw data and preparing them for spike sorting."
},
{
"code": null,
"e": 2901,
"s": 2246,
"text": "So first we need data. There is a popular spike sorting algorithm available for Matlab called Wave Clus. In the data section of their web page they provide a test dataset which we will use here. According to the information provided on the web page the recording is about 30 minutes long and comes from an epilepsy patient. The data is stored in an .ncs file which is the data format of the company that manufactured the recording system. So if we want to read the recording into Python we need to understand how the data is stored. There is a detailed description about the .ncs file format on the companies web page which we can use to import the file:"
},
{
"code": null,
"e": 3670,
"s": 2901,
"text": ">>> # Define data path>>> data_file = './UCLA_data/CSC4.Ncs'>>> # Header has 16 kilobytes length>>> header_size = 16 * 1024>>> # Open file>>> fid = open(data_file, 'rb')>>> # Skip header by shifting position by header size>>> fid.seek(header_size)>>> # Read data according to Neuralynx information>>> data_format = np.dtype([('TimeStamp', np.uint64),>>> ('ChannelNumber', np.uint32),>>> ('SampleFreq', np.uint32),>>> ('NumValidSamples', np.uint32),>>> ('Samples', np.int16, 512)])>>> raw = np.fromfile(fid, dtype=data_format)>>> # Close file>>> fid.close()>>> # Get sampling frequency>>> sf = raw['SampleFreq'][0]>>> # Create data vector>>> data = raw['Samples'].ravel()"
},
{
"code": null,
"e": 4099,
"s": 3670,
"text": "As we can see in the above code the .ncs file also contains some additional information about the recording. Most importantly, the sampling frequency which tells us how many data points were recorded per second. With the sampling frequency and the number of samples in the data we can now create a time vector which allows us to plot the signal over time. The following code will do this and plot the first second of the signal."
},
{
"code": null,
"e": 4588,
"s": 4099,
"text": ">>> # Determine duration of recording in seconds>>> dur_sec = data.shape[0]/sf>>> # Create time vector>>> time = np.linspace(0, dur_sec,data.shape[0])>>> # Plot first second of data>>> fig, ax = plt.subplots(figsize=(15, 5))>>> ax.plot(time[0:sf], data[0:sf])>>> ax.set_title('Broadband; Sampling Frequency: {}Hz'.format(sf), >>> fontsize=23)>>> ax.set_xlim(0, time[sf])>>> ax.set_xlabel('time [s]', fontsize=20)>>> ax.set_ylabel('amplitude [uV]', fontsize=20)>>> plt.show()"
},
{
"code": null,
"e": 5015,
"s": 4588,
"text": "Alright, so do we see spikes? ... No we don’t. But we do see some kind of rhythmic activity in the data. So is this a meaningful signal? Again the answer is no. If we were to count the number of peaks in this first second of data we would end up with a count of 60 peaks, meaning we are looking at a 60 Hz oscillation. We can further confirm this by plotting the power spectrum of the signal which shows a clear peak at 60 Hz."
},
{
"code": null,
"e": 5355,
"s": 5015,
"text": "So what are we looking at? On the web page where we got the data from it says that the recording is coming from Itzhak Fried’s lab at UCLA in he US. The power supply frequency in the United States is 60 Hz. So what we are looking at is actually electrical noise from the electronic devices that were in the room during the data collection."
},
{
"code": null,
"e": 5708,
"s": 5355,
"text": "Even though there is 60 Hz noise in the data we can still work with it. Lucky for us action potentials are fast events that only last for 1 to 2 milliseconds. So what we can do here is to filter the raw broadband signal in a range that excludes the 60 Hz noise. A typical filter setting is 500 to 9000 Hz and our Python implementation looks as follows:"
},
{
"code": null,
"e": 6138,
"s": 5708,
"text": ">>> # Import libarys>>> from scipy.signal import butter, lfilter>>> def filter_data(data, low=500, high=9000, sf, order=2):>>> # Determine Nyquist frequency>>> nyq = sf/2>>> # Set bands>>> low = low/nyq>>> high = high/nyq>>> # Calculate coefficients>>> b, a = butter(order, [low, high], btype='band')>>> # Filter signal>>> filtered_data = lfilter(b, a, data)>>> >>> return filtered_data"
},
{
"code": null,
"e": 6447,
"s": 6138,
"text": "Processing the data with the above function will give us the high frequency band, or spike channel, of the signal. Our expectation is that this spike channel contains the action potentials and has no 60 Hz noise anymore. So lets look at the filtered spike channel and compare it to the raw broad band signal."
},
{
"code": null,
"e": 6801,
"s": 6447,
"text": "As expected the spike channel shows no 60 Hz oscillation anymore. And most importantly we finally can see the first spike in the recording. Around 0.5 seconds into the recording it is clearly visible in the filtered data. Also, now that we now where to look, we can see it in the unfiltered data. However it is harder to spot because of the 60 Hz noise."
},
{
"code": null,
"e": 6991,
"s": 6801,
"text": "Now that we separated the high frequency spike band from the noisy low frequency band we can extract the individual spikes. For this we will write a simple function that does the following:"
},
{
"code": null,
"e": 7145,
"s": 6991,
"text": "Find data points in the signal that are above a certain thresholdDefine a window around these events and “cut them out”Align them to their peak amplitude"
},
{
"code": null,
"e": 7211,
"s": 7145,
"text": "Find data points in the signal that are above a certain threshold"
},
{
"code": null,
"e": 7266,
"s": 7211,
"text": "Define a window around these events and “cut them out”"
},
{
"code": null,
"e": 7301,
"s": 7266,
"text": "Align them to their peak amplitude"
},
{
"code": null,
"e": 7786,
"s": 7301,
"text": "Additionally we will also define an upper threshold. Data points above this threshold will be rejected as they are likely high frequency artifacts. Such artifacts may arise through movements of the patient or might reflect electrical events like switching on or off a light bulb in the room. You can have a detailed look at the spike extraction function in the Jupyter Notebook. Here we will just have a look at 100 random spikes that were extracted form the signal with our function."
},
{
"code": null,
"e": 8264,
"s": 7786,
"text": "In the above plot we can see that there are at least two types of waveforms in the data. One group of spikes with a sharp high amplitude peak and a second group with a broader initial peak. So most likely these spikes were generated by more than one neuron. The next task therefore is to find a way to group the waveforms into different clusters. But since this cannot be coded or explained in two or three lines we will have a look at the spike sorting topic in the next post."
},
{
"code": null,
"e": 8362,
"s": 8264,
"text": "Meanwhile you can check out the complete code here, follow me on Twitter or connect via LinkedIn."
}
] |
DecimalFormat("00.00E0") in Java | DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. Let us set DecimalFormat("00.00E0") and use the format() method as well.
DecimalFormat decFormat = new DecimalFormat("00.00E0");
System.out.println(decFormat.format(-289.8787));
System.out.println(decFormat.format(8.19));
Since, we have used DecimalFormat class in Java, therefore importing the following package is a must −
import java.text.DecimalFormat;
The following is the complete example −
Live Demo
import java.text.DecimalFormat;
public class Demo {
public static void main(String[] argv) throws Exception {
DecimalFormat decFormat = new DecimalFormat("00.00E0");
System.out.println(decFormat.format(-289.8787));
System.out.println(decFormat.format(8.19));
System.out.println(decFormat.format(9897.88));
System.out.println(decFormat.format(9.9099));
System.out.println(decFormat.format(12.788));
System.out.println(decFormat.format(9.678));
}
}
-28.99E1
81.90E-1
98.98E2
99.10E-1
12.79E0
96.78E-1 | [
{
"code": null,
"e": 1218,
"s": 1062,
"text": "DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. Let us set DecimalFormat(\"00.00E0\") and use the format() method as well."
},
{
"code": null,
"e": 1367,
"s": 1218,
"text": "DecimalFormat decFormat = new DecimalFormat(\"00.00E0\");\nSystem.out.println(decFormat.format(-289.8787));\nSystem.out.println(decFormat.format(8.19));"
},
{
"code": null,
"e": 1470,
"s": 1367,
"text": "Since, we have used DecimalFormat class in Java, therefore importing the following package is a must −"
},
{
"code": null,
"e": 1502,
"s": 1470,
"text": "import java.text.DecimalFormat;"
},
{
"code": null,
"e": 1542,
"s": 1502,
"text": "The following is the complete example −"
},
{
"code": null,
"e": 1553,
"s": 1542,
"text": " Live Demo"
},
{
"code": null,
"e": 2048,
"s": 1553,
"text": "import java.text.DecimalFormat;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n DecimalFormat decFormat = new DecimalFormat(\"00.00E0\");\n System.out.println(decFormat.format(-289.8787));\n System.out.println(decFormat.format(8.19));\n System.out.println(decFormat.format(9897.88));\n System.out.println(decFormat.format(9.9099));\n System.out.println(decFormat.format(12.788));\n System.out.println(decFormat.format(9.678));\n }\n}"
},
{
"code": null,
"e": 2100,
"s": 2048,
"text": "-28.99E1\n81.90E-1\n98.98E2\n99.10E-1\n12.79E0\n96.78E-1"
}
] |
How Does k-Means Clustering in Machine Learning Work? | by Anas Al-Masri | Towards Data Science | One of the most famous topics under the realm of Unsupervised Learning in Machine Learning is k-Means Clustering. Even though this clustering algorithm is fairly simple, it can look challenging to newcomers into the field. In this post, I try to tackle the process of k-Means Clustering with two different examples. The first example will focus more on the big picture and visualizing the process, while the second example focuses on the underlying calculation involved.
The main difference between Supervised and Unsupervised learning algorithms is the absence of data labels in the latter. With unsupervised learning, data features are fed into the learning algorithm, which determines how to label them (usually with numbers 0,1,2..) and based on what. This “based on what” part dictates which unsupervised learning algorithm to follow.
Most unsupervised learning-based applications utilize the sub-field called Clustering. Clustering is the process of grouping data samples together into clusters based on a certain feature that they share — exactly the purpose of unsupervised learning in the first place.
Being a clustering algorithm, k-Means takes data points as input and groups them into k clusters. This process of grouping is the training phase of the learning algorithm. The result would be a model that takes a data sample as input and returns the cluster that the new data point belongs to, according the training that the model went through. How can this be useful? Well, that’s how content promotion and recommendation usually works — in a very simplistic manner. Websites may choose to put people in bubbles (i.e. clusters) with other people who share similar activities (i.e. features) on the website. This way, the recommended content will be somewhat on-point, as existing users with similar activities are likely to be interested in similar content. Moreover, as a new person goes into the ecosystem of the website, that person will be placed within a particular cluster, and the content recommendation system takes care of the rest.
Building on that idea, k-Means is just a clustering algorithm. It uses the distance between points as a measure of similarity, based on k averages (i.e. means). This is a very interesting algorithm, so let’s get down to business.
The idea behind k-Means is that, we want to add k new points to the data we have. Each one of those points — called a Centroid — will be going around trying to center itself in the middle of one of the k clusters we have. Once those points stop moving, our clustering algorithm stops.
As you might’ve suspected, the value of k is of great importance. This k is called a hyper-parameter; a variable whose value we set before training. This k specifies the number of clusters we want the algorithm to yield. This number of clusters is actually the number of centroids going around in the data.
Before we go further, let’s take a look at how everything so far fits within the big picture:
We know that the core of Machine Learning lies on the idea of generalization — making a reliable prediction of outputs for inputs that the model has never seen before.
Unsupervised Learning is all about grouping data samples together, regardless of their labels (if they have any).
Clustering is an Unsupervised Learning algorithm that groups data samples into k clusters.
The algorithm yields the k clusters based on k averages of points (i.e. centroids) that roam around the data set trying to center themselves — one in the middle of each cluster.
What is a better summary of an algorithm than pseudo-code?
Assign initial values for each u (from u=1 till u=k);Repeat { Assign each point in the input data to the u that is closest to it in value;Calculate the new mean for each u;if all u values are unchanged { break out of loop; }}
If you’ve read any of my posts before, you probably know that I like to explain with an example first then talk about the technical aspect of our topic. Moreover, I don’t like to walk the reader through the overwhelming mathematics behind topics, as I believe those are more important to researchers than to people who have a self-interest in the matter.
Back to k-Means and our first example. Let’s say we have a data set that looks like the following figure when plotted out:
To us humans, this data looks like it perfectly fits within three groups (i.e. clusters). However, machines can’t see that, as those points are actual data “points” whose values are just numbers that cannot be sensible to the machine.
Referring to the objective of clustering, we have a set of unlabeled data points that we want to put in groups. Those groups are usually labeled with numbers (0,1,2..) by the algorithm itself. Implicitly, what we really need is actually a decision boundary that separates the groups. Why? In practice, inference works by associating a data point with a respective cluster. That’s where the decision boundary appears to be important.
k-Means clustering is all about putting the training points we have into clusters. But the purpose of it follows the same idea. We want to know which data points belong together without having any labels for any of them.
We start the algorithm by placing k different averages (i.e. means) whose values are either initialized randomly or set to real data points on the plane. Let’s start with k=3, as the data “seems” to be falling into three groups (we will get back to this “seems” word later in the post). For explanation-related purposes, lets randomly initialize the values (i.e. positions) of the averages:
Now, the algorithm goes through the data points one-by-one, measuring the distance between each point and the three centroids (A, B and C). The algorithm then groups the the data point with the closest centroid (i.e. closest in distance).
For instance, data point number 21 will belong to group A in the green color, merely because it’s closer in distance to centroid A:
As soon as we’re done associating each data point with its closest centroid, we re-calculate the means — the values of the centroids; the new value of a centroid is the sum of all the points belonging to that centroid divided by the number of points in the group.
We keep doing the above until no centroid changes its value in re-calculation. This means that each centroid has centered itself in the middle of its cluster, which is surrounded by its own circular decision boundary:
Let’s take another example, but from a different perspective this time. Let’s say we have the following set of points that we want to cluster into 3 groups:
This data is not put in a visually-appealing manner. We just have a set of points that we want to cluster. Another important note is that the values in the circles symbolizing those data points are actual values of the points. They’re not put a way of showing the sequence of data like our previous example. Rather, these values are a quantification of some feature value F. I put them this way to make it easier on you to understand how the calculation of means works.
Let’s prepare our empty clusters:
Think of these clusters as just bags that will contain points from our data set.
Let’s initialize the U values (i.e. means/centroids) to:
U1 = 6U2 = 12U3 = 18
These values can be random, but for simplicity reasons, they were chosen to be uniformly scattered along the data space (1 through 24).
Since we already have our means, we can start calculating distances between any point whose feature F value is F and the three means (U1, U2 & U3), where the absolute distance follows:
distance = | F - U |
For starters, let’s take the data point whose feature F value is 20:
|20 - U1| = |20 - 6| = 14|20 - U2| = |20 - 12| = 8|20 - U3| = |20 - 18| = 2
According to the above calculations, the data point whose value is 20 is closer in distance to mean U3. Therefore, we “label” the point as U3 by putting it in its respective cluster/bag:
And the same goes for all the other points:
|3 - U1| = |20 - 6| = 3|3 - U2| = |20 - 12| = 9|3 - U3| = |20 - 18| = 15
And so on, until we have all our data points in their appropriate clusters:
Following the algorithm, we now need to re-calculate the means (U1, U2 as well as U3):
U1 = (3+8+1+3+7+5+2+3+8) / 9 = 4.44U2 = (9+10+14+9) / 4 = 10.5U3 = (20+24+23) / 3 = 22.33
Upon the beginning of our execution, our U values were 6, 12, and 18, respectively. Now, after the first iteration, the values became 4.44, 10.5 and 22.33, respectively. We now have to go through the distance calculation step again, but with the new mean values. We empty out our bags/clusters, and start again:
Let’s start with a random point this time, say, the point whose feature F value is 8. The distance calculations would follow:
|8 - U1| = |8 - 4.44| = 3.56|8 - U2| = |8 - 10.5| = 2.5|8 - U3| = |8 - 22.33| = 14.33
So, the data point with the value 8 belongs to the cluster of mean value U2, as it’s is closest to it in distance. If you still recall, the same data point (8) belonged to U1 in the first run. This makes it evident how important the mean values are.
Running the algorithm over and over again until the mean values don’t change upon calculation will reach the following formation, with mean values 2.83, 9.29 and 22.33, respectively:
As you’ve seen in our second example, the mean values we operate with at any given point are of great importance to the reliability of the model. This does not exclude the initial values. In fact, with really bad starting positions, the algorithm could get the clustering completely wrong! Therefore, another initialization approach would be to choose our initial k positions from the data set itself, setting one of the points as a mean value in its own surroundings. Either way, it is common practice to run the algorithm on the same data set repeatedly until we find a most common solution and clustering formation — and we stick to it.
Remember the stage at which we said that data “seems” to have been partitioned into three? Well, that was only to show the importance of the human eye in such applications. Since we don’t have a ground truth error estimation (as it usually requires labels), we need another measure for the hyper-parameters. For a lot of applications, a person looking at the plot and determining the k value is sufficient. However, this does not overestimate the importance of the k value in any way.
Finally, one of the apparent strengths of k-Means is the fact that it gives an average value of the feature over the cluster, not just the cluster itself. This could be very useful in segmentation-related image processing tasks — when dealing with segmentation as a clustering problem. | [
{
"code": null,
"e": 643,
"s": 172,
"text": "One of the most famous topics under the realm of Unsupervised Learning in Machine Learning is k-Means Clustering. Even though this clustering algorithm is fairly simple, it can look challenging to newcomers into the field. In this post, I try to tackle the process of k-Means Clustering with two different examples. The first example will focus more on the big picture and visualizing the process, while the second example focuses on the underlying calculation involved."
},
{
"code": null,
"e": 1012,
"s": 643,
"text": "The main difference between Supervised and Unsupervised learning algorithms is the absence of data labels in the latter. With unsupervised learning, data features are fed into the learning algorithm, which determines how to label them (usually with numbers 0,1,2..) and based on what. This “based on what” part dictates which unsupervised learning algorithm to follow."
},
{
"code": null,
"e": 1283,
"s": 1012,
"text": "Most unsupervised learning-based applications utilize the sub-field called Clustering. Clustering is the process of grouping data samples together into clusters based on a certain feature that they share — exactly the purpose of unsupervised learning in the first place."
},
{
"code": null,
"e": 2227,
"s": 1283,
"text": "Being a clustering algorithm, k-Means takes data points as input and groups them into k clusters. This process of grouping is the training phase of the learning algorithm. The result would be a model that takes a data sample as input and returns the cluster that the new data point belongs to, according the training that the model went through. How can this be useful? Well, that’s how content promotion and recommendation usually works — in a very simplistic manner. Websites may choose to put people in bubbles (i.e. clusters) with other people who share similar activities (i.e. features) on the website. This way, the recommended content will be somewhat on-point, as existing users with similar activities are likely to be interested in similar content. Moreover, as a new person goes into the ecosystem of the website, that person will be placed within a particular cluster, and the content recommendation system takes care of the rest."
},
{
"code": null,
"e": 2457,
"s": 2227,
"text": "Building on that idea, k-Means is just a clustering algorithm. It uses the distance between points as a measure of similarity, based on k averages (i.e. means). This is a very interesting algorithm, so let’s get down to business."
},
{
"code": null,
"e": 2742,
"s": 2457,
"text": "The idea behind k-Means is that, we want to add k new points to the data we have. Each one of those points — called a Centroid — will be going around trying to center itself in the middle of one of the k clusters we have. Once those points stop moving, our clustering algorithm stops."
},
{
"code": null,
"e": 3049,
"s": 2742,
"text": "As you might’ve suspected, the value of k is of great importance. This k is called a hyper-parameter; a variable whose value we set before training. This k specifies the number of clusters we want the algorithm to yield. This number of clusters is actually the number of centroids going around in the data."
},
{
"code": null,
"e": 3143,
"s": 3049,
"text": "Before we go further, let’s take a look at how everything so far fits within the big picture:"
},
{
"code": null,
"e": 3311,
"s": 3143,
"text": "We know that the core of Machine Learning lies on the idea of generalization — making a reliable prediction of outputs for inputs that the model has never seen before."
},
{
"code": null,
"e": 3425,
"s": 3311,
"text": "Unsupervised Learning is all about grouping data samples together, regardless of their labels (if they have any)."
},
{
"code": null,
"e": 3516,
"s": 3425,
"text": "Clustering is an Unsupervised Learning algorithm that groups data samples into k clusters."
},
{
"code": null,
"e": 3694,
"s": 3516,
"text": "The algorithm yields the k clusters based on k averages of points (i.e. centroids) that roam around the data set trying to center themselves — one in the middle of each cluster."
},
{
"code": null,
"e": 3753,
"s": 3694,
"text": "What is a better summary of an algorithm than pseudo-code?"
},
{
"code": null,
"e": 3993,
"s": 3753,
"text": "Assign initial values for each u (from u=1 till u=k);Repeat { Assign each point in the input data to the u that is closest to it in value;Calculate the new mean for each u;if all u values are unchanged { break out of loop; }}"
},
{
"code": null,
"e": 4348,
"s": 3993,
"text": "If you’ve read any of my posts before, you probably know that I like to explain with an example first then talk about the technical aspect of our topic. Moreover, I don’t like to walk the reader through the overwhelming mathematics behind topics, as I believe those are more important to researchers than to people who have a self-interest in the matter."
},
{
"code": null,
"e": 4471,
"s": 4348,
"text": "Back to k-Means and our first example. Let’s say we have a data set that looks like the following figure when plotted out:"
},
{
"code": null,
"e": 4706,
"s": 4471,
"text": "To us humans, this data looks like it perfectly fits within three groups (i.e. clusters). However, machines can’t see that, as those points are actual data “points” whose values are just numbers that cannot be sensible to the machine."
},
{
"code": null,
"e": 5139,
"s": 4706,
"text": "Referring to the objective of clustering, we have a set of unlabeled data points that we want to put in groups. Those groups are usually labeled with numbers (0,1,2..) by the algorithm itself. Implicitly, what we really need is actually a decision boundary that separates the groups. Why? In practice, inference works by associating a data point with a respective cluster. That’s where the decision boundary appears to be important."
},
{
"code": null,
"e": 5360,
"s": 5139,
"text": "k-Means clustering is all about putting the training points we have into clusters. But the purpose of it follows the same idea. We want to know which data points belong together without having any labels for any of them."
},
{
"code": null,
"e": 5751,
"s": 5360,
"text": "We start the algorithm by placing k different averages (i.e. means) whose values are either initialized randomly or set to real data points on the plane. Let’s start with k=3, as the data “seems” to be falling into three groups (we will get back to this “seems” word later in the post). For explanation-related purposes, lets randomly initialize the values (i.e. positions) of the averages:"
},
{
"code": null,
"e": 5990,
"s": 5751,
"text": "Now, the algorithm goes through the data points one-by-one, measuring the distance between each point and the three centroids (A, B and C). The algorithm then groups the the data point with the closest centroid (i.e. closest in distance)."
},
{
"code": null,
"e": 6122,
"s": 5990,
"text": "For instance, data point number 21 will belong to group A in the green color, merely because it’s closer in distance to centroid A:"
},
{
"code": null,
"e": 6386,
"s": 6122,
"text": "As soon as we’re done associating each data point with its closest centroid, we re-calculate the means — the values of the centroids; the new value of a centroid is the sum of all the points belonging to that centroid divided by the number of points in the group."
},
{
"code": null,
"e": 6604,
"s": 6386,
"text": "We keep doing the above until no centroid changes its value in re-calculation. This means that each centroid has centered itself in the middle of its cluster, which is surrounded by its own circular decision boundary:"
},
{
"code": null,
"e": 6761,
"s": 6604,
"text": "Let’s take another example, but from a different perspective this time. Let’s say we have the following set of points that we want to cluster into 3 groups:"
},
{
"code": null,
"e": 7231,
"s": 6761,
"text": "This data is not put in a visually-appealing manner. We just have a set of points that we want to cluster. Another important note is that the values in the circles symbolizing those data points are actual values of the points. They’re not put a way of showing the sequence of data like our previous example. Rather, these values are a quantification of some feature value F. I put them this way to make it easier on you to understand how the calculation of means works."
},
{
"code": null,
"e": 7265,
"s": 7231,
"text": "Let’s prepare our empty clusters:"
},
{
"code": null,
"e": 7346,
"s": 7265,
"text": "Think of these clusters as just bags that will contain points from our data set."
},
{
"code": null,
"e": 7403,
"s": 7346,
"text": "Let’s initialize the U values (i.e. means/centroids) to:"
},
{
"code": null,
"e": 7424,
"s": 7403,
"text": "U1 = 6U2 = 12U3 = 18"
},
{
"code": null,
"e": 7560,
"s": 7424,
"text": "These values can be random, but for simplicity reasons, they were chosen to be uniformly scattered along the data space (1 through 24)."
},
{
"code": null,
"e": 7745,
"s": 7560,
"text": "Since we already have our means, we can start calculating distances between any point whose feature F value is F and the three means (U1, U2 & U3), where the absolute distance follows:"
},
{
"code": null,
"e": 7767,
"s": 7745,
"text": "distance = | F - U | "
},
{
"code": null,
"e": 7836,
"s": 7767,
"text": "For starters, let’s take the data point whose feature F value is 20:"
},
{
"code": null,
"e": 7912,
"s": 7836,
"text": "|20 - U1| = |20 - 6| = 14|20 - U2| = |20 - 12| = 8|20 - U3| = |20 - 18| = 2"
},
{
"code": null,
"e": 8099,
"s": 7912,
"text": "According to the above calculations, the data point whose value is 20 is closer in distance to mean U3. Therefore, we “label” the point as U3 by putting it in its respective cluster/bag:"
},
{
"code": null,
"e": 8143,
"s": 8099,
"text": "And the same goes for all the other points:"
},
{
"code": null,
"e": 8216,
"s": 8143,
"text": "|3 - U1| = |20 - 6| = 3|3 - U2| = |20 - 12| = 9|3 - U3| = |20 - 18| = 15"
},
{
"code": null,
"e": 8292,
"s": 8216,
"text": "And so on, until we have all our data points in their appropriate clusters:"
},
{
"code": null,
"e": 8379,
"s": 8292,
"text": "Following the algorithm, we now need to re-calculate the means (U1, U2 as well as U3):"
},
{
"code": null,
"e": 8469,
"s": 8379,
"text": "U1 = (3+8+1+3+7+5+2+3+8) / 9 = 4.44U2 = (9+10+14+9) / 4 = 10.5U3 = (20+24+23) / 3 = 22.33"
},
{
"code": null,
"e": 8781,
"s": 8469,
"text": "Upon the beginning of our execution, our U values were 6, 12, and 18, respectively. Now, after the first iteration, the values became 4.44, 10.5 and 22.33, respectively. We now have to go through the distance calculation step again, but with the new mean values. We empty out our bags/clusters, and start again:"
},
{
"code": null,
"e": 8907,
"s": 8781,
"text": "Let’s start with a random point this time, say, the point whose feature F value is 8. The distance calculations would follow:"
},
{
"code": null,
"e": 8993,
"s": 8907,
"text": "|8 - U1| = |8 - 4.44| = 3.56|8 - U2| = |8 - 10.5| = 2.5|8 - U3| = |8 - 22.33| = 14.33"
},
{
"code": null,
"e": 9243,
"s": 8993,
"text": "So, the data point with the value 8 belongs to the cluster of mean value U2, as it’s is closest to it in distance. If you still recall, the same data point (8) belonged to U1 in the first run. This makes it evident how important the mean values are."
},
{
"code": null,
"e": 9426,
"s": 9243,
"text": "Running the algorithm over and over again until the mean values don’t change upon calculation will reach the following formation, with mean values 2.83, 9.29 and 22.33, respectively:"
},
{
"code": null,
"e": 10066,
"s": 9426,
"text": "As you’ve seen in our second example, the mean values we operate with at any given point are of great importance to the reliability of the model. This does not exclude the initial values. In fact, with really bad starting positions, the algorithm could get the clustering completely wrong! Therefore, another initialization approach would be to choose our initial k positions from the data set itself, setting one of the points as a mean value in its own surroundings. Either way, it is common practice to run the algorithm on the same data set repeatedly until we find a most common solution and clustering formation — and we stick to it."
},
{
"code": null,
"e": 10551,
"s": 10066,
"text": "Remember the stage at which we said that data “seems” to have been partitioned into three? Well, that was only to show the importance of the human eye in such applications. Since we don’t have a ground truth error estimation (as it usually requires labels), we need another measure for the hyper-parameters. For a lot of applications, a person looking at the plot and determining the k value is sufficient. However, this does not overestimate the importance of the k value in any way."
}
] |
HSQLDB - Quick Guide | HyperSQL Database (HSQLDB) is a modern relational database manager that conforms closely to the SQL:2011 standard and JDBC 4 specifications. It supports all core features and RDBMS. HSQLDB is used for development, testing, and deployment of database applications.
The main and unique feature of HSQLDB is Standard Compliance. It can provide database access within the user's application process, within an application server, or as a separate server process.
HSQLDB uses in-memory structure for fast operations against DB server. It uses disk persistence as per user flexibility, with a reliable crash recovery.
HSQLDB uses in-memory structure for fast operations against DB server. It uses disk persistence as per user flexibility, with a reliable crash recovery.
HSQLDB is also suitable for business intelligence, ETL, and other applications that process large data sets.
HSQLDB is also suitable for business intelligence, ETL, and other applications that process large data sets.
HSQLDB has a wide range of enterprise deployment options, such as XA transactions, connection pooling data sources, and remote authentication.
HSQLDB has a wide range of enterprise deployment options, such as XA transactions, connection pooling data sources, and remote authentication.
HSQLDB is written in the Java programming language and runs in a Java Virtual Machine (JVM). It supports the JDBC interface for database access.
HSQLDB is written in the Java programming language and runs in a Java Virtual Machine (JVM). It supports the JDBC interface for database access.
There are three different components in HSQLDB jar package.
HyperSQL RDBMS Engine (HSQLDB)
HyperSQL RDBMS Engine (HSQLDB)
HyperSQL JDBC Driver
HyperSQL JDBC Driver
Database Manager (GUI database access tool, with Swing and AWT versions)
Database Manager (GUI database access tool, with Swing and AWT versions)
HyperSQL RDBMS and JDBC Driver provide the core functionality. Database Managers are general-purpose database access tools that can be used with any database engine having a JDBC driver.
An additional jar called sqltool.jar, contains Sql Tool, which is a command line database access tool. This is a general purpose command. Line database access tool that can be used with other database engines as well.
HSQLDB is a relational database management system implemented in pure Java. You can easily embed this database to your application using JDBC. Or you can use the operations separately.
Follow the prerequisite software installations for HSQLDB.
Since HSQLDB is a relational database management system implemented in pure Java, you must install JDK (Java Development Kit) software before installing HSQLDB. If you already have JDK installation in your system, then try the following command to verify the Java version.
java –version
If JDK is successfully installed in your system, you will get the following output.
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)
If you don’t have JDK installed in your system, then visit the following link to Install JDK.
Following are the steps to install HSQLDB.
Step 1 − Download HSQLDB bundle
Download the latest version of HSQLDB database from the following link https://sourceforge.net/projects/hsqldb/files/. Once you click the link, you will get the following screenshot.
Click HSQLDB and the download will start immediately. Finally, you will get the zip file named hsqldb-2.3.4.zip.
Step 2 − Extract the HSQLDB zip file
Extract the zip file and place it into the C:\ directory. After extraction, you will get a file structure as shown in the following screenshot.
Step 3 − Create a default database
There is no default database for HSQLDB, therefore, you need to create a database for HSQLDB. Let us create a properties file named server.properties which defines a new database named demodb. Take a look at the following database server properties.
server.database.0 = file:hsqldb/demodb
server.dbname.0 = testdb
Place this server.properties file into HSQLDB home directory that is C:\hsqldb- 2.3.4\hsqldb\.
Now execute the following command on command prompt.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server
After execution of the above command, you will receive the server status as shown in the following screenshot.
Later, you will get to find the following folder structure of the hsqldb directory in the HSQLDB home directory that is C:\hsqldb-2.3.4\hsqldb. Those files are temp file, lck file, log file, properties file, and script file of demodb database created by HSQLDB database server.
Step 4 − Start the database server
Once you are done creating a database, you have to start the database by using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
After execution of the above command, you get the following status.
Now, you can open the database home screen that is runManagerSwing.bat from C:\hsqldb-2.3.4\hsqldb\bin location. This bat file will open the GUI file for HSQLDB database. Before that it will ask you for database settings through a dialog box. Take a look at the following screenshot. In this dialog box, enter the Setting Name, URL as shown above and click Ok.
You will get the GUI screen of HSQLDB database as shown in the following screenshot.
In the installation chapter, we discussed how to connect the database manually. In this chapter, we will discuss how to connect the database programmatically (using Java programming).
Take a look at the following program, which will start the server and create a connection between the Java application and the database.
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectDatabase {
public static void main(String[] args) {
Connection con = null;
try {
//Registering the HSQLDB JDBC driver
Class.forName("org.hsqldb.jdbc.JDBCDriver");
//Creating the connection with HSQLDB
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
if (con!= null){
System.out.println("Connection created successfully");
}else{
System.out.println("Problem with creating connection");
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
Save this code into ConnectDatabase.java file. You will have to start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
You can use the following command to compile and execute the code.
\>javac ConnectDatabase.java
\>java ConnectDatabase
After execution of the above command, you will receive the following output −
Connection created successfully
This chapter explains the different datatypes of HSQLDB. HSQLDB server offers six categories of data types.
Note − Here, datetime has 3.33 milliseconds accuracy whereas small datetime has 1- minute accuracy.
The basic mandatory requirements to create a table are table name, field names, and the data types to those fields. Optionally, you can also provide the key constraints to the table.
Take a look at the following syntax.
CREATE TABLE table_name (column_name column_type);
Let us create a table named tutorials_tbl with the field-names such as id, title, author, and submission_date. Take a look at the following query.
CREATE TABLE tutorials_tbl (
id INT NOT NULL,
title VARCHAR(50) NOT NULL,
author VARCHAR(20) NOT NULL,
submission_date DATE,
PRIMARY KEY (id)
);
After execution of the above query, you will receive the following output −
(0) rows effected
Following is the JDBC program used to create a table named tutorials_tbl into the HSQLDB database. Save the program into CreateTable.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class CreateTable {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
int result = 0;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeUpdate("CREATE TABLE tutorials_tbl (
id INT NOT NULL, title VARCHAR(50) NOT NULL,
author VARCHAR(20) NOT NULL, submission_date DATE,
PRIMARY KEY (id));
");
} catch (Exception e) {
e.printStackTrace(System.out);
}
System.out.println("Table created successfully");
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above program using the following command.
\>javac CreateTable.java
\>java CreateTable
After execution of the above command, you will receive the following output −
Table created successfully
It is very easy to drop an existing HSQLDB table. However, you need to be very careful while deleting any existing table as any data lost will not be recovered after deleting a table.
Following is a generic SQL syntax to drop a HSQLDB table.
DROP TABLE table_name;
Let us consider an example to drop a table named employee from the HSQLDB server. Following is the query to drop a table named employee.
DROP TABLE employee;
After execution of the above query, you will receive the following output −
(0) rows effected
Following is the JDBC program used to drop the table employee from the HSQLDB server.
Save the following code into DropTable.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DropTable {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
int result = 0;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeUpdate("DROP TABLE employee");
}catch (Exception e) {
e.printStackTrace(System.out);
}
System.out.println("Table dropped successfully");
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above program using the following command.
\>javac DropTable.java
\>java DropTable
After execution of the above command, you will receive the following output −
Table dropped successfully
You can achieve Insert query statement in HSQLDB by using the INSERT INTO command. You have to provide the user-defined data following the column field order from the table.
Following is the generic syntax to INSERT a query.
INSERT INTO table_name (field1, field2,...fieldN)
VALUES (value1, value2,...valueN );
To insert a string type data into a table, you will have to use double or single quotes to provide string value into the insert query statement.
Let us consider an example that inserts a record into a table named tutorials_tbl with the values id = 100, title = Learn PHP, Author = John Poul, and the submission date is current date.
Following is the query for the given example.
INSERT INTO tutorials_tbl VALUES (100,'Learn PHP', 'John Poul', NOW());
After execution of the above query, you will receive the following output −
1 row effected
Here is the JDBC program to insert the record into the table with the given values, id =100, title = Learn PHP, Author = John Poul, and the submission date is current date. Take a look at the given program. Save the code into the InserQuery.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class InsertQuery {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
int result = 0;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeUpdate("INSERT INTO tutorials_tbl
VALUES (100,'Learn PHP', 'John Poul', NOW())");
con.commit();
}catch (Exception e) {
e.printStackTrace(System.out);
}
System.out.println(result+" rows effected");
System.out.println("Rows inserted successfully");
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above program using the following command.
\>javac InsertQuery.java
\>java InsertQuery
After execution of the above command, you will receive the following output −
1 rows effected
Rows inserted successfully
Try to insert the following records into the tutorials_tbl table by using the INSERT INTO command.
The SELECT command is used to fetch the record data from HSQLDB database. Here, you need to mention the required fields list in the Select statement.
Here is the generic syntax for Select query.
SELECT field1, field2,...fieldN table_name1, table_name2...
[WHERE Clause]
[OFFSET M ][LIMIT N]
You can fetch one or more fields in a single SELECT command.
You can fetch one or more fields in a single SELECT command.
You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
You can specify any condition using WHERE clause.
You can specify any condition using WHERE clause.
You can specify an offset using OFFSET from where SELECT will start returning records. By default, offset is zero.
You can specify an offset using OFFSET from where SELECT will start returning records. By default, offset is zero.
You can limit the number of returns using LIMIT attribute.
You can limit the number of returns using LIMIT attribute.
Here is an example that fetches id, title, and author fields of all records from tutorials_tbl table. We can achieve this by using the SELECT statement. Following is the query for the example.
SELECT id, title, author FROM tutorials_tbl
After execution of the above query, you will receive the following output.
+------+----------------+-----------------+
| id | title | author |
+------+----------------+-----------------+
| 100 | Learn PHP | John Poul |
| 101 | Learn C | Yaswanth |
| 102 | Learn MySQL | Abdul S |
| 103 | Learn Excell | Bavya kanna |
| 104 | Learn JDB | Ajith kumar |
| 105 | Learn Junit | Sathya Murthi |
+------+----------------+-----------------+
Here is the JDBC program that will fetch id, title, and author fields of all records from tutorials_tbl table. Save the following code into the SelectQuery.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SelectQuery {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet result = null;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeQuery(
"SELECT id, title, author FROM tutorials_tbl");
while(result.next()){
System.out.println(result.getInt("id")+" | "+
result.getString("title")+" | "+
result.getString("author"));
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above code using the following command.
\>javac SelectQuery.java
\>java SelectQuery
After execution of the above command, you will receive the following output −
100 | Learn PHP | John Poul
101 | Learn C | Yaswanth
102 | Learn MySQL | Abdul S
103 | Learn Excell | Bavya Kanna
104 | Learn JDB | Ajith kumar
105 | Learn Junit | Sathya Murthi
Generally, we use SELECT command to fetch data from HSQLDB table. We can use WHERE conditional clause to filter the resultant data. Using WHERE we can specify the selection criteria to select the required records from a table.
Following is the syntax of SELECT command WHERE clause to fetch data from HSQLDB table.
SELECT field1, field2,...fieldN table_name1, table_name2...
[WHERE condition1 [AND [OR]] condition2.....
You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command.
You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command.
You can specify any condition using WHERE clause.
You can specify any condition using WHERE clause.
You can specify more than one conditions using AND or OR operators.
You can specify more than one conditions using AND or OR operators.
A WHERE clause can also be used along with DELETE or UPDATE SQL command to specify a condition.
A WHERE clause can also be used along with DELETE or UPDATE SQL command to specify a condition.
We can filter the record data by using conditions. We are using different operators in conditional WHERE clause. Here is the list of operators, which can be used with WHERE clause.
Here is an example that retrieves the details such as id, title, and the author of the book titled "Learn C". It is possible by using WHERE clause in the SELECT command. Following is the query for the same.
SELECT id, title, author FROM tutorials_tbl WHERE title = 'Learn C';
After execution of the above query, you will receive the following output.
+------+----------------+-----------------+
| id | title | author |
+------+----------------+-----------------+
| 101 | Learn C | Yaswanth |
+------+----------------+-----------------+
Here is the JDBC program that retrieves the record data from the table tutorials_tblhaving the title Learn C. Save the following code into WhereClause.java.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class WhereClause {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet result = null;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeQuery(
"SELECT id, title, author FROM tutorials_tbl
WHERE title = 'Learn C'");
while(result.next()){
System.out.println(result.getInt("id")+" |
"+result.getString("title")+" |
"+result.getString("author"));
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above code using the following command.
\>javac WhereClause.java
\>java WhereClause
After execution of the above command, you will receive the following output.
101 | Learn C | Yaswanth
Whenever you want to modify the values of a table, you can use the UPDATE command. This will modify any field value from any HSQLDB table.
Here is the generic syntax for UPDATE command.
UPDATE table_name SET field1 = new-value1, field2 = new-value2 [WHERE Clause]
You can update one or more field altogether.
You can specify any condition using WHERE clause.
You can update values in a single table at a time.
Let us consider an example that updates the title of the tutorial from "Learn C" to "C and Data Structures" having an id "101". Following is the query for the update.
UPDATE tutorials_tbl SET title = 'C and Data Structures' WHERE id = 101;
After execution of the above query, you will receive the following output.
(1) Rows effected
Here is the JDBC program that will update a tutorial title from Learn C to C and Data Structures having an id 101. Save the following program into the UpdateQuery.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class UpdateQuery {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
int result = 0;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeUpdate(
"UPDATE tutorials_tbl SET title = 'C and Data Structures' WHERE id = 101");
} catch (Exception e) {
e.printStackTrace(System.out);
}
System.out.println(result+" Rows effected");
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above program using the following command.
\>javac UpdateQuery.java
\>java UpdateQuery
After execution of the above command, you will receive the following output −
1 Rows effected
Whenever you want to delete a record from any HSQLDB table, you can use the DELETE FROM command.
Here is the generic syntax for DELETE command to delete data from a HSQLDB table.
DELETE FROM table_name [WHERE Clause]
If WHERE clause is not specified, then all the records will be deleted from the given MySQL table.
If WHERE clause is not specified, then all the records will be deleted from the given MySQL table.
You can specify any condition using WHERE clause.
You can specify any condition using WHERE clause.
You can delete records in a single table at a time.
You can delete records in a single table at a time.
Let us consider an example that deletes the record data from the table named tutorials_tbl having id 105. Following is the query that implements the given example.
DELETE FROM tutorials_tbl WHERE id = 105;
After execution of the above query, you will receive the following output −
(1) rows effected
Here is the JDBC program that implements the given example. Save the following program into DeleteQuery.java.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DeleteQuery {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
int result = 0;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeUpdate(
"DELETE FROM tutorials_tbl WHERE id=105");
} catch (Exception e) {
e.printStackTrace(System.out);
}
System.out.println(result+" Rows effected");
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above program using the following command.
\>javac DeleteQuery.java
\>java DeleteQuery
After execution of the above command, you will receive the following output −
1 Rows effected
There is a WHERE clause in the RDBMS structure. You can use the WHERE clause with an equal to sign (=) where we want to do an exact match. But there may be a requirement where we want to filter out all the results where the author name should contain "john". This can be handled using the SQL LIKE clause along with the WHERE clause.
If the SQL LIKE clause is used along with % characters, then it will work like a metacharacter (*) in UNIX while listing out all the files or directories at command prompt.
Following is the generic SQL syntax of the LIKE clause.
SELECT field1, field2,...fieldN table_name1, table_name2...
WHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'
You can specify any condition using the WHERE clause.
You can specify any condition using the WHERE clause.
You can use the LIKE clause along with the WHERE clause.
You can use the LIKE clause along with the WHERE clause.
You can use the LIKE clause in place of the equal to sign.
You can use the LIKE clause in place of the equal to sign.
When the LIKE clause is used along with the % sign, then it will work like a metacharacter search.
When the LIKE clause is used along with the % sign, then it will work like a metacharacter search.
You can specify more than one conditions using AND or OR operators.
You can specify more than one conditions using AND or OR operators.
A WHERE...LIKE clause can be used along with the DELETE or the UPDATE SQL command to specify a condition.
A WHERE...LIKE clause can be used along with the DELETE or the UPDATE SQL command to specify a condition.
Let us consider an example that retrieves the list of tutorials data where the author name starts with John. Following is the HSQLDB query for the given example.
SELECT * from tutorials_tbl WHERE author LIKE 'John%';
After execution of the above query, you will receive the following output.
+-----+----------------+-----------+-----------------+
| id | title | author | submission_date |
+-----+----------------+-----------+-----------------+
| 100 | Learn PHP | John Poul | 2016-06-20 |
+-----+----------------+-----------+-----------------+
Following is the JDBC program that retrieves the list of tutorials data where the author name starts with John. Save the code into LikeClause.java.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class LikeClause {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet result = null;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeQuery(
"SELECT * from tutorials_tbl WHERE author LIKE 'John%';");
while(result.next()){
System.out.println(result.getInt("id")+" |
"+result.getString("title")+" |
"+result.getString("author")+" |
"+result.getDate("submission_date"));
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above code using the following command.
\>javac LikeClause.java
\>java LikeClause
After execution of the following command, you will receive the following output.
100 | Learn PHP | John Poul | 2016-06-20
The SQL SELECT command fetches data from the HSQLDB table whenever there is a requirement that follows a particular order while retrieving and displaying records. In that case, we can use the ORDER BY clause.
Here is the syntax of the SELECT command along with ORDER BY clause to sort data from HSQLDB.
SELECT field1, field2,...fieldN table_name1, table_name2...
ORDER BY field1, [field2...] [ASC [DESC]]
You can sort the returned result on any field provided that field is being listed out.
You can sort the returned result on any field provided that field is being listed out.
You can sort the result on more than one field.
You can sort the result on more than one field.
You can use the keyword ASC or DESC to get the result in an ascending or descending order. By default, it's in an ascending order.
You can use the keyword ASC or DESC to get the result in an ascending or descending order. By default, it's in an ascending order.
You can use the WHERE...LIKE clause in a usual way to put a condition.
You can use the WHERE...LIKE clause in a usual way to put a condition.
Let us consider an example that fetches and sorts the records of tutorials_tbl table by ordering the author name in an ascending order. Following is the query for the same.
SELECT id, title, author from tutorials_tbl ORDER BY author ASC;
After execution of the above query, you will receive the following output.
+------+----------------+-----------------+
| id | title | author |
+------+----------------+-----------------+
| 102 | Learn MySQL | Abdul S |
| 104 | Learn JDB | Ajith kumar |
| 103 | Learn Excell | Bavya kanna |
| 100 | Learn PHP | John Poul |
| 105 | Learn Junit | Sathya Murthi |
| 101 | Learn C | Yaswanth |
+------+----------------+-----------------+
Here is the JDBC program that fetches and sorts the records of tutorials_tbl table by ordering the author name in an ascending order. Save the following program into OrderBy.java.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class OrderBy {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet result = null;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeQuery(
"SELECT id, title, author from tutorials_tbl
ORDER BY author ASC");
while(result.next()){
System.out.println(result.getInt("id")+" |
"+result.getString("title")+" |
"+result.getString("author"));
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above program using the following command.
\>javac OrderBy.java
\>java OrderBy
After execution of the above command, you will receive the following output.
102 | Learn MySQL | Abdul S
104 | Learn JDB | Ajith kumar
103 | Learn Excell | Bavya Kanna
100 | Learn PHP | John Poul
105 | Learn Junit | Sathya Murthi
101 | C and Data Structures | Yaswanth
Whenever there is a requirement to retrieve data from multiple tables using a single query, you can use JOINS from RDBMS. You can use multiple tables in your single SQL query. The act of joining in HSQLDB refers to smashing two or more tables into a single table.
Consider the following Customers and Orders tables.
Customer:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Orders:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us try to retrieve the data of the customers and the order amount that the respective customer placed. This means we are retrieving the record data from both customers and orders table. We can achieve this by using the JOINS concept in HSQLDB. Following is the JOIN query for the same.
SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;
After execution of the above query, you will receive the following output.
+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
There are different types of joins available in HSQLDB.
INNER JOIN − Returns the rows when there is a match in both tables.
INNER JOIN − Returns the rows when there is a match in both tables.
LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table.
LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table.
RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN − Returns the rows when there is a match in one of the tables.
FULL JOIN − Returns the rows when there is a match in one of the tables.
SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
The most frequently used and important of the joins is the INNER JOIN. It is also referred to as an EQUIJOIN.
The INNER JOIN creates a new result table by combining the column values of two tables (table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows, which satisfy the join-predicate. When the join-predicate is satisfied, the column values for each matched pair of rows A and B are combined into a result row.
The basic syntax of INNER JOIN is as follows.
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
| OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using INNER JOIN query as follows −
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
After execution of the above query, you will receive the following output.
+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+----+----------+--------+---------------------+
The HSQLDB LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table, the join will still return a row in the result, but with NULL in each column from the right table.
This means that a left join returns all the values from the left table, plus matched values from the right table or NULL in case of no matching join predicate.
The basic syntax of LEFT JOIN is as follows −
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Here the given condition could be any given expression based on your requirement.
Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
| OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using the LEFT JOIN query as follows −
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
After execution of the above query, you will receive the following output −
+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+----+----------+--------+---------------------+
The HSQLDB RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table. This means that if the ON clause matches 0 (zero) records in the left table, the join will still return a row in the result, but with NULL in each column from the left table.
This means that a right join returns all the values from the right table, plus matched values from the left table or NULL in case of no matching join predicate.
The basic syntax of RIGHT JOIN is as follows −
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
| OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using the RIGHT JOIN query as follows −
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
After execution of the above query, you will receive the following result.
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
The HSQLDB FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for the missing matches on either side.
The basic syntax of FULL JOIN is as follows −
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Here the given condition could be any given expression based on your requirement.
Consider the following two tables, one titled as CUSTOMERS table and another titled as
ORDERS table as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
| OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using the FULL JOIN query as follows −
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
FULL JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
After execution of the above query, you will receive the following result.
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
The basic syntax of SELF JOIN is as follows −
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;
Here, the WHERE clause could be any given expression based on your requirement.
Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us join this table using the SELF JOIN query as follows −
SELECT a.ID, b.NAME, a.SALARY FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY > b.SALARY;
After execution of the above query, you will receive the following output −
+----+----------+---------+
| ID | NAME | SALARY |
+----+----------+---------+
| 2 | Ramesh | 1500.00 |
| 2 | kaushik | 1500.00 |
| 1 | Chaitali | 2000.00 |
| 2 | Chaitali | 1500.00 |
| 3 | Chaitali | 2000.00 |
| 6 | Chaitali | 4500.00 |
| 1 | Hardik | 2000.00 |
| 2 | Hardik | 1500.00 |
| 3 | Hardik | 2000.00 |
| 4 | Hardik | 6500.00 |
| 6 | Hardik | 4500.00 |
| 1 | Komal | 2000.00 |
| 2 | Komal | 1500.00 |
| 3 | Komal | 2000.00 |
| 1 | Muffy | 2000.00 |
| 2 | Muffy | 1500.00 |
| 3 | Muffy | 2000.00 |
| 4 | Muffy | 6500.00 |
| 5 | Muffy | 8500.00 |
| 6 | Muffy | 4500.00 |
+----+----------+---------+
SQL NULL is a term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank. Whenever we try to give a condition, which compare the field or column value to NULL, it does not work properly.
We can handle the NULL values by using the three things.
IS NULL − The operator returns true if the column value is NULL.
IS NULL − The operator returns true if the column value is NULL.
IS NOT NULL − The operator returns true if the column value is NOT NULL.
IS NOT NULL − The operator returns true if the column value is NOT NULL.
<=> − The operator compares values, which (unlike the = operator) is true even for two NULL values.
<=> − The operator compares values, which (unlike the = operator) is true even for two NULL values.
To look for columns that are NULL or NOT NULL, use IS NULL or IS NOT NULL respectively.
Let us consider an example where there is a table tcount_tbl that contains two columns, author and tutorial_count. We can provide NULL values to the tutorial_count indicates that the author did not publish even one tutorial. Therefore, the tutorial_count value for that respective author is NULL.
Execute the following queries.
create table tcount_tbl(author varchar(40) NOT NULL, tutorial_count INT);
INSERT INTO tcount_tbl values ('Abdul S', 20);
INSERT INTO tcount_tbl values ('Ajith kumar', 5);
INSERT INTO tcount_tbl values ('Jen', NULL);
INSERT INTO tcount_tbl values ('Bavya kanna', 8);
INSERT INTO tcount_tbl values ('mahran', NULL);
INSERT INTO tcount_tbl values ('John Poul', 10);
INSERT INTO tcount_tbl values ('Sathya Murthi', 6);
Use the following command to display all the records from the tcount_tbl table.
select * from tcount_tbl;
After execution of the above command, you will receive the following output.
+-----------------+----------------+
| author | tutorial_count |
+-----------------+----------------+
| Abdul S | 20 |
| Ajith kumar | 5 |
| Jen | NULL |
| Bavya kanna | 8 |
| mahran | NULL |
| John Poul | 10 |
| Sathya Murthi | 6 |
+-----------------+----------------+
To find the records where the tutorial_count column IS NULL, following is the query.
SELECT * FROM tcount_tbl WHERE tutorial_count IS NULL;
After execution of the query, you will receive the following output.
+-----------------+----------------+
| author | tutorial_count |
+-----------------+----------------+
| Jen | NULL |
| mahran | NULL |
+-----------------+----------------+
To find the records where the tutorial_count column IS NOT NULL, following is the query.
SELECT * FROM tcount_tbl WHERE tutorial_count IS NOT NULL;
After execution of the query, you will receive the following output.
+-----------------+----------------+
| author | tutorial_count |
+-----------------+----------------+
| Abdul S | 20 |
| Ajith kumar | 5 |
| Bavya kanna | 8 |
| John Poul | 10 |
| Sathya Murthi | 6 |
+-----------------+----------------+
Here is the JDBC program that retrieves the records separately from the table tcount_tbl where the tutorial_ count is NULL and the tutorial_count is NOT NULL. Save the following program into NullValues.java.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class NullValues {
public static void main(String[] args) {
Connection con = null;
Statement stmt_is_null = null;
Statement stmt_is_not_null = null;
ResultSet result = null;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt_is_null = con.createStatement();
stmt_is_not_null = con.createStatement();
result = stmt_is_null.executeQuery(
"SELECT * FROM tcount_tbl WHERE tutorial_count IS NULL;");
System.out.println("Records where the tutorial_count is NULL");
while(result.next()){
System.out.println(result.getString("author")+" |
"+result.getInt("tutorial_count"));
}
result = stmt_is_not_null.executeQuery(
"SELECT * FROM tcount_tbl WHERE tutorial_count IS NOT NULL;");
System.out.println("Records where the tutorial_count is NOT NULL");
while(result.next()){
System.out.println(result.getString("author")+" |
"+result.getInt("tutorial_count"));
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
Compile and execute the above program using the following command.
\>javac NullValues.java
\>Java NullValues
After execution of the above command, you will receive the following output.
Records where the tutorial_count is NULL
Jen | 0
mahran | 0
Records where the tutorial_count is NOT NULL
Abdul S | 20
Ajith kumar | 5
Bavya kanna | 8
John Poul | 10
Sathya Murthi | 6
HSQLDB supports some special symbols for pattern matching operation based on regular expressions and the REGEXP operator.
Following is the table of pattern, which can be used along with REGEXP operator.
Let us try different example queries to meet our requirements. Take a look at the following given queries.
Try this Query to find all the authors whose name starts with '^A'.
SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'^A.*');
After execution of the above query, you will receive the following output.
+-----------------+
| author |
+-----------------+
| Abdul S |
| Ajith kumar |
+-----------------+
Try this Query to find all the authors whose name ends with 'ul$'.
SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'.*ul$');
After execution of the above query, you will receive the following output.
+-----------------+
| author |
+-----------------+
| John Poul |
+-----------------+
Try this Query to find all the authors whose name contains 'th'.
SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'.*th.*');
After execution of the above query, you will receive the following output.
+-----------------+
| author |
+-----------------+
| Ajith kumar |
| Abdul S |
+-----------------+
Try this query to find all the authors whose name starts with vowel (a, e, i, o, u).
SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'^[AEIOU].*');
After execution of the above query, you will receive the following output.
+-----------------+
| author |
+-----------------+
| Abdul S |
| Ajith kumar |
+-----------------+
A Transaction is a sequential group of database manipulation operations, which is performed and considered as one single work unit. In other words, when all the operations are successfully executed, only then the entire transaction will be complete. If any operation within the transaction fails, then the entire transaction will fail.
Basically, transaction supports 4 standard properties. They can be referred to as ACID properties.
Atomicity − All the operations in the transactions are executed successfully, otherwise the transaction gets aborted at the point of failure and the previous operations are rolled back to their previous position.
Consistency − The database properly changes states upon a successfully committed transaction.
Isolation − It enables the transaction to operate independently on and transparent to each other.
Durability − The result or effect of a committed transaction persists in case of a system failure.
These keywords are mainly used for HSQLDB transactions.
Commit− Always the successful transaction should be completed by executing the COMMIT command.
Rollback − If a failure occurs in the transaction, then the ROLLBACK command should be executed to return every table referenced in the transaction to its previous state.
Savepoint − Creates a point within the group of transactions in which to rollback.
The following example explains the transactions concept along with commit, rollback, and Savepoint. Let us consider the table Customers with the columns id, name, age, address, and salary.
Use the following commands to create the customer table along the lines of the above data.
CREATE TABLE Customer (id INT NOT NULL, name VARCHAR(100) NOT NULL, age INT NOT
NULL, address VARCHAR(20), Salary INT, PRIMARY KEY (id));
Insert into Customer values (1, "Ramesh", 32, "Ahmedabad", 2000);
Insert into Customer values (2, "Karun", 25, "Delhi", 1500);
Insert into Customer values (3, "Kaushik", 23, "Kota", 2000);
Insert into Customer values (4, "Chaitanya", 25, "Mumbai", 6500);
Insert into Customer values (5, "Harish", 27, "Bhopal", 8500);
Insert into Customer values (6, "Kamesh", 22, "MP", 1500);
Insert into Customer values (7, "Murali", 24, "Indore", 10000);
The following query deletes rows from the table having age = 25 and uses the COMMIT command to apply those changes in the database.
DELETE FROM CUSTOMERS WHERE AGE = 25;
COMMIT;
After execution of the above query, you will receive the following output.
2 rows effected
After successful execution of the above command, check the records of the customer table by executing the below given command.
Select * from Customer;
After execution of the above query, you will receive the following output.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000 |
| 3 | kaushik | 23 | Kota | 2000 |
| 5 | Harish | 27 | Bhopal | 8500 |
| 6 | Kamesh | 22 | MP | 4500 |
| 7 | Murali | 24 | Indore | 10000 |
+----+----------+-----+-----------+----------+
Let us consider the same Customer table as input.
Here is the example query that explains about Rollback functionality by deleting records from the table having age = 25 and then ROLLBACK the changes in the database.
DELETE FROM CUSTOMERS WHERE AGE = 25;
ROLLBACK;
After successful execution of the above two queries, you can view the record data in the Customer table using the following command.
Select * from Customer;
After execution of the above command, you will receive the following output.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000 |
| 2 | Karun | 25 | Delhi | 1500 |
| 3 | Kaushik | 23 | Kota | 2000 |
| 4 | Chaitanya| 25 | Mumbai | 6500 |
| 5 | Harish | 27 | Bhopal | 8500 |
| 6 | Kamesh | 22 | MP | 4500 |
| 7 | Murali | 24 | Indore | 10000 |
+----+----------+-----+-----------+----------+
The delete query deletes the record data of customers whose age = 25. The Rollback command, rolls back those changes on the Customer table.
Savepoint is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction.
Let us consider the same Customer table as input.
Let us consider in this example, you plan to delete the three different records from the Customers table. You want to create a Savepoint before each delete, so that you can roll back to any Savepoint at any time to return the appropriate data to its original state.
Here is the series of operations.
SAVEPOINT SP1;
DELETE FROM CUSTOMERS WHERE ID = 1;
SAVEPOINT SP2;
DELETE FROM CUSTOMERS WHERE ID = 2;
SAVEPOINT SP3;
DELETE FROM CUSTOMERS WHERE ID = 3;
Now, you have created three Savepoint and deleted three records. In this situation, if you want to roll back the records having Id 2 and 3 then use the following Rollback command.
ROLLBACK TO SP2;
Notice that only the first deletion took place since you rolled back to SP2. Use the following query to display all the records of the customers.
Select * from Customer;
After execution of the above query, you will receive the following output.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Karun | 25 | Delhi | 1500 |
| 3 | Kaushik | 23 | Kota | 2000 |
| 4 | Chaitanya| 25 | Mumbai | 6500 |
| 5 | Harish | 27 | Bhopal | 8500 |
| 6 | Kamesh | 22 | MP | 4500 |
| 7 | Murali | 24 | Indore | 10000 |
+----+----------+-----+-----------+----------+
We can release the Savepoint using the RELEASE command. Following is the generic syntax.
RELEASE SAVEPOINT SAVEPOINT_NAME;
Whenever there is a need to change the name of a table or a field, change the order of fields, change the datatype of fields, or any table structure, you can achieve the same using the ALTER command.
Let us consider an example that explains the ALTER command using different scenarios.
Use the following query to create a table named testalter_tbl with the fields’ id and name.
//below given query is to create a table testalter_tbl table.
create table testalter_tbl(id INT, name VARCHAR(10));
//below given query is to verify the table structure testalter_tbl.
Select * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =
'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';
After execution of the above query, you will receive the following output.
+------------+-------------+------------+-----------+-----------+------------+
|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|
+------------+-------------+------------+-----------+-----------+------------+
| PUBLIC |TESTALTER_TBL| ID | 4 | INTEGER | 4 |
| PUBLIC |TESTALTER_TBL| NAME | 12 | VARCHAR | 10 |
+------------+-------------+------------+-----------+-----------+------------+
Whenever you want to DROP an existing column from the HSQLDB table, then you can use the DROP clause along with the ALTER command.
Use the following query to drop a column (name) from the table testalter_tbl.
ALTER TABLE testalter_tbl DROP name;
After successful execution of the above query, you can get to know if the name field is dropped from the table testalter_tbl using the following command.
Select * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =
'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';
After execution of the above command, you will receive the following output.
+------------+-------------+------------+-----------+-----------+------------+
|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|
+------------+-------------+------------+-----------+-----------+------------+
| PUBLIC |TESTALTER_TBL| ID | 4 | INTEGER | 4 |
+------------+-------------+------------+-----------+-----------+------------+
Whenever you want to add any column into the HSQLDB table, you can use the ADD clause along with the ALTER command.
Use the following query to add a column named NAME to the table testalter_tbl.
ALTER TABLE testalter_tbl ADD name VARCHAR(10);
After successful execution of the above query, you can get to know if the name field is added to the table testalter_tbl using the following command.
Select * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =
'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';
After execution of the above query, you will receive the following output.
+------------+-------------+------------+-----------+-----------+------------+
|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|
+------------+-------------+------------+-----------+-----------+------------+
| PUBLIC |TESTALTER_TBL| ID | 4 | INTEGER | 4 |
| PUBLIC |TESTALTER_TBL| NAME | 12 | VARCHAR | 10 |
+------------+-------------+------------+-----------+-----------+------------+
Whenever there is a requirement of changing the column definition, use the MODIFY or CHANGE clause along with the ALTER command.
Let us consider an example that will explain how to use the CHANGE clause. The table testalter_tbl contains two fields - id and name - having datatypes int and varchar respectively. Now let us try to change the datatype of id from INT to BIGINT. Following is the query to make the change.
ALTER TABLE testalter_tbl CHANGE id id BIGINT;
After successful execution of the above query, the table structure can be verified using the following command.
Select * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =
'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';
After execution of the above command, you will receive the following output.
+------------+-------------+------------+-----------+-----------+------------+
|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|
+------------+-------------+------------+-----------+-----------+------------+
| PUBLIC |TESTALTER_TBL| ID | 4 | BIGINT | 4 |
| PUBLIC |TESTALTER_TBL| NAME | 12 | VARCHAR | 10 |
+------------+-------------+------------+-----------+-----------+------------+
Now let us try to increase the size of a column NAME from 10 to 20 in the testalter_tbl table. Following is the query to achieve this using the MODIFY clause along with the ALTER command.
ALTER TABLE testalter_tbl MODIFY name VARCHAR(20);
After successful execution of the above query, the table structure can be verified using the following command.
Select * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =
'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';
After execution of the above command, you will receive the following output.
+------------+-------------+------------+-----------+-----------+------------+
|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|
+------------+-------------+------------+-----------+-----------+------------+
| PUBLIC |TESTALTER_TBL| ID | 4 | BIGINT | 4 |
| PUBLIC |TESTALTER_TBL| NAME | 12 | VARCHAR | 20 |
+------------+-------------+------------+-----------+-----------+------------+
A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to the records.
While creating an index, it should be considered what are the columns which will be used to make SQL queries, and create one or more indexes on those columns.
Practically, indexes are also type of tables, which keep the primary key or the index field and a pointer to each record into the actual table.
The users cannot see the indexes. They are just used to speed up queries and will be used by the Database Search Engine to quickly locate records.
The INSERT and UPDATE statements take more time on tables having indexes, whereas SELECT statements run faster on those tables. The reason being while inserting or updating, the database needs to insert or update the index values as well.
You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Following is the syntax to create an Index on a table.
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2,...);
You can use one or more columns to create an index. For example, create an index on tutorials_tbl using tutorial_author.
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author)
You can create a simple index on a table. Just omit the UNIQUE keyword from the query to create a simple index. A simple index allows duplicate values in a table.
If you want to index the values in a column in a descending order, you can add the reserved word DESC after the column name.
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author DESC)
There are four types of statements for adding indexes to a table −
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which the values must be unique (with the exception of NULL values, which may appear multiple times).
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which the values must be unique (with the exception of NULL values, which may appear multiple times).
ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once.
ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once.
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes.
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes.
Following is the query to add index in an existing table.
ALTER TABLE testalter_tbl ADD INDEX (c);
You can drop any INDEX by using the DROP clause along with the ALTER command. Following is the query to drop the above-created index.
ALTER TABLE testalter_tbl DROP INDEX (c);
You can use the SHOW INDEX command to list out all the indexes associated with a table. Vertical-format output (specified by \G) often is useful with this statement, to avoid long line wraparound.
Following is the generic syntax to display the index information about a table.
SHOW INDEX FROM table_name\G
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2246,
"s": 1982,
"text": "HyperSQL Database (HSQLDB) is a modern relational database manager that conforms closely to the SQL:2011 standard and JDBC 4 specifications. It supports all core features and RDBMS. HSQLDB is used for development, testing, and deployment of database applications."
},
{
"code": null,
"e": 2441,
"s": 2246,
"text": "The main and unique feature of HSQLDB is Standard Compliance. It can provide database access within the user's application process, within an application server, or as a separate server process."
},
{
"code": null,
"e": 2594,
"s": 2441,
"text": "HSQLDB uses in-memory structure for fast operations against DB server. It uses disk persistence as per user flexibility, with a reliable crash recovery."
},
{
"code": null,
"e": 2747,
"s": 2594,
"text": "HSQLDB uses in-memory structure for fast operations against DB server. It uses disk persistence as per user flexibility, with a reliable crash recovery."
},
{
"code": null,
"e": 2856,
"s": 2747,
"text": "HSQLDB is also suitable for business intelligence, ETL, and other applications that process large data sets."
},
{
"code": null,
"e": 2965,
"s": 2856,
"text": "HSQLDB is also suitable for business intelligence, ETL, and other applications that process large data sets."
},
{
"code": null,
"e": 3108,
"s": 2965,
"text": "HSQLDB has a wide range of enterprise deployment options, such as XA transactions, connection pooling data sources, and remote authentication."
},
{
"code": null,
"e": 3251,
"s": 3108,
"text": "HSQLDB has a wide range of enterprise deployment options, such as XA transactions, connection pooling data sources, and remote authentication."
},
{
"code": null,
"e": 3396,
"s": 3251,
"text": "HSQLDB is written in the Java programming language and runs in a Java Virtual Machine (JVM). It supports the JDBC interface for database access."
},
{
"code": null,
"e": 3541,
"s": 3396,
"text": "HSQLDB is written in the Java programming language and runs in a Java Virtual Machine (JVM). It supports the JDBC interface for database access."
},
{
"code": null,
"e": 3601,
"s": 3541,
"text": "There are three different components in HSQLDB jar package."
},
{
"code": null,
"e": 3632,
"s": 3601,
"text": "HyperSQL RDBMS Engine (HSQLDB)"
},
{
"code": null,
"e": 3663,
"s": 3632,
"text": "HyperSQL RDBMS Engine (HSQLDB)"
},
{
"code": null,
"e": 3684,
"s": 3663,
"text": "HyperSQL JDBC Driver"
},
{
"code": null,
"e": 3705,
"s": 3684,
"text": "HyperSQL JDBC Driver"
},
{
"code": null,
"e": 3778,
"s": 3705,
"text": "Database Manager (GUI database access tool, with Swing and AWT versions)"
},
{
"code": null,
"e": 3851,
"s": 3778,
"text": "Database Manager (GUI database access tool, with Swing and AWT versions)"
},
{
"code": null,
"e": 4038,
"s": 3851,
"text": "HyperSQL RDBMS and JDBC Driver provide the core functionality. Database Managers are general-purpose database access tools that can be used with any database engine having a JDBC driver."
},
{
"code": null,
"e": 4256,
"s": 4038,
"text": "An additional jar called sqltool.jar, contains Sql Tool, which is a command line database access tool. This is a general purpose command. Line database access tool that can be used with other database engines as well."
},
{
"code": null,
"e": 4441,
"s": 4256,
"text": "HSQLDB is a relational database management system implemented in pure Java. You can easily embed this database to your application using JDBC. Or you can use the operations separately."
},
{
"code": null,
"e": 4500,
"s": 4441,
"text": "Follow the prerequisite software installations for HSQLDB."
},
{
"code": null,
"e": 4773,
"s": 4500,
"text": "Since HSQLDB is a relational database management system implemented in pure Java, you must install JDK (Java Development Kit) software before installing HSQLDB. If you already have JDK installation in your system, then try the following command to verify the Java version."
},
{
"code": null,
"e": 4788,
"s": 4773,
"text": "java –version\n"
},
{
"code": null,
"e": 4872,
"s": 4788,
"text": "If JDK is successfully installed in your system, you will get the following output."
},
{
"code": null,
"e": 5014,
"s": 4872,
"text": "java version \"1.8.0_91\"\nJava(TM) SE Runtime Environment (build 1.8.0_91-b14)\nJava HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)\n"
},
{
"code": null,
"e": 5108,
"s": 5014,
"text": "If you don’t have JDK installed in your system, then visit the following link to Install JDK."
},
{
"code": null,
"e": 5151,
"s": 5108,
"text": "Following are the steps to install HSQLDB."
},
{
"code": null,
"e": 5183,
"s": 5151,
"text": "Step 1 − Download HSQLDB bundle"
},
{
"code": null,
"e": 5366,
"s": 5183,
"text": "Download the latest version of HSQLDB database from the following link https://sourceforge.net/projects/hsqldb/files/. Once you click the link, you will get the following screenshot."
},
{
"code": null,
"e": 5479,
"s": 5366,
"text": "Click HSQLDB and the download will start immediately. Finally, you will get the zip file named hsqldb-2.3.4.zip."
},
{
"code": null,
"e": 5516,
"s": 5479,
"text": "Step 2 − Extract the HSQLDB zip file"
},
{
"code": null,
"e": 5660,
"s": 5516,
"text": "Extract the zip file and place it into the C:\\ directory. After extraction, you will get a file structure as shown in the following screenshot."
},
{
"code": null,
"e": 5695,
"s": 5660,
"text": "Step 3 − Create a default database"
},
{
"code": null,
"e": 5945,
"s": 5695,
"text": "There is no default database for HSQLDB, therefore, you need to create a database for HSQLDB. Let us create a properties file named server.properties which defines a new database named demodb. Take a look at the following database server properties."
},
{
"code": null,
"e": 6010,
"s": 5945,
"text": "server.database.0 = file:hsqldb/demodb\nserver.dbname.0 = testdb\n"
},
{
"code": null,
"e": 6105,
"s": 6010,
"text": "Place this server.properties file into HSQLDB home directory that is C:\\hsqldb- 2.3.4\\hsqldb\\."
},
{
"code": null,
"e": 6158,
"s": 6105,
"text": "Now execute the following command on command prompt."
},
{
"code": null,
"e": 6250,
"s": 6158,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server\n"
},
{
"code": null,
"e": 6361,
"s": 6250,
"text": "After execution of the above command, you will receive the server status as shown in the following screenshot."
},
{
"code": null,
"e": 6639,
"s": 6361,
"text": "Later, you will get to find the following folder structure of the hsqldb directory in the HSQLDB home directory that is C:\\hsqldb-2.3.4\\hsqldb. Those files are temp file, lck file, log file, properties file, and script file of demodb database created by HSQLDB database server."
},
{
"code": null,
"e": 6674,
"s": 6639,
"text": "Step 4 − Start the database server"
},
{
"code": null,
"e": 6776,
"s": 6674,
"text": "Once you are done creating a database, you have to start the database by using the following command."
},
{
"code": null,
"e": 6918,
"s": 6776,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 6986,
"s": 6918,
"text": "After execution of the above command, you get the following status."
},
{
"code": null,
"e": 7347,
"s": 6986,
"text": "Now, you can open the database home screen that is runManagerSwing.bat from C:\\hsqldb-2.3.4\\hsqldb\\bin location. This bat file will open the GUI file for HSQLDB database. Before that it will ask you for database settings through a dialog box. Take a look at the following screenshot. In this dialog box, enter the Setting Name, URL as shown above and click Ok."
},
{
"code": null,
"e": 7432,
"s": 7347,
"text": "You will get the GUI screen of HSQLDB database as shown in the following screenshot."
},
{
"code": null,
"e": 7616,
"s": 7432,
"text": "In the installation chapter, we discussed how to connect the database manually. In this chapter, we will discuss how to connect the database programmatically (using Java programming)."
},
{
"code": null,
"e": 7753,
"s": 7616,
"text": "Take a look at the following program, which will start the server and create a connection between the Java application and the database."
},
{
"code": null,
"e": 8470,
"s": 7753,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\n\npublic class ConnectDatabase {\n public static void main(String[] args) {\n Connection con = null;\n \n try {\n //Registering the HSQLDB JDBC driver\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n //Creating the connection with HSQLDB\n con = DriverManager.getConnection(\"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n if (con!= null){\n System.out.println(\"Connection created successfully\");\n \n }else{\n System.out.println(\"Problem with creating connection\");\n }\n \n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n }\n}"
},
{
"code": null,
"e": 8582,
"s": 8470,
"text": "Save this code into ConnectDatabase.java file. You will have to start the database using the following command."
},
{
"code": null,
"e": 8724,
"s": 8582,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 8791,
"s": 8724,
"text": "You can use the following command to compile and execute the code."
},
{
"code": null,
"e": 8844,
"s": 8791,
"text": "\\>javac ConnectDatabase.java\n\\>java ConnectDatabase\n"
},
{
"code": null,
"e": 8922,
"s": 8844,
"text": "After execution of the above command, you will receive the following output −"
},
{
"code": null,
"e": 8955,
"s": 8922,
"text": "Connection created successfully\n"
},
{
"code": null,
"e": 9063,
"s": 8955,
"text": "This chapter explains the different datatypes of HSQLDB. HSQLDB server offers six categories of data types."
},
{
"code": null,
"e": 9163,
"s": 9063,
"text": "Note − Here, datetime has 3.33 milliseconds accuracy whereas small datetime has 1- minute accuracy."
},
{
"code": null,
"e": 9346,
"s": 9163,
"text": "The basic mandatory requirements to create a table are table name, field names, and the data types to those fields. Optionally, you can also provide the key constraints to the table."
},
{
"code": null,
"e": 9383,
"s": 9346,
"text": "Take a look at the following syntax."
},
{
"code": null,
"e": 9435,
"s": 9383,
"text": "CREATE TABLE table_name (column_name column_type);\n"
},
{
"code": null,
"e": 9582,
"s": 9435,
"text": "Let us create a table named tutorials_tbl with the field-names such as id, title, author, and submission_date. Take a look at the following query."
},
{
"code": null,
"e": 9743,
"s": 9582,
"text": "CREATE TABLE tutorials_tbl (\n id INT NOT NULL,\n title VARCHAR(50) NOT NULL,\n author VARCHAR(20) NOT NULL,\n submission_date DATE,\n PRIMARY KEY (id) \n);"
},
{
"code": null,
"e": 9819,
"s": 9743,
"text": "After execution of the above query, you will receive the following output −"
},
{
"code": null,
"e": 9838,
"s": 9819,
"text": "(0) rows effected\n"
},
{
"code": null,
"e": 9982,
"s": 9838,
"text": "Following is the JDBC program used to create a table named tutorials_tbl into the HSQLDB database. Save the program into CreateTable.java file."
},
{
"code": null,
"e": 10823,
"s": 9982,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Statement;\n\npublic class CreateTable {\n \n public static void main(String[] args) {\n \n Connection con = null;\n Statement stmt = null;\n int result = 0;\n \n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n \n result = stmt.executeUpdate(\"CREATE TABLE tutorials_tbl (\n id INT NOT NULL, title VARCHAR(50) NOT NULL,\n author VARCHAR(20) NOT NULL, submission_date DATE,\n PRIMARY KEY (id));\n \");\n\t\t\t\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n System.out.println(\"Table created successfully\");\n }\n}"
},
{
"code": null,
"e": 10879,
"s": 10823,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 11020,
"s": 10879,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb"
},
{
"code": null,
"e": 11087,
"s": 11020,
"text": "Compile and execute the above program using the following command."
},
{
"code": null,
"e": 11132,
"s": 11087,
"text": "\\>javac CreateTable.java\n\\>java CreateTable\n"
},
{
"code": null,
"e": 11210,
"s": 11132,
"text": "After execution of the above command, you will receive the following output −"
},
{
"code": null,
"e": 11238,
"s": 11210,
"text": "Table created successfully\n"
},
{
"code": null,
"e": 11422,
"s": 11238,
"text": "It is very easy to drop an existing HSQLDB table. However, you need to be very careful while deleting any existing table as any data lost will not be recovered after deleting a table."
},
{
"code": null,
"e": 11480,
"s": 11422,
"text": "Following is a generic SQL syntax to drop a HSQLDB table."
},
{
"code": null,
"e": 11504,
"s": 11480,
"text": "DROP TABLE table_name;\n"
},
{
"code": null,
"e": 11641,
"s": 11504,
"text": "Let us consider an example to drop a table named employee from the HSQLDB server. Following is the query to drop a table named employee."
},
{
"code": null,
"e": 11663,
"s": 11641,
"text": "DROP TABLE employee;\n"
},
{
"code": null,
"e": 11739,
"s": 11663,
"text": "After execution of the above query, you will receive the following output −"
},
{
"code": null,
"e": 11758,
"s": 11739,
"text": "(0) rows effected\n"
},
{
"code": null,
"e": 11844,
"s": 11758,
"text": "Following is the JDBC program used to drop the table employee from the HSQLDB server."
},
{
"code": null,
"e": 11894,
"s": 11844,
"text": "Save the following code into DropTable.java file."
},
{
"code": null,
"e": 12543,
"s": 11894,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Statement;\n\npublic class DropTable {\n public static void main(String[] args) {\n Connection con = null;\n Statement stmt = null;\n int result = 0;\n \n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n result = stmt.executeUpdate(\"DROP TABLE employee\");\n }catch (Exception e) {\n e.printStackTrace(System.out);\n }\n \n System.out.println(\"Table dropped successfully\");\n }\n}"
},
{
"code": null,
"e": 12599,
"s": 12543,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 12741,
"s": 12599,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 12808,
"s": 12741,
"text": "Compile and execute the above program using the following command."
},
{
"code": null,
"e": 12849,
"s": 12808,
"text": "\\>javac DropTable.java\n\\>java DropTable\n"
},
{
"code": null,
"e": 12927,
"s": 12849,
"text": "After execution of the above command, you will receive the following output −"
},
{
"code": null,
"e": 12955,
"s": 12927,
"text": "Table dropped successfully\n"
},
{
"code": null,
"e": 13129,
"s": 12955,
"text": "You can achieve Insert query statement in HSQLDB by using the INSERT INTO command. You have to provide the user-defined data following the column field order from the table."
},
{
"code": null,
"e": 13180,
"s": 13129,
"text": "Following is the generic syntax to INSERT a query."
},
{
"code": null,
"e": 13267,
"s": 13180,
"text": "INSERT INTO table_name (field1, field2,...fieldN)\nVALUES (value1, value2,...valueN );\n"
},
{
"code": null,
"e": 13412,
"s": 13267,
"text": "To insert a string type data into a table, you will have to use double or single quotes to provide string value into the insert query statement."
},
{
"code": null,
"e": 13600,
"s": 13412,
"text": "Let us consider an example that inserts a record into a table named tutorials_tbl with the values id = 100, title = Learn PHP, Author = John Poul, and the submission date is current date."
},
{
"code": null,
"e": 13646,
"s": 13600,
"text": "Following is the query for the given example."
},
{
"code": null,
"e": 13719,
"s": 13646,
"text": "INSERT INTO tutorials_tbl VALUES (100,'Learn PHP', 'John Poul', NOW());\n"
},
{
"code": null,
"e": 13795,
"s": 13719,
"text": "After execution of the above query, you will receive the following output −"
},
{
"code": null,
"e": 13811,
"s": 13795,
"text": "1 row effected\n"
},
{
"code": null,
"e": 14063,
"s": 13811,
"text": "Here is the JDBC program to insert the record into the table with the given values, id =100, title = Learn PHP, Author = John Poul, and the submission date is current date. Take a look at the given program. Save the code into the InserQuery.java file."
},
{
"code": null,
"e": 14873,
"s": 14063,
"text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.Statement; \n\npublic class InsertQuery {\n public static void main(String[] args) { \n Connection con = null; \n Statement stmt = null; \n int result = 0; \n try { \n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\"); \n con = DriverManager.getConnection( \n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\"); \n stmt = con.createStatement(); \n result = stmt.executeUpdate(\"INSERT INTO tutorials_tbl \n VALUES (100,'Learn PHP', 'John Poul', NOW())\"); \n con.commit(); \n }catch (Exception e) { \n e.printStackTrace(System.out); \n } \n System.out.println(result+\" rows effected\"); \n System.out.println(\"Rows inserted successfully\"); \n } \n} "
},
{
"code": null,
"e": 14929,
"s": 14873,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 15074,
"s": 14929,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb \nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0 \nfile:hsqldb/demodb --dbname.0 testdb \n"
},
{
"code": null,
"e": 15141,
"s": 15074,
"text": "Compile and execute the above program using the following command."
},
{
"code": null,
"e": 15188,
"s": 15141,
"text": "\\>javac InsertQuery.java \n\\>java InsertQuery \n"
},
{
"code": null,
"e": 15266,
"s": 15188,
"text": "After execution of the above command, you will receive the following output −"
},
{
"code": null,
"e": 15312,
"s": 15266,
"text": "1 rows effected \nRows inserted successfully \n"
},
{
"code": null,
"e": 15411,
"s": 15312,
"text": "Try to insert the following records into the tutorials_tbl table by using the INSERT INTO command."
},
{
"code": null,
"e": 15561,
"s": 15411,
"text": "The SELECT command is used to fetch the record data from HSQLDB database. Here, you need to mention the required fields list in the Select statement."
},
{
"code": null,
"e": 15606,
"s": 15561,
"text": "Here is the generic syntax for Select query."
},
{
"code": null,
"e": 15703,
"s": 15606,
"text": "SELECT field1, field2,...fieldN table_name1, table_name2...\n[WHERE Clause]\n[OFFSET M ][LIMIT N]\n"
},
{
"code": null,
"e": 15764,
"s": 15703,
"text": "You can fetch one or more fields in a single SELECT command."
},
{
"code": null,
"e": 15825,
"s": 15764,
"text": "You can fetch one or more fields in a single SELECT command."
},
{
"code": null,
"e": 15919,
"s": 15825,
"text": "You can specify star (*) in place of fields. In this case, SELECT will return all the fields."
},
{
"code": null,
"e": 16013,
"s": 15919,
"text": "You can specify star (*) in place of fields. In this case, SELECT will return all the fields."
},
{
"code": null,
"e": 16063,
"s": 16013,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 16113,
"s": 16063,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 16228,
"s": 16113,
"text": "You can specify an offset using OFFSET from where SELECT will start returning records. By default, offset is zero."
},
{
"code": null,
"e": 16343,
"s": 16228,
"text": "You can specify an offset using OFFSET from where SELECT will start returning records. By default, offset is zero."
},
{
"code": null,
"e": 16402,
"s": 16343,
"text": "You can limit the number of returns using LIMIT attribute."
},
{
"code": null,
"e": 16461,
"s": 16402,
"text": "You can limit the number of returns using LIMIT attribute."
},
{
"code": null,
"e": 16654,
"s": 16461,
"text": "Here is an example that fetches id, title, and author fields of all records from tutorials_tbl table. We can achieve this by using the SELECT statement. Following is the query for the example."
},
{
"code": null,
"e": 16699,
"s": 16654,
"text": "SELECT id, title, author FROM tutorials_tbl\n"
},
{
"code": null,
"e": 16774,
"s": 16699,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 17215,
"s": 16774,
"text": "+------+----------------+-----------------+\n| id | title | author |\n+------+----------------+-----------------+\n| 100 | Learn PHP | John Poul |\n| 101 | Learn C | Yaswanth |\n| 102 | Learn MySQL | Abdul S |\n| 103 | Learn Excell | Bavya kanna |\n| 104 | Learn JDB | Ajith kumar |\n| 105 | Learn Junit | Sathya Murthi |\n+------+----------------+-----------------+\n"
},
{
"code": null,
"e": 17382,
"s": 17215,
"text": "Here is the JDBC program that will fetch id, title, and author fields of all records from tutorials_tbl table. Save the following code into the SelectQuery.java file."
},
{
"code": null,
"e": 18262,
"s": 17382,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class SelectQuery {\n \n public static void main(String[] args) {\n Connection con = null;\n Statement stmt = null;\n ResultSet result = null;\n \n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n result = stmt.executeQuery(\n \"SELECT id, title, author FROM tutorials_tbl\");\n \n while(result.next()){\n System.out.println(result.getInt(\"id\")+\" | \"+\n result.getString(\"title\")+\" | \"+\n result.getString(\"author\"));\n }\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n }\n}"
},
{
"code": null,
"e": 18318,
"s": 18262,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 18460,
"s": 18318,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 18524,
"s": 18460,
"text": "Compile and execute the above code using the following command."
},
{
"code": null,
"e": 18569,
"s": 18524,
"text": "\\>javac SelectQuery.java\n\\>java SelectQuery\n"
},
{
"code": null,
"e": 18647,
"s": 18569,
"text": "After execution of the above command, you will receive the following output −"
},
{
"code": null,
"e": 18826,
"s": 18647,
"text": "100 | Learn PHP | John Poul\n101 | Learn C | Yaswanth\n102 | Learn MySQL | Abdul S\n103 | Learn Excell | Bavya Kanna\n104 | Learn JDB | Ajith kumar\n105 | Learn Junit | Sathya Murthi\n"
},
{
"code": null,
"e": 19053,
"s": 18826,
"text": "Generally, we use SELECT command to fetch data from HSQLDB table. We can use WHERE conditional clause to filter the resultant data. Using WHERE we can specify the selection criteria to select the required records from a table."
},
{
"code": null,
"e": 19141,
"s": 19053,
"text": "Following is the syntax of SELECT command WHERE clause to fetch data from HSQLDB table."
},
{
"code": null,
"e": 19247,
"s": 19141,
"text": "SELECT field1, field2,...fieldN table_name1, table_name2...\n[WHERE condition1 [AND [OR]] condition2.....\n"
},
{
"code": null,
"e": 19405,
"s": 19247,
"text": "You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command."
},
{
"code": null,
"e": 19563,
"s": 19405,
"text": "You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command."
},
{
"code": null,
"e": 19613,
"s": 19563,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 19663,
"s": 19613,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 19731,
"s": 19663,
"text": "You can specify more than one conditions using AND or OR operators."
},
{
"code": null,
"e": 19799,
"s": 19731,
"text": "You can specify more than one conditions using AND or OR operators."
},
{
"code": null,
"e": 19895,
"s": 19799,
"text": "A WHERE clause can also be used along with DELETE or UPDATE SQL command to specify a condition."
},
{
"code": null,
"e": 19991,
"s": 19895,
"text": "A WHERE clause can also be used along with DELETE or UPDATE SQL command to specify a condition."
},
{
"code": null,
"e": 20172,
"s": 19991,
"text": "We can filter the record data by using conditions. We are using different operators in conditional WHERE clause. Here is the list of operators, which can be used with WHERE clause."
},
{
"code": null,
"e": 20379,
"s": 20172,
"text": "Here is an example that retrieves the details such as id, title, and the author of the book titled \"Learn C\". It is possible by using WHERE clause in the SELECT command. Following is the query for the same."
},
{
"code": null,
"e": 20449,
"s": 20379,
"text": "SELECT id, title, author FROM tutorials_tbl WHERE title = 'Learn C';\n"
},
{
"code": null,
"e": 20524,
"s": 20449,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 20745,
"s": 20524,
"text": "+------+----------------+-----------------+\n| id | title | author |\n+------+----------------+-----------------+\n| 101 | Learn C | Yaswanth |\n+------+----------------+-----------------+\n"
},
{
"code": null,
"e": 20902,
"s": 20745,
"text": "Here is the JDBC program that retrieves the record data from the table tutorials_tblhaving the title Learn C. Save the following code into WhereClause.java."
},
{
"code": null,
"e": 21810,
"s": 20902,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class WhereClause {\n \n public static void main(String[] args) {\n Connection con = null;\n Statement stmt = null;\n ResultSet result = null;\n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n result = stmt.executeQuery(\n \"SELECT id, title, author FROM tutorials_tbl\n WHERE title = 'Learn C'\");\n \n while(result.next()){\n System.out.println(result.getInt(\"id\")+\" |\n \"+result.getString(\"title\")+\" |\n \"+result.getString(\"author\"));\n }\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n }\n\n}"
},
{
"code": null,
"e": 21866,
"s": 21810,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 22008,
"s": 21866,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 22072,
"s": 22008,
"text": "Compile and execute the above code using the following command."
},
{
"code": null,
"e": 22117,
"s": 22072,
"text": "\\>javac WhereClause.java\n\\>java WhereClause\n"
},
{
"code": null,
"e": 22194,
"s": 22117,
"text": "After execution of the above command, you will receive the following output."
},
{
"code": null,
"e": 22220,
"s": 22194,
"text": "101 | Learn C | Yaswanth\n"
},
{
"code": null,
"e": 22359,
"s": 22220,
"text": "Whenever you want to modify the values of a table, you can use the UPDATE command. This will modify any field value from any HSQLDB table."
},
{
"code": null,
"e": 22406,
"s": 22359,
"text": "Here is the generic syntax for UPDATE command."
},
{
"code": null,
"e": 22485,
"s": 22406,
"text": "UPDATE table_name SET field1 = new-value1, field2 = new-value2 [WHERE Clause]\n"
},
{
"code": null,
"e": 22530,
"s": 22485,
"text": "You can update one or more field altogether."
},
{
"code": null,
"e": 22580,
"s": 22530,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 22631,
"s": 22580,
"text": "You can update values in a single table at a time."
},
{
"code": null,
"e": 22798,
"s": 22631,
"text": "Let us consider an example that updates the title of the tutorial from \"Learn C\" to \"C and Data Structures\" having an id \"101\". Following is the query for the update."
},
{
"code": null,
"e": 22872,
"s": 22798,
"text": "UPDATE tutorials_tbl SET title = 'C and Data Structures' WHERE id = 101;\n"
},
{
"code": null,
"e": 22947,
"s": 22872,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 22966,
"s": 22947,
"text": "(1) Rows effected\n"
},
{
"code": null,
"e": 23140,
"s": 22966,
"text": "Here is the JDBC program that will update a tutorial title from Learn C to C and Data Structures having an id 101. Save the following program into the UpdateQuery.java file."
},
{
"code": null,
"e": 23862,
"s": 23140,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Statement;\n\npublic class UpdateQuery {\n \n public static void main(String[] args) {\n Connection con = null;\n Statement stmt = null;\n int result = 0;\n \n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n result = stmt.executeUpdate(\n \"UPDATE tutorials_tbl SET title = 'C and Data Structures' WHERE id = 101\");\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n System.out.println(result+\" Rows effected\");\n }\n}"
},
{
"code": null,
"e": 23918,
"s": 23862,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 24060,
"s": 23918,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 24127,
"s": 24060,
"text": "Compile and execute the above program using the following command."
},
{
"code": null,
"e": 24172,
"s": 24127,
"text": "\\>javac UpdateQuery.java\n\\>java UpdateQuery\n"
},
{
"code": null,
"e": 24250,
"s": 24172,
"text": "After execution of the above command, you will receive the following output −"
},
{
"code": null,
"e": 24267,
"s": 24250,
"text": "1 Rows effected\n"
},
{
"code": null,
"e": 24364,
"s": 24267,
"text": "Whenever you want to delete a record from any HSQLDB table, you can use the DELETE FROM command."
},
{
"code": null,
"e": 24446,
"s": 24364,
"text": "Here is the generic syntax for DELETE command to delete data from a HSQLDB table."
},
{
"code": null,
"e": 24485,
"s": 24446,
"text": "DELETE FROM table_name [WHERE Clause]\n"
},
{
"code": null,
"e": 24584,
"s": 24485,
"text": "If WHERE clause is not specified, then all the records will be deleted from the given MySQL table."
},
{
"code": null,
"e": 24683,
"s": 24584,
"text": "If WHERE clause is not specified, then all the records will be deleted from the given MySQL table."
},
{
"code": null,
"e": 24733,
"s": 24683,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 24783,
"s": 24733,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 24835,
"s": 24783,
"text": "You can delete records in a single table at a time."
},
{
"code": null,
"e": 24887,
"s": 24835,
"text": "You can delete records in a single table at a time."
},
{
"code": null,
"e": 25051,
"s": 24887,
"text": "Let us consider an example that deletes the record data from the table named tutorials_tbl having id 105. Following is the query that implements the given example."
},
{
"code": null,
"e": 25094,
"s": 25051,
"text": "DELETE FROM tutorials_tbl WHERE id = 105;\n"
},
{
"code": null,
"e": 25170,
"s": 25094,
"text": "After execution of the above query, you will receive the following output −"
},
{
"code": null,
"e": 25189,
"s": 25170,
"text": "(1) rows effected\n"
},
{
"code": null,
"e": 25299,
"s": 25189,
"text": "Here is the JDBC program that implements the given example. Save the following program into DeleteQuery.java."
},
{
"code": null,
"e": 25997,
"s": 25299,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Statement;\n\npublic class DeleteQuery {\n \n public static void main(String[] args) {\n Connection con = null;\n Statement stmt = null;\n int result = 0;\n \n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n result = stmt.executeUpdate(\n \"DELETE FROM tutorials_tbl WHERE id=105\");\n } catch (Exception e) {\n \n e.printStackTrace(System.out);\n }\n System.out.println(result+\" Rows effected\");\n }\n}"
},
{
"code": null,
"e": 26053,
"s": 25997,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 26195,
"s": 26053,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 26262,
"s": 26195,
"text": "Compile and execute the above program using the following command."
},
{
"code": null,
"e": 26307,
"s": 26262,
"text": "\\>javac DeleteQuery.java\n\\>java DeleteQuery\n"
},
{
"code": null,
"e": 26385,
"s": 26307,
"text": "After execution of the above command, you will receive the following output −"
},
{
"code": null,
"e": 26402,
"s": 26385,
"text": "1 Rows effected\n"
},
{
"code": null,
"e": 26736,
"s": 26402,
"text": "There is a WHERE clause in the RDBMS structure. You can use the WHERE clause with an equal to sign (=) where we want to do an exact match. But there may be a requirement where we want to filter out all the results where the author name should contain \"john\". This can be handled using the SQL LIKE clause along with the WHERE clause."
},
{
"code": null,
"e": 26909,
"s": 26736,
"text": "If the SQL LIKE clause is used along with % characters, then it will work like a metacharacter (*) in UNIX while listing out all the files or directories at command prompt."
},
{
"code": null,
"e": 26965,
"s": 26909,
"text": "Following is the generic SQL syntax of the LIKE clause."
},
{
"code": null,
"e": 27087,
"s": 26965,
"text": "SELECT field1, field2,...fieldN table_name1, table_name2...\nWHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'\n"
},
{
"code": null,
"e": 27141,
"s": 27087,
"text": "You can specify any condition using the WHERE clause."
},
{
"code": null,
"e": 27195,
"s": 27141,
"text": "You can specify any condition using the WHERE clause."
},
{
"code": null,
"e": 27252,
"s": 27195,
"text": "You can use the LIKE clause along with the WHERE clause."
},
{
"code": null,
"e": 27309,
"s": 27252,
"text": "You can use the LIKE clause along with the WHERE clause."
},
{
"code": null,
"e": 27368,
"s": 27309,
"text": "You can use the LIKE clause in place of the equal to sign."
},
{
"code": null,
"e": 27427,
"s": 27368,
"text": "You can use the LIKE clause in place of the equal to sign."
},
{
"code": null,
"e": 27526,
"s": 27427,
"text": "When the LIKE clause is used along with the % sign, then it will work like a metacharacter search."
},
{
"code": null,
"e": 27625,
"s": 27526,
"text": "When the LIKE clause is used along with the % sign, then it will work like a metacharacter search."
},
{
"code": null,
"e": 27693,
"s": 27625,
"text": "You can specify more than one conditions using AND or OR operators."
},
{
"code": null,
"e": 27761,
"s": 27693,
"text": "You can specify more than one conditions using AND or OR operators."
},
{
"code": null,
"e": 27867,
"s": 27761,
"text": "A WHERE...LIKE clause can be used along with the DELETE or the UPDATE SQL command to specify a condition."
},
{
"code": null,
"e": 27973,
"s": 27867,
"text": "A WHERE...LIKE clause can be used along with the DELETE or the UPDATE SQL command to specify a condition."
},
{
"code": null,
"e": 28135,
"s": 27973,
"text": "Let us consider an example that retrieves the list of tutorials data where the author name starts with John. Following is the HSQLDB query for the given example."
},
{
"code": null,
"e": 28191,
"s": 28135,
"text": "SELECT * from tutorials_tbl WHERE author LIKE 'John%';\n"
},
{
"code": null,
"e": 28266,
"s": 28191,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 28542,
"s": 28266,
"text": "+-----+----------------+-----------+-----------------+\n| id | title | author | submission_date |\n+-----+----------------+-----------+-----------------+\n| 100 | Learn PHP | John Poul | 2016-06-20 |\n+-----+----------------+-----------+-----------------+\n"
},
{
"code": null,
"e": 28690,
"s": 28542,
"text": "Following is the JDBC program that retrieves the list of tutorials data where the author name starts with John. Save the code into LikeClause.java."
},
{
"code": null,
"e": 29633,
"s": 28690,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class LikeClause {\n \n public static void main(String[] args) {\n Connection con = null;\n Statement stmt = null;\n ResultSet result = null;\n \n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n result = stmt.executeQuery(\n \"SELECT * from tutorials_tbl WHERE author LIKE 'John%';\");\n \n while(result.next()){\n System.out.println(result.getInt(\"id\")+\" |\n \"+result.getString(\"title\")+\" |\n \"+result.getString(\"author\")+\" |\n \"+result.getDate(\"submission_date\"));\n }\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n }\n}"
},
{
"code": null,
"e": 29689,
"s": 29633,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 29831,
"s": 29689,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 29895,
"s": 29831,
"text": "Compile and execute the above code using the following command."
},
{
"code": null,
"e": 29938,
"s": 29895,
"text": "\\>javac LikeClause.java\n\\>java LikeClause\n"
},
{
"code": null,
"e": 30019,
"s": 29938,
"text": "After execution of the following command, you will receive the following output."
},
{
"code": null,
"e": 30061,
"s": 30019,
"text": "100 | Learn PHP | John Poul | 2016-06-20\n"
},
{
"code": null,
"e": 30270,
"s": 30061,
"text": "The SQL SELECT command fetches data from the HSQLDB table whenever there is a requirement that follows a particular order while retrieving and displaying records. In that case, we can use the ORDER BY clause."
},
{
"code": null,
"e": 30364,
"s": 30270,
"text": "Here is the syntax of the SELECT command along with ORDER BY clause to sort data from HSQLDB."
},
{
"code": null,
"e": 30467,
"s": 30364,
"text": "SELECT field1, field2,...fieldN table_name1, table_name2...\nORDER BY field1, [field2...] [ASC [DESC]]\n"
},
{
"code": null,
"e": 30554,
"s": 30467,
"text": "You can sort the returned result on any field provided that field is being listed out."
},
{
"code": null,
"e": 30641,
"s": 30554,
"text": "You can sort the returned result on any field provided that field is being listed out."
},
{
"code": null,
"e": 30689,
"s": 30641,
"text": "You can sort the result on more than one field."
},
{
"code": null,
"e": 30737,
"s": 30689,
"text": "You can sort the result on more than one field."
},
{
"code": null,
"e": 30868,
"s": 30737,
"text": "You can use the keyword ASC or DESC to get the result in an ascending or descending order. By default, it's in an ascending order."
},
{
"code": null,
"e": 30999,
"s": 30868,
"text": "You can use the keyword ASC or DESC to get the result in an ascending or descending order. By default, it's in an ascending order."
},
{
"code": null,
"e": 31070,
"s": 30999,
"text": "You can use the WHERE...LIKE clause in a usual way to put a condition."
},
{
"code": null,
"e": 31141,
"s": 31070,
"text": "You can use the WHERE...LIKE clause in a usual way to put a condition."
},
{
"code": null,
"e": 31314,
"s": 31141,
"text": "Let us consider an example that fetches and sorts the records of tutorials_tbl table by ordering the author name in an ascending order. Following is the query for the same."
},
{
"code": null,
"e": 31380,
"s": 31314,
"text": "SELECT id, title, author from tutorials_tbl ORDER BY author ASC;\n"
},
{
"code": null,
"e": 31455,
"s": 31380,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 31897,
"s": 31455,
"text": "+------+----------------+-----------------+\n| id | title | author |\n+------+----------------+-----------------+\n| 102 | Learn MySQL | Abdul S | \n| 104 | Learn JDB | Ajith kumar |\n| 103 | Learn Excell | Bavya kanna |\n| 100 | Learn PHP | John Poul |\n| 105 | Learn Junit | Sathya Murthi |\n| 101 | Learn C | Yaswanth |\n+------+----------------+-----------------+\n"
},
{
"code": null,
"e": 32077,
"s": 31897,
"text": "Here is the JDBC program that fetches and sorts the records of tutorials_tbl table by ordering the author name in an ascending order. Save the following program into OrderBy.java."
},
{
"code": null,
"e": 32977,
"s": 32077,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class OrderBy {\n \n public static void main(String[] args) {\n Connection con = null;\n Statement stmt = null;\n ResultSet result = null;\n \n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n result = stmt.executeQuery(\n \"SELECT id, title, author from tutorials_tbl\n ORDER BY author ASC\");\n \n while(result.next()){\n System.out.println(result.getInt(\"id\")+\" |\n \"+result.getString(\"title\")+\" |\n \"+result.getString(\"author\"));\n }\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n }\n}"
},
{
"code": null,
"e": 33033,
"s": 32977,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 33175,
"s": 33033,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 33242,
"s": 33175,
"text": "Compile and execute the above program using the following command."
},
{
"code": null,
"e": 33279,
"s": 33242,
"text": "\\>javac OrderBy.java\n\\>java OrderBy\n"
},
{
"code": null,
"e": 33356,
"s": 33279,
"text": "After execution of the above command, you will receive the following output."
},
{
"code": null,
"e": 33602,
"s": 33356,
"text": "102 | Learn MySQL | Abdul S\n104 | Learn JDB | Ajith kumar\n103 | Learn Excell | Bavya Kanna\n100 | Learn PHP | John Poul\n105 | Learn Junit | Sathya Murthi\n101 | C and Data Structures | Yaswanth\n"
},
{
"code": null,
"e": 33866,
"s": 33602,
"text": "Whenever there is a requirement to retrieve data from multiple tables using a single query, you can use JOINS from RDBMS. You can use multiple tables in your single SQL query. The act of joining in HSQLDB refers to smashing two or more tables into a single table."
},
{
"code": null,
"e": 33918,
"s": 33866,
"text": "Consider the following Customers and Orders tables."
},
{
"code": null,
"e": 34878,
"s": 33918,
"text": "Customer:\n+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\nOrders:\n+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n"
},
{
"code": null,
"e": 35173,
"s": 34878,
"text": "Now, let us try to retrieve the data of the customers and the order amount that the respective customer placed. This means we are retrieving the record data from both customers and orders table. We can achieve this by using the JOINS concept in HSQLDB. Following is the JOIN query for the same."
},
{
"code": null,
"e": 35266,
"s": 35173,
"text": "SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID =\nORDERS.CUSTOMER_ID;"
},
{
"code": null,
"e": 35341,
"s": 35266,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 35606,
"s": 35341,
"text": "+----+----------+-----+--------+\n| ID | NAME | AGE | AMOUNT |\n+----+----------+-----+--------+\n| 3 | kaushik | 23 | 3000 |\n| 3 | kaushik | 23 | 1500 |\n| 2 | Khilan | 25 | 1560 |\n| 4 | Chaitali | 25 | 2060 |\n+----+----------+-----+--------+\n"
},
{
"code": null,
"e": 35662,
"s": 35606,
"text": "There are different types of joins available in HSQLDB."
},
{
"code": null,
"e": 35730,
"s": 35662,
"text": "INNER JOIN − Returns the rows when there is a match in both tables."
},
{
"code": null,
"e": 35798,
"s": 35730,
"text": "INNER JOIN − Returns the rows when there is a match in both tables."
},
{
"code": null,
"e": 35897,
"s": 35798,
"text": "LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table."
},
{
"code": null,
"e": 35996,
"s": 35897,
"text": "LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table."
},
{
"code": null,
"e": 36096,
"s": 35996,
"text": "RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table."
},
{
"code": null,
"e": 36196,
"s": 36096,
"text": "RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table."
},
{
"code": null,
"e": 36269,
"s": 36196,
"text": "FULL JOIN − Returns the rows when there is a match in one of the tables."
},
{
"code": null,
"e": 36342,
"s": 36269,
"text": "FULL JOIN − Returns the rows when there is a match in one of the tables."
},
{
"code": null,
"e": 36480,
"s": 36342,
"text": "SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement."
},
{
"code": null,
"e": 36618,
"s": 36480,
"text": "SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement."
},
{
"code": null,
"e": 36728,
"s": 36618,
"text": "The most frequently used and important of the joins is the INNER JOIN. It is also referred to as an EQUIJOIN."
},
{
"code": null,
"e": 37115,
"s": 36728,
"text": "The INNER JOIN creates a new result table by combining the column values of two tables (table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows, which satisfy the join-predicate. When the join-predicate is satisfied, the column values for each matched pair of rows A and B are combined into a result row."
},
{
"code": null,
"e": 37161,
"s": 37115,
"text": "The basic syntax of INNER JOIN is as follows."
},
{
"code": null,
"e": 37278,
"s": 37161,
"text": "SELECT table1.column1, table2.column2...\nFROM table1\nINNER JOIN table2\nON table1.common_field = table2.common_field;"
},
{
"code": null,
"e": 37391,
"s": 37278,
"text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −"
},
{
"code": null,
"e": 37909,
"s": 37391,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 38334,
"s": 37909,
"text": "+-----+---------------------+-------------+--------+\n| OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n"
},
{
"code": null,
"e": 38404,
"s": 38334,
"text": "Now, let us join these two tables using INNER JOIN query as follows −"
},
{
"code": null,
"e": 38505,
"s": 38404,
"text": "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS\nINNER JOIN ORDERS\nON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;"
},
{
"code": null,
"e": 38580,
"s": 38505,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 38973,
"s": 38580,
"text": "+----+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+----+----------+--------+---------------------+\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n+----+----------+--------+---------------------+\n"
},
{
"code": null,
"e": 39258,
"s": 38973,
"text": "The HSQLDB LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table, the join will still return a row in the result, but with NULL in each column from the right table."
},
{
"code": null,
"e": 39418,
"s": 39258,
"text": "This means that a left join returns all the values from the left table, plus matched values from the right table or NULL in case of no matching join predicate."
},
{
"code": null,
"e": 39464,
"s": 39418,
"text": "The basic syntax of LEFT JOIN is as follows −"
},
{
"code": null,
"e": 39580,
"s": 39464,
"text": "SELECT table1.column1, table2.column2...\nFROM table1\nLEFT JOIN table2\nON table1.common_field = table2.common_field;"
},
{
"code": null,
"e": 39662,
"s": 39580,
"text": "Here the given condition could be any given expression based on your requirement."
},
{
"code": null,
"e": 39775,
"s": 39662,
"text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −"
},
{
"code": null,
"e": 40293,
"s": 39775,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 40718,
"s": 40293,
"text": "+-----+---------------------+-------------+--------+\n| OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n"
},
{
"code": null,
"e": 40791,
"s": 40718,
"text": "Now, let us join these two tables using the LEFT JOIN query as follows −"
},
{
"code": null,
"e": 40891,
"s": 40791,
"text": "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS\nLEFT JOIN ORDERS\nON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;"
},
{
"code": null,
"e": 40967,
"s": 40891,
"text": "After execution of the above query, you will receive the following output −"
},
{
"code": null,
"e": 41556,
"s": 40967,
"text": "+----+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+----+----------+--------+---------------------+\n| 1 | Ramesh | NULL | NULL |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n| 5 | Hardik | NULL | NULL |\n| 6 | Komal | NULL | NULL |\n| 7 | Muffy | NULL | NULL |\n+----+----------+--------+---------------------+\n"
},
{
"code": null,
"e": 41840,
"s": 41556,
"text": "The HSQLDB RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table. This means that if the ON clause matches 0 (zero) records in the left table, the join will still return a row in the result, but with NULL in each column from the left table."
},
{
"code": null,
"e": 42001,
"s": 41840,
"text": "This means that a right join returns all the values from the right table, plus matched values from the left table or NULL in case of no matching join predicate."
},
{
"code": null,
"e": 42048,
"s": 42001,
"text": "The basic syntax of RIGHT JOIN is as follows −"
},
{
"code": null,
"e": 42165,
"s": 42048,
"text": "SELECT table1.column1, table2.column2...\nFROM table1\nRIGHT JOIN table2\nON table1.common_field = table2.common_field;"
},
{
"code": null,
"e": 42278,
"s": 42165,
"text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −"
},
{
"code": null,
"e": 42796,
"s": 42278,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 43221,
"s": 42796,
"text": "+-----+---------------------+-------------+--------+\n| OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n"
},
{
"code": null,
"e": 43295,
"s": 43221,
"text": "Now, let us join these two tables using the RIGHT JOIN query as follows −"
},
{
"code": null,
"e": 43396,
"s": 43295,
"text": "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS\nRIGHT JOIN ORDERS\nON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;"
},
{
"code": null,
"e": 43471,
"s": 43396,
"text": "After execution of the above query, you will receive the following result."
},
{
"code": null,
"e": 43880,
"s": 43471,
"text": "+------+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+------+----------+--------+---------------------+\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n+------+----------+--------+---------------------+\n"
},
{
"code": null,
"e": 43958,
"s": 43880,
"text": "The HSQLDB FULL JOIN combines the results of both left and right outer joins."
},
{
"code": null,
"e": 44076,
"s": 43958,
"text": "The joined table will contain all records from both tables, and fill in NULLs for the missing matches on either side."
},
{
"code": null,
"e": 44122,
"s": 44076,
"text": "The basic syntax of FULL JOIN is as follows −"
},
{
"code": null,
"e": 44239,
"s": 44122,
"text": "SELECT table1.column1, table2.column2...\nFROM table1\nFULL JOIN table2\nON table1.common_field = table2.common_field;\n"
},
{
"code": null,
"e": 44321,
"s": 44239,
"text": "Here the given condition could be any given expression based on your requirement."
},
{
"code": null,
"e": 44434,
"s": 44321,
"text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as\nORDERS table as follows −"
},
{
"code": null,
"e": 44952,
"s": 44434,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 45377,
"s": 44952,
"text": "+-----+---------------------+-------------+--------+\n| OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+\n"
},
{
"code": null,
"e": 45450,
"s": 45377,
"text": "Now, let us join these two tables using the FULL JOIN query as follows −"
},
{
"code": null,
"e": 45550,
"s": 45450,
"text": "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS\nFULL JOIN ORDERS\nON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;"
},
{
"code": null,
"e": 45625,
"s": 45550,
"text": "After execution of the above query, you will receive the following result."
},
{
"code": null,
"e": 46442,
"s": 45625,
"text": "+------+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+------+----------+--------+---------------------+\n| 1 | Ramesh | NULL | NULL |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n| 5 | Hardik | NULL | NULL |\n| 6 | Komal | NULL | NULL |\n| 7 | Muffy | NULL | NULL |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n+------+----------+--------+---------------------+\n"
},
{
"code": null,
"e": 46589,
"s": 46442,
"text": "The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement."
},
{
"code": null,
"e": 46635,
"s": 46589,
"text": "The basic syntax of SELF JOIN is as follows −"
},
{
"code": null,
"e": 46737,
"s": 46635,
"text": "SELECT a.column_name, b.column_name...\nFROM table1 a, table1 b\nWHERE a.common_field = b.common_field;"
},
{
"code": null,
"e": 46817,
"s": 46737,
"text": "Here, the WHERE clause could be any given expression based on your requirement."
},
{
"code": null,
"e": 46930,
"s": 46817,
"text": "Consider the following two tables, one titled as CUSTOMERS table and another titled as ORDERS table as follows −"
},
{
"code": null,
"e": 47448,
"s": 46930,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 47515,
"s": 47448,
"text": "Now, let us join this table using the SELF JOIN query as follows −"
},
{
"code": null,
"e": 47603,
"s": 47515,
"text": "SELECT a.ID, b.NAME, a.SALARY FROM CUSTOMERS a, CUSTOMERS b\nWHERE a.SALARY > b.SALARY;\n"
},
{
"code": null,
"e": 47679,
"s": 47603,
"text": "After execution of the above query, you will receive the following output −"
},
{
"code": null,
"e": 48352,
"s": 47679,
"text": "+----+----------+---------+\n| ID | NAME | SALARY |\n+----+----------+---------+\n| 2 | Ramesh | 1500.00 |\n| 2 | kaushik | 1500.00 |\n| 1 | Chaitali | 2000.00 |\n| 2 | Chaitali | 1500.00 |\n| 3 | Chaitali | 2000.00 |\n| 6 | Chaitali | 4500.00 |\n| 1 | Hardik | 2000.00 |\n| 2 | Hardik | 1500.00 |\n| 3 | Hardik | 2000.00 |\n| 4 | Hardik | 6500.00 |\n| 6 | Hardik | 4500.00 |\n| 1 | Komal | 2000.00 |\n| 2 | Komal | 1500.00 |\n| 3 | Komal | 2000.00 |\n| 1 | Muffy | 2000.00 |\n| 2 | Muffy | 1500.00 |\n| 3 | Muffy | 2000.00 |\n| 4 | Muffy | 6500.00 |\n| 5 | Muffy | 8500.00 |\n| 6 | Muffy | 4500.00 |\n+----+----------+---------+\n"
},
{
"code": null,
"e": 48591,
"s": 48352,
"text": "SQL NULL is a term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank. Whenever we try to give a condition, which compare the field or column value to NULL, it does not work properly."
},
{
"code": null,
"e": 48648,
"s": 48591,
"text": "We can handle the NULL values by using the three things."
},
{
"code": null,
"e": 48713,
"s": 48648,
"text": "IS NULL − The operator returns true if the column value is NULL."
},
{
"code": null,
"e": 48778,
"s": 48713,
"text": "IS NULL − The operator returns true if the column value is NULL."
},
{
"code": null,
"e": 48851,
"s": 48778,
"text": "IS NOT NULL − The operator returns true if the column value is NOT NULL."
},
{
"code": null,
"e": 48924,
"s": 48851,
"text": "IS NOT NULL − The operator returns true if the column value is NOT NULL."
},
{
"code": null,
"e": 49024,
"s": 48924,
"text": "<=> − The operator compares values, which (unlike the = operator) is true even for two NULL values."
},
{
"code": null,
"e": 49124,
"s": 49024,
"text": "<=> − The operator compares values, which (unlike the = operator) is true even for two NULL values."
},
{
"code": null,
"e": 49212,
"s": 49124,
"text": "To look for columns that are NULL or NOT NULL, use IS NULL or IS NOT NULL respectively."
},
{
"code": null,
"e": 49509,
"s": 49212,
"text": "Let us consider an example where there is a table tcount_tbl that contains two columns, author and tutorial_count. We can provide NULL values to the tutorial_count indicates that the author did not publish even one tutorial. Therefore, the tutorial_count value for that respective author is NULL."
},
{
"code": null,
"e": 49540,
"s": 49509,
"text": "Execute the following queries."
},
{
"code": null,
"e": 49956,
"s": 49540,
"text": "create table tcount_tbl(author varchar(40) NOT NULL, tutorial_count INT);\nINSERT INTO tcount_tbl values ('Abdul S', 20);\nINSERT INTO tcount_tbl values ('Ajith kumar', 5);\nINSERT INTO tcount_tbl values ('Jen', NULL);\nINSERT INTO tcount_tbl values ('Bavya kanna', 8);\nINSERT INTO tcount_tbl values ('mahran', NULL);\nINSERT INTO tcount_tbl values ('John Poul', 10);\nINSERT INTO tcount_tbl values ('Sathya Murthi', 6);\n"
},
{
"code": null,
"e": 50036,
"s": 49956,
"text": "Use the following command to display all the records from the tcount_tbl table."
},
{
"code": null,
"e": 50063,
"s": 50036,
"text": "select * from tcount_tbl;\n"
},
{
"code": null,
"e": 50140,
"s": 50063,
"text": "After execution of the above command, you will receive the following output."
},
{
"code": null,
"e": 50548,
"s": 50140,
"text": "+-----------------+----------------+\n| author | tutorial_count |\n+-----------------+----------------+\n| Abdul S | 20 |\n| Ajith kumar | 5 |\n| Jen | NULL |\n| Bavya kanna | 8 |\n| mahran | NULL |\n| John Poul | 10 |\n| Sathya Murthi | 6 |\n+-----------------+----------------+\n"
},
{
"code": null,
"e": 50633,
"s": 50548,
"text": "To find the records where the tutorial_count column IS NULL, following is the query."
},
{
"code": null,
"e": 50689,
"s": 50633,
"text": "SELECT * FROM tcount_tbl WHERE tutorial_count IS NULL;\n"
},
{
"code": null,
"e": 50758,
"s": 50689,
"text": "After execution of the query, you will receive the following output."
},
{
"code": null,
"e": 50981,
"s": 50758,
"text": "+-----------------+----------------+\n| author | tutorial_count |\n+-----------------+----------------+\n| Jen | NULL |\n| mahran | NULL |\n+-----------------+----------------+\n"
},
{
"code": null,
"e": 51070,
"s": 50981,
"text": "To find the records where the tutorial_count column IS NOT NULL, following is the query."
},
{
"code": null,
"e": 51130,
"s": 51070,
"text": "SELECT * FROM tcount_tbl WHERE tutorial_count IS NOT NULL;\n"
},
{
"code": null,
"e": 51199,
"s": 51130,
"text": "After execution of the query, you will receive the following output."
},
{
"code": null,
"e": 51533,
"s": 51199,
"text": "+-----------------+----------------+\n| author | tutorial_count |\n+-----------------+----------------+\n| Abdul S | 20 |\n| Ajith kumar | 5 |\n| Bavya kanna | 8 |\n| John Poul | 10 |\n| Sathya Murthi | 6 |\n+-----------------+----------------+\n"
},
{
"code": null,
"e": 51741,
"s": 51533,
"text": "Here is the JDBC program that retrieves the records separately from the table tcount_tbl where the tutorial_ count is NULL and the tutorial_count is NOT NULL. Save the following program into NullValues.java."
},
{
"code": null,
"e": 53132,
"s": 51741,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class NullValues {\n public static void main(String[] args) {\n Connection con = null;\n Statement stmt_is_null = null;\n Statement stmt_is_not_null = null;\n ResultSet result = null;\n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt_is_null = con.createStatement();\n stmt_is_not_null = con.createStatement();\n result = stmt_is_null.executeQuery(\n \"SELECT * FROM tcount_tbl WHERE tutorial_count IS NULL;\");\n System.out.println(\"Records where the tutorial_count is NULL\");\n \n while(result.next()){\n System.out.println(result.getString(\"author\")+\" |\n \"+result.getInt(\"tutorial_count\"));\n }\n result = stmt_is_not_null.executeQuery(\n \"SELECT * FROM tcount_tbl WHERE tutorial_count IS NOT NULL;\");\n System.out.println(\"Records where the tutorial_count is NOT NULL\");\n \n while(result.next()){\n System.out.println(result.getString(\"author\")+\" |\n \"+result.getInt(\"tutorial_count\"));\n }\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n }\n}"
},
{
"code": null,
"e": 53199,
"s": 53132,
"text": "Compile and execute the above program using the following command."
},
{
"code": null,
"e": 53242,
"s": 53199,
"text": "\\>javac NullValues.java\n\\>Java NullValues\n"
},
{
"code": null,
"e": 53319,
"s": 53242,
"text": "After execution of the above command, you will receive the following output."
},
{
"code": null,
"e": 53536,
"s": 53319,
"text": "Records where the tutorial_count is NULL\nJen | 0\nmahran | 0\n\nRecords where the tutorial_count is NOT NULL\nAbdul S | 20\nAjith kumar | 5\nBavya kanna | 8\nJohn Poul | 10\nSathya Murthi | 6\n"
},
{
"code": null,
"e": 53658,
"s": 53536,
"text": "HSQLDB supports some special symbols for pattern matching operation based on regular expressions and the REGEXP operator."
},
{
"code": null,
"e": 53739,
"s": 53658,
"text": "Following is the table of pattern, which can be used along with REGEXP operator."
},
{
"code": null,
"e": 53846,
"s": 53739,
"text": "Let us try different example queries to meet our requirements. Take a look at the following given queries."
},
{
"code": null,
"e": 53914,
"s": 53846,
"text": "Try this Query to find all the authors whose name starts with '^A'."
},
{
"code": null,
"e": 53982,
"s": 53914,
"text": "SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'^A.*');\n"
},
{
"code": null,
"e": 54057,
"s": 53982,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 54178,
"s": 54057,
"text": "+-----------------+\n| author |\n+-----------------+\n| Abdul S |\n| Ajith kumar |\n+-----------------+\n"
},
{
"code": null,
"e": 54245,
"s": 54178,
"text": "Try this Query to find all the authors whose name ends with 'ul$'."
},
{
"code": null,
"e": 54314,
"s": 54245,
"text": "SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'.*ul$');\n"
},
{
"code": null,
"e": 54389,
"s": 54314,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 54490,
"s": 54389,
"text": "+-----------------+\n| author |\n+-----------------+\n| John Poul |\n+-----------------+\n"
},
{
"code": null,
"e": 54555,
"s": 54490,
"text": "Try this Query to find all the authors whose name contains 'th'."
},
{
"code": null,
"e": 54625,
"s": 54555,
"text": "SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'.*th.*');\n"
},
{
"code": null,
"e": 54700,
"s": 54625,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 54822,
"s": 54700,
"text": "+-----------------+\n| author |\n+-----------------+\n| Ajith kumar | \n| Abdul S |\n+-----------------+\n"
},
{
"code": null,
"e": 54907,
"s": 54822,
"text": "Try this query to find all the authors whose name starts with vowel (a, e, i, o, u)."
},
{
"code": null,
"e": 54981,
"s": 54907,
"text": "SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'^[AEIOU].*');\n"
},
{
"code": null,
"e": 55056,
"s": 54981,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 55177,
"s": 55056,
"text": "+-----------------+\n| author |\n+-----------------+\n| Abdul S |\n| Ajith kumar |\n+-----------------+\n"
},
{
"code": null,
"e": 55513,
"s": 55177,
"text": "A Transaction is a sequential group of database manipulation operations, which is performed and considered as one single work unit. In other words, when all the operations are successfully executed, only then the entire transaction will be complete. If any operation within the transaction fails, then the entire transaction will fail."
},
{
"code": null,
"e": 55612,
"s": 55513,
"text": "Basically, transaction supports 4 standard properties. They can be referred to as ACID properties."
},
{
"code": null,
"e": 55825,
"s": 55612,
"text": "Atomicity − All the operations in the transactions are executed successfully, otherwise the transaction gets aborted at the point of failure and the previous operations are rolled back to their previous position."
},
{
"code": null,
"e": 55919,
"s": 55825,
"text": "Consistency − The database properly changes states upon a successfully committed transaction."
},
{
"code": null,
"e": 56017,
"s": 55919,
"text": "Isolation − It enables the transaction to operate independently on and transparent to each other."
},
{
"code": null,
"e": 56116,
"s": 56017,
"text": "Durability − The result or effect of a committed transaction persists in case of a system failure."
},
{
"code": null,
"e": 56172,
"s": 56116,
"text": "These keywords are mainly used for HSQLDB transactions."
},
{
"code": null,
"e": 56267,
"s": 56172,
"text": "Commit− Always the successful transaction should be completed by executing the COMMIT command."
},
{
"code": null,
"e": 56438,
"s": 56267,
"text": "Rollback − If a failure occurs in the transaction, then the ROLLBACK command should be executed to return every table referenced in the transaction to its previous state."
},
{
"code": null,
"e": 56521,
"s": 56438,
"text": "Savepoint − Creates a point within the group of transactions in which to rollback."
},
{
"code": null,
"e": 56710,
"s": 56521,
"text": "The following example explains the transactions concept along with commit, rollback, and Savepoint. Let us consider the table Customers with the columns id, name, age, address, and salary."
},
{
"code": null,
"e": 56801,
"s": 56710,
"text": "Use the following commands to create the customer table along the lines of the above data."
},
{
"code": null,
"e": 57381,
"s": 56801,
"text": "CREATE TABLE Customer (id INT NOT NULL, name VARCHAR(100) NOT NULL, age INT NOT\nNULL, address VARCHAR(20), Salary INT, PRIMARY KEY (id));\nInsert into Customer values (1, \"Ramesh\", 32, \"Ahmedabad\", 2000);\nInsert into Customer values (2, \"Karun\", 25, \"Delhi\", 1500);\nInsert into Customer values (3, \"Kaushik\", 23, \"Kota\", 2000);\nInsert into Customer values (4, \"Chaitanya\", 25, \"Mumbai\", 6500);\nInsert into Customer values (5, \"Harish\", 27, \"Bhopal\", 8500);\nInsert into Customer values (6, \"Kamesh\", 22, \"MP\", 1500);\nInsert into Customer values (7, \"Murali\", 24, \"Indore\", 10000);\n"
},
{
"code": null,
"e": 57513,
"s": 57381,
"text": "The following query deletes rows from the table having age = 25 and uses the COMMIT command to apply those changes in the database."
},
{
"code": null,
"e": 57560,
"s": 57513,
"text": "DELETE FROM CUSTOMERS WHERE AGE = 25;\nCOMMIT;\n"
},
{
"code": null,
"e": 57635,
"s": 57560,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 57652,
"s": 57635,
"text": "2 rows effected\n"
},
{
"code": null,
"e": 57779,
"s": 57652,
"text": "After successful execution of the above command, check the records of the customer table by executing the below given command."
},
{
"code": null,
"e": 57804,
"s": 57779,
"text": "Select * from Customer;\n"
},
{
"code": null,
"e": 57879,
"s": 57804,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 58303,
"s": 57879,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000 |\n| 3 | kaushik | 23 | Kota | 2000 |\n| 5 | Harish | 27 | Bhopal | 8500 |\n| 6 | Kamesh | 22 | MP | 4500 |\n| 7 | Murali | 24 | Indore | 10000 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 58353,
"s": 58303,
"text": "Let us consider the same Customer table as input."
},
{
"code": null,
"e": 58520,
"s": 58353,
"text": "Here is the example query that explains about Rollback functionality by deleting records from the table having age = 25 and then ROLLBACK the changes in the database."
},
{
"code": null,
"e": 58569,
"s": 58520,
"text": "DELETE FROM CUSTOMERS WHERE AGE = 25;\nROLLBACK;\n"
},
{
"code": null,
"e": 58702,
"s": 58569,
"text": "After successful execution of the above two queries, you can view the record data in the Customer table using the following command."
},
{
"code": null,
"e": 58727,
"s": 58702,
"text": "Select * from Customer;\n"
},
{
"code": null,
"e": 58804,
"s": 58727,
"text": "After execution of the above command, you will receive the following output."
},
{
"code": null,
"e": 59322,
"s": 58804,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000 |\n| 2 | Karun | 25 | Delhi | 1500 |\n| 3 | Kaushik | 23 | Kota | 2000 |\n| 4 | Chaitanya| 25 | Mumbai | 6500 |\n| 5 | Harish | 27 | Bhopal | 8500 |\n| 6 | Kamesh | 22 | MP | 4500 |\n| 7 | Murali | 24 | Indore | 10000 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 59462,
"s": 59322,
"text": "The delete query deletes the record data of customers whose age = 25. The Rollback command, rolls back those changes on the Customer table."
},
{
"code": null,
"e": 59603,
"s": 59462,
"text": "Savepoint is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction."
},
{
"code": null,
"e": 59653,
"s": 59603,
"text": "Let us consider the same Customer table as input."
},
{
"code": null,
"e": 59919,
"s": 59653,
"text": "Let us consider in this example, you plan to delete the three different records from the Customers table. You want to create a Savepoint before each delete, so that you can roll back to any Savepoint at any time to return the appropriate data to its original state."
},
{
"code": null,
"e": 59953,
"s": 59919,
"text": "Here is the series of operations."
},
{
"code": null,
"e": 60107,
"s": 59953,
"text": "SAVEPOINT SP1;\nDELETE FROM CUSTOMERS WHERE ID = 1;\nSAVEPOINT SP2;\nDELETE FROM CUSTOMERS WHERE ID = 2;\nSAVEPOINT SP3;\nDELETE FROM CUSTOMERS WHERE ID = 3;\n"
},
{
"code": null,
"e": 60287,
"s": 60107,
"text": "Now, you have created three Savepoint and deleted three records. In this situation, if you want to roll back the records having Id 2 and 3 then use the following Rollback command."
},
{
"code": null,
"e": 60305,
"s": 60287,
"text": "ROLLBACK TO SP2;\n"
},
{
"code": null,
"e": 60451,
"s": 60305,
"text": "Notice that only the first deletion took place since you rolled back to SP2. Use the following query to display all the records of the customers."
},
{
"code": null,
"e": 60476,
"s": 60451,
"text": "Select * from Customer;\n"
},
{
"code": null,
"e": 60551,
"s": 60476,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 61022,
"s": 60551,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 2 | Karun | 25 | Delhi | 1500 |\n| 3 | Kaushik | 23 | Kota | 2000 |\n| 4 | Chaitanya| 25 | Mumbai | 6500 |\n| 5 | Harish | 27 | Bhopal | 8500 |\n| 6 | Kamesh | 22 | MP | 4500 |\n| 7 | Murali | 24 | Indore | 10000 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 61111,
"s": 61022,
"text": "We can release the Savepoint using the RELEASE command. Following is the generic syntax."
},
{
"code": null,
"e": 61146,
"s": 61111,
"text": "RELEASE SAVEPOINT SAVEPOINT_NAME;\n"
},
{
"code": null,
"e": 61346,
"s": 61146,
"text": "Whenever there is a need to change the name of a table or a field, change the order of fields, change the datatype of fields, or any table structure, you can achieve the same using the ALTER command."
},
{
"code": null,
"e": 61432,
"s": 61346,
"text": "Let us consider an example that explains the ALTER command using different scenarios."
},
{
"code": null,
"e": 61524,
"s": 61432,
"text": "Use the following query to create a table named testalter_tbl with the fields’ id and name."
},
{
"code": null,
"e": 61833,
"s": 61524,
"text": "//below given query is to create a table testalter_tbl table.\ncreate table testalter_tbl(id INT, name VARCHAR(10));\n\n//below given query is to verify the table structure testalter_tbl.\nSelect * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =\n 'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';\n"
},
{
"code": null,
"e": 61908,
"s": 61833,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 62383,
"s": 61908,
"text": "+------------+-------------+------------+-----------+-----------+------------+\n|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|\n+------------+-------------+------------+-----------+-----------+------------+\n| PUBLIC |TESTALTER_TBL| ID | 4 | INTEGER | 4 |\n| PUBLIC |TESTALTER_TBL| NAME | 12 | VARCHAR | 10 |\n+------------+-------------+------------+-----------+-----------+------------+\n"
},
{
"code": null,
"e": 62514,
"s": 62383,
"text": "Whenever you want to DROP an existing column from the HSQLDB table, then you can use the DROP clause along with the ALTER command."
},
{
"code": null,
"e": 62592,
"s": 62514,
"text": "Use the following query to drop a column (name) from the table testalter_tbl."
},
{
"code": null,
"e": 62630,
"s": 62592,
"text": "ALTER TABLE testalter_tbl DROP name;\n"
},
{
"code": null,
"e": 62784,
"s": 62630,
"text": "After successful execution of the above query, you can get to know if the name field is dropped from the table testalter_tbl using the following command."
},
{
"code": null,
"e": 62908,
"s": 62784,
"text": "Select * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =\n 'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';\n"
},
{
"code": null,
"e": 62985,
"s": 62908,
"text": "After execution of the above command, you will receive the following output."
},
{
"code": null,
"e": 63381,
"s": 62985,
"text": "+------------+-------------+------------+-----------+-----------+------------+\n|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|\n+------------+-------------+------------+-----------+-----------+------------+\n| PUBLIC |TESTALTER_TBL| ID | 4 | INTEGER | 4 |\n+------------+-------------+------------+-----------+-----------+------------+\n"
},
{
"code": null,
"e": 63497,
"s": 63381,
"text": "Whenever you want to add any column into the HSQLDB table, you can use the ADD clause along with the ALTER command."
},
{
"code": null,
"e": 63576,
"s": 63497,
"text": "Use the following query to add a column named NAME to the table testalter_tbl."
},
{
"code": null,
"e": 63625,
"s": 63576,
"text": "ALTER TABLE testalter_tbl ADD name VARCHAR(10);\n"
},
{
"code": null,
"e": 63775,
"s": 63625,
"text": "After successful execution of the above query, you can get to know if the name field is added to the table testalter_tbl using the following command."
},
{
"code": null,
"e": 63899,
"s": 63775,
"text": "Select * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =\n 'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';\n"
},
{
"code": null,
"e": 63974,
"s": 63899,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 64449,
"s": 63974,
"text": "+------------+-------------+------------+-----------+-----------+------------+\n|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|\n+------------+-------------+------------+-----------+-----------+------------+\n| PUBLIC |TESTALTER_TBL| ID | 4 | INTEGER | 4 |\n| PUBLIC |TESTALTER_TBL| NAME | 12 | VARCHAR | 10 |\n+------------+-------------+------------+-----------+-----------+------------+\n"
},
{
"code": null,
"e": 64578,
"s": 64449,
"text": "Whenever there is a requirement of changing the column definition, use the MODIFY or CHANGE clause along with the ALTER command."
},
{
"code": null,
"e": 64867,
"s": 64578,
"text": "Let us consider an example that will explain how to use the CHANGE clause. The table testalter_tbl contains two fields - id and name - having datatypes int and varchar respectively. Now let us try to change the datatype of id from INT to BIGINT. Following is the query to make the change."
},
{
"code": null,
"e": 64915,
"s": 64867,
"text": "ALTER TABLE testalter_tbl CHANGE id id BIGINT;\n"
},
{
"code": null,
"e": 65027,
"s": 64915,
"text": "After successful execution of the above query, the table structure can be verified using the following command."
},
{
"code": null,
"e": 65151,
"s": 65027,
"text": "Select * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =\n 'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';\n"
},
{
"code": null,
"e": 65228,
"s": 65151,
"text": "After execution of the above command, you will receive the following output."
},
{
"code": null,
"e": 65703,
"s": 65228,
"text": "+------------+-------------+------------+-----------+-----------+------------+\n|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|\n+------------+-------------+------------+-----------+-----------+------------+\n| PUBLIC |TESTALTER_TBL| ID | 4 | BIGINT | 4 |\n| PUBLIC |TESTALTER_TBL| NAME | 12 | VARCHAR | 10 |\n+------------+-------------+------------+-----------+-----------+------------+\n"
},
{
"code": null,
"e": 65891,
"s": 65703,
"text": "Now let us try to increase the size of a column NAME from 10 to 20 in the testalter_tbl table. Following is the query to achieve this using the MODIFY clause along with the ALTER command."
},
{
"code": null,
"e": 65943,
"s": 65891,
"text": "ALTER TABLE testalter_tbl MODIFY name VARCHAR(20);\n"
},
{
"code": null,
"e": 66055,
"s": 65943,
"text": "After successful execution of the above query, the table structure can be verified using the following command."
},
{
"code": null,
"e": 66179,
"s": 66055,
"text": "Select * From INFORMATION_SCHEMA.SYSTEM_COLUMNS as C Where C.TABLE_SCHEM =\n 'PUBLIC' AND C.TABLE_NAME = 'TESTALTER_TBL';\n"
},
{
"code": null,
"e": 66256,
"s": 66179,
"text": "After execution of the above command, you will receive the following output."
},
{
"code": null,
"e": 66731,
"s": 66256,
"text": "+------------+-------------+------------+-----------+-----------+------------+\n|TABLE_SCHEM | TABLE_NAME | COLUMN_NAME| DATA_TYPE | TYPE_NAME | COLUMN_SIZE|\n+------------+-------------+------------+-----------+-----------+------------+\n| PUBLIC |TESTALTER_TBL| ID | 4 | BIGINT | 4 |\n| PUBLIC |TESTALTER_TBL| NAME | 12 | VARCHAR | 20 |\n+------------+-------------+------------+-----------+-----------+------------+\n"
},
{
"code": null,
"e": 66967,
"s": 66731,
"text": "A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to the records."
},
{
"code": null,
"e": 67126,
"s": 66967,
"text": "While creating an index, it should be considered what are the columns which will be used to make SQL queries, and create one or more indexes on those columns."
},
{
"code": null,
"e": 67270,
"s": 67126,
"text": "Practically, indexes are also type of tables, which keep the primary key or the index field and a pointer to each record into the actual table."
},
{
"code": null,
"e": 67417,
"s": 67270,
"text": "The users cannot see the indexes. They are just used to speed up queries and will be used by the Database Search Engine to quickly locate records."
},
{
"code": null,
"e": 67656,
"s": 67417,
"text": "The INSERT and UPDATE statements take more time on tables having indexes, whereas SELECT statements run faster on those tables. The reason being while inserting or updating, the database needs to insert or update the index values as well."
},
{
"code": null,
"e": 67822,
"s": 67656,
"text": "You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Following is the syntax to create an Index on a table."
},
{
"code": null,
"e": 67892,
"s": 67822,
"text": "CREATE UNIQUE INDEX index_name\nON table_name (column1, column2,...);\n"
},
{
"code": null,
"e": 68013,
"s": 67892,
"text": "You can use one or more columns to create an index. For example, create an index on tutorials_tbl using tutorial_author."
},
{
"code": null,
"e": 68082,
"s": 68013,
"text": "CREATE UNIQUE INDEX AUTHOR_INDEX\nON tutorials_tbl (tutorial_author)\n"
},
{
"code": null,
"e": 68245,
"s": 68082,
"text": "You can create a simple index on a table. Just omit the UNIQUE keyword from the query to create a simple index. A simple index allows duplicate values in a table."
},
{
"code": null,
"e": 68370,
"s": 68245,
"text": "If you want to index the values in a column in a descending order, you can add the reserved word DESC after the column name."
},
{
"code": null,
"e": 68444,
"s": 68370,
"text": "CREATE UNIQUE INDEX AUTHOR_INDEX\nON tutorials_tbl (tutorial_author DESC)\n"
},
{
"code": null,
"e": 68511,
"s": 68444,
"text": "There are four types of statements for adding indexes to a table −"
},
{
"code": null,
"e": 68666,
"s": 68511,
"text": "ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL."
},
{
"code": null,
"e": 68821,
"s": 68666,
"text": "ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL."
},
{
"code": null,
"e": 69018,
"s": 68821,
"text": "ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which the values must be unique (with the exception of NULL values, which may appear multiple times)."
},
{
"code": null,
"e": 69215,
"s": 69018,
"text": "ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which the values must be unique (with the exception of NULL values, which may appear multiple times)."
},
{
"code": null,
"e": 69347,
"s": 69215,
"text": "ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once."
},
{
"code": null,
"e": 69479,
"s": 69347,
"text": "ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once."
},
{
"code": null,
"e": 69620,
"s": 69479,
"text": "ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes."
},
{
"code": null,
"e": 69761,
"s": 69620,
"text": "ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes."
},
{
"code": null,
"e": 69819,
"s": 69761,
"text": "Following is the query to add index in an existing table."
},
{
"code": null,
"e": 69861,
"s": 69819,
"text": "ALTER TABLE testalter_tbl ADD INDEX (c);\n"
},
{
"code": null,
"e": 69995,
"s": 69861,
"text": "You can drop any INDEX by using the DROP clause along with the ALTER command. Following is the query to drop the above-created index."
},
{
"code": null,
"e": 70038,
"s": 69995,
"text": "ALTER TABLE testalter_tbl DROP INDEX (c);\n"
},
{
"code": null,
"e": 70235,
"s": 70038,
"text": "You can use the SHOW INDEX command to list out all the indexes associated with a table. Vertical-format output (specified by \\G) often is useful with this statement, to avoid long line wraparound."
},
{
"code": null,
"e": 70315,
"s": 70235,
"text": "Following is the generic syntax to display the index information about a table."
},
{
"code": null,
"e": 70345,
"s": 70315,
"text": "SHOW INDEX FROM table_name\\G\n"
},
{
"code": null,
"e": 70352,
"s": 70345,
"text": " Print"
},
{
"code": null,
"e": 70363,
"s": 70352,
"text": " Add Notes"
}
] |
drag_and_drop_by_offset method - Action Chains in Selenium Python - GeeksforGeeks | 15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around drag_and_drop_by_offset method on Action Chains in Python Selenium. drag_and_drop_by_offset method holds down the left mouse button on the source element, then moves to the target offset and releases the mouse button.
Syntax –
drag_and_drop_by_offset(source, xoffset, yoffset)
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use drag_and_drop_by_offset method as an Action chain as below –
drag_and_drop_by_offset(element, 100, 200)
To demonstrate, drag_and_drop_by_offset method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # drag_and_drop_by_offset the itemaction.drag_and_drop_by_offset(element, 100, 200) # perform the operationaction.perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python | [
{
"code": null,
"e": 24770,
"s": 24742,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 25440,
"s": 24770,
"text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around drag_and_drop_by_offset method on Action Chains in Python Selenium. drag_and_drop_by_offset method holds down the left mouse button on the source element, then moves to the target offset and releases the mouse button."
},
{
"code": null,
"e": 25449,
"s": 25440,
"text": "Syntax –"
},
{
"code": null,
"e": 25499,
"s": 25449,
"text": "drag_and_drop_by_offset(source, xoffset, yoffset)"
},
{
"code": null,
"e": 25534,
"s": 25499,
"text": "source: The element to mouse down."
},
{
"code": null,
"e": 25564,
"s": 25534,
"text": "xoffset: X offset to move to."
},
{
"code": null,
"e": 25594,
"s": 25564,
"text": "yoffset: Y offset to move to."
},
{
"code": null,
"e": 25604,
"s": 25594,
"text": "Example –"
},
{
"code": "<input type =\"text\" name =\"passwd\" id =\"passwd-id\" />",
"e": 25658,
"s": 25604,
"text": null
},
{
"code": null,
"e": 25739,
"s": 25658,
"text": "To find an element one needs to use one of the locating strategies, For example,"
},
{
"code": "element = driver.find_element_by_id(\"passwd-id\")element = driver.find_element_by_name(\"passwd\")",
"e": 25835,
"s": 25739,
"text": null
},
{
"code": null,
"e": 25912,
"s": 25835,
"text": "Now one can use drag_and_drop_by_offset method as an Action chain as below –"
},
{
"code": null,
"e": 25956,
"s": 25912,
"text": "drag_and_drop_by_offset(element, 100, 200)\n"
},
{
"code": null,
"e": 26111,
"s": 25956,
"text": "To demonstrate, drag_and_drop_by_offset method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element."
},
{
"code": null,
"e": 26121,
"s": 26111,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # drag_and_drop_by_offset the itemaction.drag_and_drop_by_offset(element, 100, 200) # perform the operationaction.perform()",
"e": 26637,
"s": 26121,
"text": null
},
{
"code": null,
"e": 26646,
"s": 26637,
"text": "Output –"
},
{
"code": null,
"e": 26662,
"s": 26646,
"text": "Python-selenium"
},
{
"code": null,
"e": 26671,
"s": 26662,
"text": "selenium"
},
{
"code": null,
"e": 26678,
"s": 26671,
"text": "Python"
},
{
"code": null,
"e": 26776,
"s": 26678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26785,
"s": 26776,
"text": "Comments"
},
{
"code": null,
"e": 26798,
"s": 26785,
"text": "Old Comments"
},
{
"code": null,
"e": 26816,
"s": 26798,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26851,
"s": 26816,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26883,
"s": 26851,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26905,
"s": 26883,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26935,
"s": 26905,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26977,
"s": 26935,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27003,
"s": 26977,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27040,
"s": 27003,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27084,
"s": 27040,
"text": "Reading and Writing to text files in Python"
}
] |
Default Values Assigned to Primitive Data Types in Java - GeeksforGeeks | 29 Oct, 2021
Primitive data types are built-in data types in java and can be used directly without using any new keyword. As we know primitive data types are treated differently by java cause of which the wrapper class concept also comes into play. But here we will be entirely focussing on data types. So, in java, there are 8 primitive data types as shown in the table below with their corresponding sizes.
Now, here default values are values assigned by the compiler to the variables which are declared but not initialized or given a value. They are different according to the return type of data type which is shown below where default values assigned to variables of different primitive data types are given in the table. However, relying on such default values is not considered a good programming style.
Data Type
Default Values
Byte
0
Short
0
Int
0
Long
0
Float
0.0
Double
0.0
Boolean
false
Char
\u0000′ or null
Now as we know Initializing a variable means to give an initial value to a variable before using it. So, in order to use the default values first, declare the variable with data type and name (eg, int x, here int is the data type and x is the name of the variable), if you don’t declare the variable before using it, it would result in a compile-time error. Now to use the default value of the variable do not initialize it, i.e. do not assign a value to it.
Example 1
Java
// Java Program to Print Default Value Assigned
// to Primitive Datatype
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Global class variable
static int a;
// Main driver method
public static void main(String[] args)
{
// Trying to print the default value
// assigned to variable
System.out.println(a);
}
}
0
Output explanation:
Here ‘a‘ is a class member variable or you can say an instance variable and it will be initialized to its default value by the compiler.
Note: There would have been a problem if variable (‘a’) was not a class member as the compiler never assigns default values to an uninitialized local variable.
In this scenario, there will be an error pointing to variable ‘a‘ that variable ‘a‘ might not have been initialized yet. This is because here ‘a‘ is the main() method local variable and has to be initialized before being used. The compiler never assigns default values to an uninitialized local variable. If you haven’t initialized the variable where you have declared it, assign the variable a value before using it, or else it will result in a compile-time error.
It is as shown in the next example as shown below for a better understanding of the class variable.
Example 2
Java
// Java Program to Print Default Value Assigned
// to Primitive Datatype
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Declaring class member variable
// (inside a local scope)
int a;
// Trying to printing the default value assigned
System.out.println(a);
}
}
Output:
sweetyty
java-basics
Java-Data Types
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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": 23655,
"s": 23624,
"text": " \n29 Oct, 2021\n"
},
{
"code": null,
"e": 24051,
"s": 23655,
"text": "Primitive data types are built-in data types in java and can be used directly without using any new keyword. As we know primitive data types are treated differently by java cause of which the wrapper class concept also comes into play. But here we will be entirely focussing on data types. So, in java, there are 8 primitive data types as shown in the table below with their corresponding sizes."
},
{
"code": null,
"e": 24453,
"s": 24051,
"text": "Now, here default values are values assigned by the compiler to the variables which are declared but not initialized or given a value. They are different according to the return type of data type which is shown below where default values assigned to variables of different primitive data types are given in the table. However, relying on such default values is not considered a good programming style."
},
{
"code": null,
"e": 24463,
"s": 24453,
"text": "Data Type"
},
{
"code": null,
"e": 24478,
"s": 24463,
"text": "Default Values"
},
{
"code": null,
"e": 24483,
"s": 24478,
"text": "Byte"
},
{
"code": null,
"e": 24485,
"s": 24483,
"text": "0"
},
{
"code": null,
"e": 24491,
"s": 24485,
"text": "Short"
},
{
"code": null,
"e": 24493,
"s": 24491,
"text": "0"
},
{
"code": null,
"e": 24497,
"s": 24493,
"text": "Int"
},
{
"code": null,
"e": 24499,
"s": 24497,
"text": "0"
},
{
"code": null,
"e": 24504,
"s": 24499,
"text": "Long"
},
{
"code": null,
"e": 24506,
"s": 24504,
"text": "0"
},
{
"code": null,
"e": 24512,
"s": 24506,
"text": "Float"
},
{
"code": null,
"e": 24516,
"s": 24512,
"text": "0.0"
},
{
"code": null,
"e": 24523,
"s": 24516,
"text": "Double"
},
{
"code": null,
"e": 24527,
"s": 24523,
"text": "0.0"
},
{
"code": null,
"e": 24535,
"s": 24527,
"text": "Boolean"
},
{
"code": null,
"e": 24541,
"s": 24535,
"text": "false"
},
{
"code": null,
"e": 24546,
"s": 24541,
"text": "Char"
},
{
"code": null,
"e": 24562,
"s": 24546,
"text": "\\u0000′ or null"
},
{
"code": null,
"e": 25021,
"s": 24562,
"text": "Now as we know Initializing a variable means to give an initial value to a variable before using it. So, in order to use the default values first, declare the variable with data type and name (eg, int x, here int is the data type and x is the name of the variable), if you don’t declare the variable before using it, it would result in a compile-time error. Now to use the default value of the variable do not initialize it, i.e. do not assign a value to it."
},
{
"code": null,
"e": 25031,
"s": 25021,
"text": "Example 1"
},
{
"code": null,
"e": 25036,
"s": 25031,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program to Print Default Value Assigned \n// to Primitive Datatype \n \n// Importing input output classes \nimport java.io.*; \n \n// Main class \npublic class GFG { \n \n // Global class variable \n static int a; \n \n // Main driver method \n public static void main(String[] args) \n { \n // Trying to print the default value \n // assigned to variable \n System.out.println(a); \n } \n}\n\n\n\n\n\n",
"e": 25482,
"s": 25046,
"text": null
},
{
"code": null,
"e": 25484,
"s": 25482,
"text": "0"
},
{
"code": null,
"e": 25504,
"s": 25484,
"text": "Output explanation:"
},
{
"code": null,
"e": 25641,
"s": 25504,
"text": "Here ‘a‘ is a class member variable or you can say an instance variable and it will be initialized to its default value by the compiler."
},
{
"code": null,
"e": 25801,
"s": 25641,
"text": "Note: There would have been a problem if variable (‘a’) was not a class member as the compiler never assigns default values to an uninitialized local variable."
},
{
"code": null,
"e": 26267,
"s": 25801,
"text": "In this scenario, there will be an error pointing to variable ‘a‘ that variable ‘a‘ might not have been initialized yet. This is because here ‘a‘ is the main() method local variable and has to be initialized before being used. The compiler never assigns default values to an uninitialized local variable. If you haven’t initialized the variable where you have declared it, assign the variable a value before using it, or else it will result in a compile-time error."
},
{
"code": null,
"e": 26367,
"s": 26267,
"text": "It is as shown in the next example as shown below for a better understanding of the class variable."
},
{
"code": null,
"e": 26377,
"s": 26367,
"text": "Example 2"
},
{
"code": null,
"e": 26382,
"s": 26377,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program to Print Default Value Assigned \n// to Primitive Datatype \n \n// Main class \npublic class GFG { \n \n // Main driver method \n public static void main(String[] args) \n { \n // Declaring class member variable \n // (inside a local scope) \n int a; \n \n // Trying to printing the default value assigned \n System.out.println(a); \n } \n}\n\n\n\n\n\n",
"e": 26796,
"s": 26392,
"text": null
},
{
"code": null,
"e": 26804,
"s": 26796,
"text": "Output:"
},
{
"code": null,
"e": 26813,
"s": 26804,
"text": "sweetyty"
},
{
"code": null,
"e": 26827,
"s": 26813,
"text": "\njava-basics\n"
},
{
"code": null,
"e": 26845,
"s": 26827,
"text": "\nJava-Data Types\n"
},
{
"code": null,
"e": 26852,
"s": 26845,
"text": "\nJava\n"
},
{
"code": null,
"e": 27057,
"s": 26852,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 27087,
"s": 27057,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27102,
"s": 27087,
"text": "Stream In Java"
},
{
"code": null,
"e": 27123,
"s": 27102,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27169,
"s": 27123,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27188,
"s": 27169,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27205,
"s": 27188,
"text": "Generics in Java"
},
{
"code": null,
"e": 27248,
"s": 27205,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27264,
"s": 27248,
"text": "Strings in Java"
},
{
"code": null,
"e": 27320,
"s": 27264,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Matrix multiplication algorithm | In this section we will see how to multiply two matrices. The matrix multiplication can only be performed, if it satisfies this condition. Suppose two matrices are A and B, and their dimensions are A (m x n) and B (p x q) the resultant matrix can be found if and only if n = p. Then the order of the resultant matrix C will be (m x q).
matrixMultiply(A, B):
Assume dimension of A is (m x n), dimension of B is (p x q)
Begin
if n is not same as p, then exit
otherwise define C matrix as (m x q)
for i in range 0 to m - 1, do
for j in range 0 to q – 1, do
for k in range 0 to p, do
C[i, j] = C[i, j] + (A[i, k] * A[k, j])
done
done
done
End
Live Demo
#include<iostream>
using namespace std;
int main() {
int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;
int a[3][3] = {
{2, 4, 1},
{2, 3, 9},
{3, 1, 8}
};
int b[3][3] = {
{1, 2, 3},
{3, 6, 1},
{2, 4, 7}
};
if (c1 != r2) {
cout<<"Column of first matrix should be equal to row of second matrix";
} else {
cout<<"The first matrix is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c1; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is:"<<endl;
for(i=0; i<r2; ++i) {
for(j=0; j<c2; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j) {
product[i][j] = 0;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k) {
product[i][j]+=a[i][k]*b[k][j];
}
cout<<"Product of the two matrices is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c2; ++j)
cout<<product[i][j]<<" ";
cout<<endl;
}
}
return 0;
}
The first matrix is:
2 4 1
2 3 9
3 1 8
The second matrix is:
1 2 3
3 6 1
2 4 7
Product of the two matrices is:
16 32 17
29 58 72
22 44 66 | [
{
"code": null,
"e": 1398,
"s": 1062,
"text": "In this section we will see how to multiply two matrices. The matrix multiplication can only be performed, if it satisfies this condition. Suppose two matrices are A and B, and their dimensions are A (m x n) and B (p x q) the resultant matrix can be found if and only if n = p. Then the order of the resultant matrix C will be (m x q)."
},
{
"code": null,
"e": 1755,
"s": 1398,
"text": "matrixMultiply(A, B):\nAssume dimension of A is (m x n), dimension of B is (p x q)\nBegin\n if n is not same as p, then exit\n otherwise define C matrix as (m x q)\n for i in range 0 to m - 1, do\n for j in range 0 to q – 1, do\n for k in range 0 to p, do\n C[i, j] = C[i, j] + (A[i, k] * A[k, j])\n done\n done\n done\nEnd"
},
{
"code": null,
"e": 1766,
"s": 1755,
"text": " Live Demo"
},
{
"code": null,
"e": 2938,
"s": 1766,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;\n int a[3][3] = {\n {2, 4, 1},\n {2, 3, 9},\n {3, 1, 8}\n };\n int b[3][3] = {\n {1, 2, 3},\n {3, 6, 1},\n {2, 4, 7}\n };\n if (c1 != r2) {\n cout<<\"Column of first matrix should be equal to row of second matrix\";\n } else {\n cout<<\"The first matrix is:\"<<endl;\n for(i=0; i<r1; ++i) {\n for(j=0; j<c1; ++j)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n }\n cout<<endl;\n cout<<\"The second matrix is:\"<<endl;\n for(i=0; i<r2; ++i) {\n for(j=0; j<c2; ++j)\n cout<<b[i][j]<<\" \";\n cout<<endl;\n }\n cout<<endl;\n for(i=0; i<r1; ++i)\n for(j=0; j<c2; ++j) {\n product[i][j] = 0;\n }\n for(i=0; i<r1; ++i)\n for(j=0; j<c2; ++j)\n for(k=0; k<c1; ++k) {\n product[i][j]+=a[i][k]*b[k][j];\n }\n cout<<\"Product of the two matrices is:\"<<endl;\n for(i=0; i<r1; ++i) {\n for(j=0; j<c2; ++j)\n cout<<product[i][j]<<\" \";\n cout<<endl;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 3076,
"s": 2938,
"text": "The first matrix is:\n2 4 1\n2 3 9\n3 1 8\nThe second matrix is:\n1 2 3\n3 6 1\n2 4 7\nProduct of the two matrices is:\n16 32 17\n29 58 72\n22 44 66"
}
] |
How to match only digits in Python using Regular Expression? | The following code matches only digits in the given string using python regular expression.
import re
m = re.search(r'\d+', '5Need47forSpeed 2')
print m
<_sre.SRE_Match object at 0x0000000004B46648>
The following code finds all digits in the given string and prints them as a list
import re
m = re.findall(r'\d', '5Need47forSpeed 2')
print m
['5', '4', '7', '2'] | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "The following code matches only digits in the given string using python regular expression."
},
{
"code": null,
"e": 1215,
"s": 1154,
"text": "import re\nm = re.search(r'\\d+', '5Need47forSpeed 2')\nprint m"
},
{
"code": null,
"e": 1261,
"s": 1215,
"text": "<_sre.SRE_Match object at 0x0000000004B46648>"
},
{
"code": null,
"e": 1343,
"s": 1261,
"text": "The following code finds all digits in the given string and prints them as a list"
},
{
"code": null,
"e": 1404,
"s": 1343,
"text": "import re\nm = re.findall(r'\\d', '5Need47forSpeed 2')\nprint m"
},
{
"code": null,
"e": 1425,
"s": 1404,
"text": "['5', '4', '7', '2']"
}
] |
How to configure modal width in Bootstrap? - GeeksforGeeks | 06 Sep, 2021
Bootstrap Modal: It is a dialog window that opens inside the browser window on triggering certain events. It is a really convenient way to improve the website’s content rendering as per the requirements. In this article, we will focus on adjusting the width/height of the modal box.Method 1: Using pre-defined Bootstrap classes Bootstrap has pre-defined classes for changing modal dimension attributes to be used with the div element containing .modal-dialog. These are listed below:
Small-sized modal: .modal-sm
Medium-sized modal: .modal-md
Large-sized modal: .modal-lg
html
<!-- Small Bootstrap Modal Example --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> </head> <body> <div class="container-fluid"> <h2>Small Modal</h2> <p> Other classes mentioned above are also implemented in the same manner. </p> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#modal" > Open Small-modal </button> <!-- Modal Code --> <div class="modal fade" id="modal" role="dialog"> <div class="modal-dialog modal-sm"> <!-- .modal-sm here makes a small modal Can be replaced with '.modal-md' & '.modal-lg' --> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> × </button> <h4 class="modal-title">GeeksforGeeks</h4> </div> <div class="modal-body"> <p>GeeksforGeeks - A computer science portal for geeks</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" > Close </button> </div> </div> </div> </div> </div> </body></html>
Output:
Method 2: Using custom dimensions by tampering with default CSS attributes We can also customize the width/height of the modal by changing the CSS properties for the div containing .modal-dialog class. Below is the solution for the same. Solution:
html
<!-- Changing CSS properties for the div containing '.modal-dialog' class --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .custom { width: 600px; min-height: 400px; } </style> </head> <body> <div class="container-fluid"> <h2>Custom-sized Modal</h2> <p> We are changing CSS properties of div containing the '.modal-dialog' to do the same. </p> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#modal" > Open Custom-sized modal </button> <!-- Modal Code --> <div class="modal fade" id="modal" role="dialog"> <div class="modal-dialog"> <!-- '.custom' class added here to do the same --> <div class="modal-content custom"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> × </button> <h4 class="modal-title">GeeksforGeeks</h4> </div> <div class="modal-body"> <p>GeeksforGeeks - A computer science portal for geeks</p> </div> </div> </div> </div> </div> </body></html>
Output:
singghakshay
Bootstrap-Misc
Picked
Technical Scripter 2019
Bootstrap
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
How to keep gap between columns using Bootstrap?
Tailwind CSS vs Bootstrap
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25540,
"s": 25512,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 26026,
"s": 25540,
"text": "Bootstrap Modal: It is a dialog window that opens inside the browser window on triggering certain events. It is a really convenient way to improve the website’s content rendering as per the requirements. In this article, we will focus on adjusting the width/height of the modal box.Method 1: Using pre-defined Bootstrap classes Bootstrap has pre-defined classes for changing modal dimension attributes to be used with the div element containing .modal-dialog. These are listed below: "
},
{
"code": null,
"e": 26055,
"s": 26026,
"text": "Small-sized modal: .modal-sm"
},
{
"code": null,
"e": 26085,
"s": 26055,
"text": "Medium-sized modal: .modal-md"
},
{
"code": null,
"e": 26114,
"s": 26085,
"text": "Large-sized modal: .modal-lg"
},
{
"code": null,
"e": 26121,
"s": 26116,
"text": "html"
},
{
"code": "<!-- Small Bootstrap Modal Example --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> </head> <body> <div class=\"container-fluid\"> <h2>Small Modal</h2> <p> Other classes mentioned above are also implemented in the same manner. </p> <button type=\"button\" class=\"btn btn-success\" data-toggle=\"modal\" data-target=\"#modal\" > Open Small-modal </button> <!-- Modal Code --> <div class=\"modal fade\" id=\"modal\" role=\"dialog\"> <div class=\"modal-dialog modal-sm\"> <!-- .modal-sm here makes a small modal Can be replaced with '.modal-md' & '.modal-lg' --> <div class=\"modal-content\"> <div class=\"modal-header\"> <button type=\"button\" class=\"close\" data-dismiss=\"modal\"> × </button> <h4 class=\"modal-title\">GeeksforGeeks</h4> </div> <div class=\"modal-body\"> <p>GeeksforGeeks - A computer science portal for geeks</p> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\" > Close </button> </div> </div> </div> </div> </div> </body></html>",
"e": 27899,
"s": 26121,
"text": null
},
{
"code": null,
"e": 27909,
"s": 27899,
"text": "Output: "
},
{
"code": null,
"e": 28159,
"s": 27909,
"text": "Method 2: Using custom dimensions by tampering with default CSS attributes We can also customize the width/height of the modal by changing the CSS properties for the div containing .modal-dialog class. Below is the solution for the same. Solution: "
},
{
"code": null,
"e": 28164,
"s": 28159,
"text": "html"
},
{
"code": "<!-- Changing CSS properties for the div containing '.modal-dialog' class --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .custom { width: 600px; min-height: 400px; } </style> </head> <body> <div class=\"container-fluid\"> <h2>Custom-sized Modal</h2> <p> We are changing CSS properties of div containing the '.modal-dialog' to do the same. </p> <button type=\"button\" class=\"btn btn-success\" data-toggle=\"modal\" data-target=\"#modal\" > Open Custom-sized modal </button> <!-- Modal Code --> <div class=\"modal fade\" id=\"modal\" role=\"dialog\"> <div class=\"modal-dialog\"> <!-- '.custom' class added here to do the same --> <div class=\"modal-content custom\"> <div class=\"modal-header\"> <button type=\"button\" class=\"close\" data-dismiss=\"modal\"> × </button> <h4 class=\"modal-title\">GeeksforGeeks</h4> </div> <div class=\"modal-body\"> <p>GeeksforGeeks - A computer science portal for geeks</p> </div> </div> </div> </div> </div> </body></html>",
"e": 29844,
"s": 28164,
"text": null
},
{
"code": null,
"e": 29854,
"s": 29844,
"text": "Output: "
},
{
"code": null,
"e": 29869,
"s": 29856,
"text": "singghakshay"
},
{
"code": null,
"e": 29884,
"s": 29869,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 29891,
"s": 29884,
"text": "Picked"
},
{
"code": null,
"e": 29915,
"s": 29891,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 29925,
"s": 29915,
"text": "Bootstrap"
},
{
"code": null,
"e": 29944,
"s": 29925,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29961,
"s": 29944,
"text": "Web Technologies"
},
{
"code": null,
"e": 30059,
"s": 29961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30068,
"s": 30059,
"text": "Comments"
},
{
"code": null,
"e": 30081,
"s": 30068,
"text": "Old Comments"
},
{
"code": null,
"e": 30144,
"s": 30081,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 30185,
"s": 30144,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 30218,
"s": 30185,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 30267,
"s": 30218,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 30293,
"s": 30267,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 30335,
"s": 30293,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30368,
"s": 30335,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30430,
"s": 30368,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30473,
"s": 30430,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Interactive Distribution Plots with Plotly | by Soner Yıldırım | Towards Data Science | Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js). Plotly express is a high-level interface of plotly.py that allows us to create many interactive and informative visualizations.
In this post, we will create different types of distribution plots using plotly express. Distribution plots are very informative tools that are widely used in statistical analysis as well as in exploratory data analysis part of data science projects. As the name suggests, distribution plots show the distribution of values and give an overview about the values that are more likely to be observed, how much the values are spread out, the ranges that are more densely populated with values and so on.
We will first use a dataset that includes basic information about the courses on Coursera. The dataset is available here on Kaggle. Let’s start by reading the data into a pandas dataframe.
import numpy as npimport pandas as pdcoursera = pd.read_csv("coursera_data.csv")print(coursera.shape)coursera.head()
We need to do some data cleaning and manipulation. The “Unnamed: 0” columns is just an ID so we can drop it.
coursera.drop('Unnamed: 0', axis=1, inplace=True)
“Course_students_enrolled” column is not in a proper numerical format. For instance, 5.3k should be 5300 and so on. There are different ways to accomplish this task. What we will do is to separate the last characters and convert it to numerical values (k for thousand, m for million). Then multiply with the values to get actual enrollment numbers.
coursera['unit'] = [x.strip()[-1] for x in coursera['course_students_enrolled']]unit_values = {'k':1000, 'm':1000000}coursera.unit.replace(unit_values, inplace=True)
We also need to remove the letters “k” and “m” from the course_students_enrolled column which can be done by slicing the string to exclude the last character.
coursera['course_students_enrolled'] = coursera['course_students_enrolled'].str.slice(0, -1)
Then we can multiply these two columns to create an “enrollment” column. To be able to multiple, both columns must have a numeric data type.
coursera['course_students_enrolled'] = coursera['course_students_enrolled'].astype("float")coursera['enrollment'] = coursera['course_students_enrolled'] * coursera['unit']coursera.drop(['course_students_enrolled','unit'], axis=1, inplace=True)coursera.head()
Let’s first create a basic histogram on enrollment column. To make the plots look better, I removed the outliers whose enrollment values are more than 500k.
df = coursera[coursera.enrollment < 500000]fig = px.histogram(df, x="enrollment")fig.show()
Most of the courses have less than 100k enrollments. We can also check if course difficulty has any effect on enrollment.
fig = px.histogram(df, x="enrollment", color="course_difficulty", facet_col="course_difficulty", title="Course Enrollment Numbers")fig.show()
Beginner level courses have the most enrollment numbers and the values decreases as the difficulty increases. However, within each difficulty level, there is a similar distribution trend.
We can create a similar plot to visualize course ratings. Let’s also use the y-axis for a different purpose this time. By passing the enrollment column to y parameter, we can see the total number of enrollments in addition to the distribution of course ratings.
fig = px.histogram(df, x="course_rating", y="enrollment", color="course_difficulty", facet_col="course_difficulty", title="Course Ratings")fig.show()
We can have multiple distributions on one plot using figure factory of plotly. Numpy can be used to create synthetic variables with different distribution types.
x1 = np.random.normal(3, size=500)x2 = np.random.normal(5, size=500)
Let’s put these variables on a plot:
variables = [x1, x2]labels = ['Normal', 'Random']fig = ff.create_distplot(variables, labels, show_hist=False)fig.show()
We have two normally distributed variables with different means. The plot on the bottom is called “rug” plot which is just another way to represent distributions. The vertical lines are denser in more populated regions. We can eliminate the rug plot part by setting show_rug parameter as false.
Another way to represent distributions is boxplot. Let’s go back to the Coursera dataset and visualize enrollment numbers using a boxplot.
fig = px.box(df, y="enrollment", color="course_difficulty", title="Course Enrollment Numbers")fig.show()
Boxplot gives an idea about how spread out the values are and also points out the outliers. As we hover on boxes, we see the critical values of a boxplot which are min, first quartile, median, third quartile, upper fence, and max. If there are no outliers, then the upper fence is the max values. We are also able to see the outlier values.
We have covered basic distribution plots with plotly. Of course, this is just a little of what can be done with this amazing library. There are many other plot types that we can dynamically create with plotly. Its syntax is easy to understand as well. I will try to cover more complex plots in the upcoming posts. You can also check the plotly documentation which I think is well-documented with many different examples. Just like any other topic, the best way to get familiar with plotly is to practice. Thus, I suggest creating lots of plots to sharpen your skills.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 401,
"s": 172,
"text": "Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js). Plotly express is a high-level interface of plotly.py that allows us to create many interactive and informative visualizations."
},
{
"code": null,
"e": 902,
"s": 401,
"text": "In this post, we will create different types of distribution plots using plotly express. Distribution plots are very informative tools that are widely used in statistical analysis as well as in exploratory data analysis part of data science projects. As the name suggests, distribution plots show the distribution of values and give an overview about the values that are more likely to be observed, how much the values are spread out, the ranges that are more densely populated with values and so on."
},
{
"code": null,
"e": 1091,
"s": 902,
"text": "We will first use a dataset that includes basic information about the courses on Coursera. The dataset is available here on Kaggle. Let’s start by reading the data into a pandas dataframe."
},
{
"code": null,
"e": 1208,
"s": 1091,
"text": "import numpy as npimport pandas as pdcoursera = pd.read_csv(\"coursera_data.csv\")print(coursera.shape)coursera.head()"
},
{
"code": null,
"e": 1317,
"s": 1208,
"text": "We need to do some data cleaning and manipulation. The “Unnamed: 0” columns is just an ID so we can drop it."
},
{
"code": null,
"e": 1367,
"s": 1317,
"text": "coursera.drop('Unnamed: 0', axis=1, inplace=True)"
},
{
"code": null,
"e": 1716,
"s": 1367,
"text": "“Course_students_enrolled” column is not in a proper numerical format. For instance, 5.3k should be 5300 and so on. There are different ways to accomplish this task. What we will do is to separate the last characters and convert it to numerical values (k for thousand, m for million). Then multiply with the values to get actual enrollment numbers."
},
{
"code": null,
"e": 1882,
"s": 1716,
"text": "coursera['unit'] = [x.strip()[-1] for x in coursera['course_students_enrolled']]unit_values = {'k':1000, 'm':1000000}coursera.unit.replace(unit_values, inplace=True)"
},
{
"code": null,
"e": 2041,
"s": 1882,
"text": "We also need to remove the letters “k” and “m” from the course_students_enrolled column which can be done by slicing the string to exclude the last character."
},
{
"code": null,
"e": 2134,
"s": 2041,
"text": "coursera['course_students_enrolled'] = coursera['course_students_enrolled'].str.slice(0, -1)"
},
{
"code": null,
"e": 2275,
"s": 2134,
"text": "Then we can multiply these two columns to create an “enrollment” column. To be able to multiple, both columns must have a numeric data type."
},
{
"code": null,
"e": 2534,
"s": 2275,
"text": "coursera['course_students_enrolled'] = coursera['course_students_enrolled'].astype(\"float\")coursera['enrollment'] = coursera['course_students_enrolled'] * coursera['unit']coursera.drop(['course_students_enrolled','unit'], axis=1, inplace=True)coursera.head()"
},
{
"code": null,
"e": 2691,
"s": 2534,
"text": "Let’s first create a basic histogram on enrollment column. To make the plots look better, I removed the outliers whose enrollment values are more than 500k."
},
{
"code": null,
"e": 2783,
"s": 2691,
"text": "df = coursera[coursera.enrollment < 500000]fig = px.histogram(df, x=\"enrollment\")fig.show()"
},
{
"code": null,
"e": 2905,
"s": 2783,
"text": "Most of the courses have less than 100k enrollments. We can also check if course difficulty has any effect on enrollment."
},
{
"code": null,
"e": 3084,
"s": 2905,
"text": "fig = px.histogram(df, x=\"enrollment\", color=\"course_difficulty\", facet_col=\"course_difficulty\", title=\"Course Enrollment Numbers\")fig.show()"
},
{
"code": null,
"e": 3272,
"s": 3084,
"text": "Beginner level courses have the most enrollment numbers and the values decreases as the difficulty increases. However, within each difficulty level, there is a similar distribution trend."
},
{
"code": null,
"e": 3534,
"s": 3272,
"text": "We can create a similar plot to visualize course ratings. Let’s also use the y-axis for a different purpose this time. By passing the enrollment column to y parameter, we can see the total number of enrollments in addition to the distribution of course ratings."
},
{
"code": null,
"e": 3739,
"s": 3534,
"text": "fig = px.histogram(df, x=\"course_rating\", y=\"enrollment\", color=\"course_difficulty\", facet_col=\"course_difficulty\", title=\"Course Ratings\")fig.show()"
},
{
"code": null,
"e": 3901,
"s": 3739,
"text": "We can have multiple distributions on one plot using figure factory of plotly. Numpy can be used to create synthetic variables with different distribution types."
},
{
"code": null,
"e": 3970,
"s": 3901,
"text": "x1 = np.random.normal(3, size=500)x2 = np.random.normal(5, size=500)"
},
{
"code": null,
"e": 4007,
"s": 3970,
"text": "Let’s put these variables on a plot:"
},
{
"code": null,
"e": 4127,
"s": 4007,
"text": "variables = [x1, x2]labels = ['Normal', 'Random']fig = ff.create_distplot(variables, labels, show_hist=False)fig.show()"
},
{
"code": null,
"e": 4422,
"s": 4127,
"text": "We have two normally distributed variables with different means. The plot on the bottom is called “rug” plot which is just another way to represent distributions. The vertical lines are denser in more populated regions. We can eliminate the rug plot part by setting show_rug parameter as false."
},
{
"code": null,
"e": 4561,
"s": 4422,
"text": "Another way to represent distributions is boxplot. Let’s go back to the Coursera dataset and visualize enrollment numbers using a boxplot."
},
{
"code": null,
"e": 4692,
"s": 4561,
"text": "fig = px.box(df, y=\"enrollment\", color=\"course_difficulty\", title=\"Course Enrollment Numbers\")fig.show()"
},
{
"code": null,
"e": 5033,
"s": 4692,
"text": "Boxplot gives an idea about how spread out the values are and also points out the outliers. As we hover on boxes, we see the critical values of a boxplot which are min, first quartile, median, third quartile, upper fence, and max. If there are no outliers, then the upper fence is the max values. We are also able to see the outlier values."
},
{
"code": null,
"e": 5601,
"s": 5033,
"text": "We have covered basic distribution plots with plotly. Of course, this is just a little of what can be done with this amazing library. There are many other plot types that we can dynamically create with plotly. Its syntax is easy to understand as well. I will try to cover more complex plots in the upcoming posts. You can also check the plotly documentation which I think is well-documented with many different examples. Just like any other topic, the best way to get familiar with plotly is to practice. Thus, I suggest creating lots of plots to sharpen your skills."
}
] |
Custom Field Validations in Django Models - GeeksforGeeks | 21 Sep, 2021
This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the model itself so that you need not manipulate it elsewhere. These Validation are run when you are trying to create an instance of a model. Technically, this validation is implemented after you run ModelName.objects.create(data = data).
Syntax –
field_name = models.Field(validators = [function 1, function 2])
Illustration of validators using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options.
Python3
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_mail = models.CharField( max_length = 200, )
Now we will apply a custom validation so that the above field is validated for google mail IDs only. Create a function that accepts an argument called value. One can apply any type of operation on value now. so let us check if our function value contains @gmail.com to be validated for google mail IDs only.
Python3
from django.db import models# importing validationerrorfrom django.core.exceptions import ValidationError # creating a validator functiondef validate_geeks_mail(value): if "@gmail.com" in value: return value else: raise ValidationError("This field accepts mail id of google only") # Create your models here.class GeeksModel(models.Model): geeks_mail = models.CharField(max_length = 200)
Now let us add this function as a validator in our field. Note that one validator function can be used for multiple fields simultaneously.
Python3
from django.db import models# importing validationerrorfrom django.core.exceptions import ValidationError # creating a validator functiondef validate_geeks_mail(value): if "@gmail.com" in value: return value else: raise ValidationError("This field accepts mail id of google only") # Create your models here.class GeeksModel(models.Model): geeks_mail = models.CharField( max_length = 200, validators =[validate_geeks_mail] )
Let us try to create an instance without gmail.com and check if our validation worked or not. Note that after every change in models.py one needs to run makemigrations and migrate commands. In your browser go to http://localhost:8000/admin/geeks/geeksmodel/add/ and enter “[email protected]”.
Let us check if it gets saved in database.
So the validation worked and this field can only accept email ids ending with @gmail.com. This way one can apply any kind of custom validation on value.
sweetyty
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24221,
"s": 24193,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 24743,
"s": 24221,
"text": "This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the model itself so that you need not manipulate it elsewhere. These Validation are run when you are trying to create an instance of a model. Technically, this validation is implemented after you run ModelName.objects.create(data = data)."
},
{
"code": null,
"e": 24752,
"s": 24743,
"text": "Syntax –"
},
{
"code": null,
"e": 24818,
"s": 24752,
"text": "field_name = models.Field(validators = [function 1, function 2]) "
},
{
"code": null,
"e": 24931,
"s": 24818,
"text": "Illustration of validators using an Example. Consider a project named geeksforgeeks having an app named geeks. "
},
{
"code": null,
"e": 25019,
"s": 24931,
"text": "Refer to the following articles to check how to create a project and an app in Django. "
},
{
"code": null,
"e": 25070,
"s": 25019,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 25103,
"s": 25070,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 25232,
"s": 25103,
"text": "Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options. "
},
{
"code": null,
"e": 25240,
"s": 25232,
"text": "Python3"
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_mail = models.CharField( max_length = 200, )",
"e": 25447,
"s": 25240,
"text": null
},
{
"code": null,
"e": 25756,
"s": 25447,
"text": "Now we will apply a custom validation so that the above field is validated for google mail IDs only. Create a function that accepts an argument called value. One can apply any type of operation on value now. so let us check if our function value contains @gmail.com to be validated for google mail IDs only. "
},
{
"code": null,
"e": 25764,
"s": 25756,
"text": "Python3"
},
{
"code": "from django.db import models# importing validationerrorfrom django.core.exceptions import ValidationError # creating a validator functiondef validate_geeks_mail(value): if \"@gmail.com\" in value: return value else: raise ValidationError(\"This field accepts mail id of google only\") # Create your models here.class GeeksModel(models.Model): geeks_mail = models.CharField(max_length = 200)",
"e": 26175,
"s": 25764,
"text": null
},
{
"code": null,
"e": 26315,
"s": 26175,
"text": "Now let us add this function as a validator in our field. Note that one validator function can be used for multiple fields simultaneously. "
},
{
"code": null,
"e": 26323,
"s": 26315,
"text": "Python3"
},
{
"code": "from django.db import models# importing validationerrorfrom django.core.exceptions import ValidationError # creating a validator functiondef validate_geeks_mail(value): if \"@gmail.com\" in value: return value else: raise ValidationError(\"This field accepts mail id of google only\") # Create your models here.class GeeksModel(models.Model): geeks_mail = models.CharField( max_length = 200, validators =[validate_geeks_mail] )",
"e": 26843,
"s": 26323,
"text": null
},
{
"code": null,
"e": 27141,
"s": 26843,
"text": "Let us try to create an instance without gmail.com and check if our validation worked or not. Note that after every change in models.py one needs to run makemigrations and migrate commands. In your browser go to http://localhost:8000/admin/geeks/geeksmodel/add/ and enter “[email protected]”. "
},
{
"code": null,
"e": 27185,
"s": 27141,
"text": "Let us check if it gets saved in database. "
},
{
"code": null,
"e": 27339,
"s": 27185,
"text": "So the validation worked and this field can only accept email ids ending with @gmail.com. This way one can apply any kind of custom validation on value. "
},
{
"code": null,
"e": 27348,
"s": 27339,
"text": "sweetyty"
},
{
"code": null,
"e": 27362,
"s": 27348,
"text": "Django-models"
},
{
"code": null,
"e": 27376,
"s": 27362,
"text": "Python Django"
},
{
"code": null,
"e": 27383,
"s": 27376,
"text": "Python"
},
{
"code": null,
"e": 27481,
"s": 27383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27490,
"s": 27481,
"text": "Comments"
},
{
"code": null,
"e": 27503,
"s": 27490,
"text": "Old Comments"
},
{
"code": null,
"e": 27521,
"s": 27503,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27556,
"s": 27521,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27578,
"s": 27556,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27610,
"s": 27578,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27640,
"s": 27610,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27682,
"s": 27640,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27725,
"s": 27682,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27751,
"s": 27725,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27795,
"s": 27751,
"text": "Reading and Writing to text files in Python"
}
] |
How to calculate the sensitivity and specificity from a confusion matrix in R? | If we have a confusion matrix then the sensitivity and specificity can be calculated using confusionMatrix function of caret package. For example, if we have a contingency table named as table then we can use the code confusionMatrix(table). This will return sensitivity and specificity as well as many other metrics.
Live Demo
> x1<-sample(letters[1:4],20,replace=TRUE)
> y1<-sample(letters[1:4],20,replace=TRUE)
> table1<-table(x1,y1)
> table1
y1
x1 a b c d
a 0 0 1 0
b 0 1 2 1
c 2 2 0 2
d 3 2 1 3
Loading caret package:
> library(caret)
Finding sensitivity and specificity of table1:
> confusionMatrix(table1)
Confusion Matrix and Statistics
y1
x1 a b c d
a 0 0 1 0
b 0 1 2 1
c 2 2 0 2
d 3 2 1 3
Overall Statistics
Accuracy : 0.2
95% CI : (0.0573, 0.4366)
No Information Rate : 0.3
P-Value [Acc > NIR] : 0.8929
Kappa : -0.0774
Mcnemar's Test P-Value : NA
Statistics by Class:
Class: a Class: b Class: c Class: d
Sensitivity 0.0000 0.20 0.0000 0.5000
Specificity 0.9333 0.80 0.6250 0.5714
Pos Pred Value 0.0000 0.25 0.0000 0.3333
Neg Pred Value 0.7368 0.75 0.7143 0.7273
Prevalence 0.2500 0.25 0.2000 0.3000
Detection Rate 0.0000 0.05 0.0000 0.1500
Detection Prevalence 0.0500 0.20 0.3000 0.4500
Balanced Accuracy 0.4667 0.50 0.3125 0.5357
Live Demo
> x2<-sample(c("India","China","Croatia","Indonesia"),2000,replace=TRUE)
> y2<-sample(c("India","China","Croatia","Indonesia"),2000,replace=TRUE)
> table2<-table(x2,y2)
> table2
y2
x2 China Croatia India Indonesia
China 143 131 138 118
Croatia 118 118 123 119
India 115 132 115 132
Indonesia 107 126 124 141
> confusionMatrix(table2)
Confusion Matrix and Statistics
y2
x2 China Croatia India Indonesia
China 143 131 138 118
Croatia 118 118 123 119
India 115 132 115 132
Indonesia 107 126 124 141
Overall Statistics
Accuracy : 0.2585
95% CI : (0.2394, 0.2783)
No Information Rate : 0.255
P-Value [Acc > NIR] : 0.3680
Kappa : 0.0116
Mcnemar's Test P-Value : 0.6665
Statistics by Class:
Class: China Class: Croatia Class: India Class: Indonesia
Sensitivity 0.2961 0.2327 0.2300 0.2765
Specificity 0.7449 0.7589 0.7473 0.7604
Pos Pred Value 0.2698 0.2469 0.2328 0.2831
Neg Pred Value 0.7687 0.7444 0.7444 0.7543
Prevalence 0.2415 0.2535 0.2500 0.2550
Detection Rate 0.0715 0.0590 0.0575 0.0705
Detection Prevalence 0.2650 0.2390 0.2470 0.2490
Balanced Accuracy 0.5205 0.4958 0.4887 0.5184
> x3<-sample(c("Male","Female"),20,replace=TRUE)
> y3<-sample(c("Male","Female"),20,replace=TRUE)
> df<-data.frame(x3,y3)
> confusionMatrix(table(df$x3,df$y3))
Confusion Matrix and Statistics
Female Male
Female 3 7
Male 6 4
Accuracy : 0.35
95% CI : (0.1539, 0.5922)
No Information Rate : 0.55
P-Value [Acc > NIR] : 0.9786
Kappa : -0.3
Mcnemar's Test P-Value : 1.0000
Sensitivity : 0.3333
Specificity : 0.3636
Pos Pred Value : 0.3000
Neg Pred Value : 0.4000
Prevalence : 0.4500
Detection Rate : 0.1500
Detection Prevalence : 0.5000
Balanced Accuracy : 0.3485
'Positive' Class : Female | [
{
"code": null,
"e": 1380,
"s": 1062,
"text": "If we have a confusion matrix then the sensitivity and specificity can be calculated using confusionMatrix function of caret package. For example, if we have a contingency table named as table then we can use the code confusionMatrix(table). This will return sensitivity and specificity as well as many other metrics."
},
{
"code": null,
"e": 1390,
"s": 1380,
"text": "Live Demo"
},
{
"code": null,
"e": 1508,
"s": 1390,
"text": "> x1<-sample(letters[1:4],20,replace=TRUE)\n> y1<-sample(letters[1:4],20,replace=TRUE)\n> table1<-table(x1,y1)\n> table1"
},
{
"code": null,
"e": 1566,
"s": 1508,
"text": "y1\nx1 a b c d\n a 0 0 1 0\n b 0 1 2 1\n c 2 2 0 2\n d 3 2 1 3"
},
{
"code": null,
"e": 1589,
"s": 1566,
"text": "Loading caret package:"
},
{
"code": null,
"e": 1606,
"s": 1589,
"text": "> library(caret)"
},
{
"code": null,
"e": 1653,
"s": 1606,
"text": "Finding sensitivity and specificity of table1:"
},
{
"code": null,
"e": 1679,
"s": 1653,
"text": "> confusionMatrix(table1)"
},
{
"code": null,
"e": 1711,
"s": 1679,
"text": "Confusion Matrix and Statistics"
},
{
"code": null,
"e": 1769,
"s": 1711,
"text": "y1\nx1 a b c d\n a 0 0 1 0\n b 0 1 2 1\n c 2 2 0 2\n d 3 2 1 3"
},
{
"code": null,
"e": 1788,
"s": 1769,
"text": "Overall Statistics"
},
{
"code": null,
"e": 1930,
"s": 1788,
"text": "Accuracy : 0.2\n95% CI : (0.0573, 0.4366)\nNo Information Rate : 0.3\nP-Value [Acc > NIR] : 0.8929\n\nKappa : -0.0774\n\nMcnemar's Test P-Value : NA"
},
{
"code": null,
"e": 1951,
"s": 1930,
"text": "Statistics by Class:"
},
{
"code": null,
"e": 2314,
"s": 1951,
"text": "Class: a Class: b Class: c Class: d\nSensitivity 0.0000 0.20 0.0000 0.5000\nSpecificity 0.9333 0.80 0.6250 0.5714\nPos Pred Value 0.0000 0.25 0.0000 0.3333\nNeg Pred Value 0.7368 0.75 0.7143 0.7273\nPrevalence 0.2500 0.25 0.2000 0.3000\nDetection Rate 0.0000 0.05 0.0000 0.1500\nDetection Prevalence 0.0500 0.20 0.3000 0.4500\nBalanced Accuracy 0.4667 0.50 0.3125 0.5357"
},
{
"code": null,
"e": 2324,
"s": 2314,
"text": "Live Demo"
},
{
"code": null,
"e": 2502,
"s": 2324,
"text": "> x2<-sample(c(\"India\",\"China\",\"Croatia\",\"Indonesia\"),2000,replace=TRUE)\n> y2<-sample(c(\"India\",\"China\",\"Croatia\",\"Indonesia\"),2000,replace=TRUE)\n> table2<-table(x2,y2)\n> table2"
},
{
"code": null,
"e": 2632,
"s": 2502,
"text": "y2\nx2 China Croatia India Indonesia\nChina 143 131 138 118\nCroatia 118 118 123 119\nIndia 115 132 115 132\nIndonesia 107 126 124 141"
},
{
"code": null,
"e": 2690,
"s": 2632,
"text": "> confusionMatrix(table2)\nConfusion Matrix and Statistics"
},
{
"code": null,
"e": 2820,
"s": 2690,
"text": "y2\nx2 China Croatia India Indonesia\nChina 143 131 138 118\nCroatia 118 118 123 119\nIndia 115 132 115 132\nIndonesia 107 126 124 141"
},
{
"code": null,
"e": 2839,
"s": 2820,
"text": "Overall Statistics"
},
{
"code": null,
"e": 2989,
"s": 2839,
"text": "Accuracy : 0.2585\n95% CI : (0.2394, 0.2783)\nNo Information Rate : 0.255\nP-Value [Acc > NIR] : 0.3680\n\nKappa : 0.0116\n\nMcnemar's Test P-Value : 0.6665"
},
{
"code": null,
"e": 3010,
"s": 2989,
"text": "Statistics by Class:"
},
{
"code": null,
"e": 3411,
"s": 3010,
"text": "Class: China Class: Croatia Class: India Class: Indonesia\nSensitivity 0.2961 0.2327 0.2300 0.2765\nSpecificity 0.7449 0.7589 0.7473 0.7604\nPos Pred Value 0.2698 0.2469 0.2328 0.2831\nNeg Pred Value 0.7687 0.7444 0.7444 0.7543\nPrevalence 0.2415 0.2535 0.2500 0.2550\nDetection Rate 0.0715 0.0590 0.0575 0.0705\nDetection Prevalence 0.2650 0.2390 0.2470 0.2490\nBalanced Accuracy 0.5205 0.4958 0.4887 0.5184"
},
{
"code": null,
"e": 3603,
"s": 3411,
"text": "> x3<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\n> y3<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\n> df<-data.frame(x3,y3)\n> confusionMatrix(table(df$x3,df$y3))\nConfusion Matrix and Statistics"
},
{
"code": null,
"e": 4000,
"s": 3603,
"text": "Female Male\nFemale 3 7\nMale 6 4\n\nAccuracy : 0.35\n95% CI : (0.1539, 0.5922)\nNo Information Rate : 0.55\nP-Value [Acc > NIR] : 0.9786\n\nKappa : -0.3\n\nMcnemar's Test P-Value : 1.0000\n\nSensitivity : 0.3333\nSpecificity : 0.3636\nPos Pred Value : 0.3000\nNeg Pred Value : 0.4000\nPrevalence : 0.4500\nDetection Rate : 0.1500\nDetection Prevalence : 0.5000\nBalanced Accuracy : 0.3485\n\n'Positive' Class : Female"
}
] |
Create a circular badge with Bootstrap | Use the .badge class in Bootstrap to create a circular badge with Bootstrap.
You can try to run the following code to implement .badge 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>Blog Posts</h2>
<a href = "#">Tech <span class="badge">95</span></a><br>
<a href = "#">Entertainment <span class="badge">30</span></a><br>
<a href = "#">Research <span class="badge">9</span></a><br>
<a href = "#">Viral <span class="badge">20</span></a><br>
<a href = "#">Sport <span class="badge">105</span></a>
</div>
</body>
</html> | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "Use the .badge class in Bootstrap to create a circular badge with Bootstrap."
},
{
"code": null,
"e": 1205,
"s": 1139,
"text": "You can try to run the following code to implement .badge class −"
},
{
"code": null,
"e": 1215,
"s": 1205,
"text": "Live Demo"
},
{
"code": null,
"e": 1934,
"s": 1215,
"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>Blog Posts</h2>\n <a href = \"#\">Tech <span class=\"badge\">95</span></a><br>\n <a href = \"#\">Entertainment <span class=\"badge\">30</span></a><br>\n <a href = \"#\">Research <span class=\"badge\">9</span></a><br>\n <a href = \"#\">Viral <span class=\"badge\">20</span></a><br>\n <a href = \"#\">Sport <span class=\"badge\">105</span></a>\n </div>\n </body>\n</html>"
}
] |
What are Character Literals in C++? | A character literal is a type of literal in programming for the representation of a single character's value within the source code of a computer program.
In C++, A character literal is composed of a constant character. It is represented by the character surrounded by single quotation marks. There are two kinds of character literals −
Narrow-character literals of type char, for example 'a'
Wide-character literals of type wchar_t, for example L'a'
The character used for a character literal may be any graphic character, except for reserved characters such as newline ('\n'), backslash ('\'), single quotation mark ('), and double quotation mark ("). Reserved characters are be specified with an escape sequence. For example,
#include <iostream>
using namespace std;
int main() {
char newline = '\n';
char tab = '\t';
char backspace = '\b';
char backslash = '\\';
char nullChar = '\0';
cout << "Newline character: " << newline << "ending" << endl;
cout << "Tab character: " << tab << "ending" << endl;
cout << "Backspace character: " << backspace << "ending" << endl;
cout << "Backslash character: " << backslash << "ending" << endl;
cout << "Null character: " << nullChar << "ending" << endl;
}
This gives the output −
Newline character: ending
Tab character: ending
Backspace character: ending
Backslash character: \ending
Null character: ending | [
{
"code": null,
"e": 1217,
"s": 1062,
"text": "A character literal is a type of literal in programming for the representation of a single character's value within the source code of a computer program."
},
{
"code": null,
"e": 1399,
"s": 1217,
"text": "In C++, A character literal is composed of a constant character. It is represented by the character surrounded by single quotation marks. There are two kinds of character literals −"
},
{
"code": null,
"e": 1455,
"s": 1399,
"text": "Narrow-character literals of type char, for example 'a'"
},
{
"code": null,
"e": 1513,
"s": 1455,
"text": "Wide-character literals of type wchar_t, for example L'a'"
},
{
"code": null,
"e": 1791,
"s": 1513,
"text": "The character used for a character literal may be any graphic character, except for reserved characters such as newline ('\\n'), backslash ('\\'), single quotation mark ('), and double quotation mark (\"). Reserved characters are be specified with an escape sequence. For example,"
},
{
"code": null,
"e": 2293,
"s": 1791,
"text": "#include <iostream>\nusing namespace std;\n\nint main() {\n char newline = '\\n';\n char tab = '\\t';\n char backspace = '\\b';\n char backslash = '\\\\';\n char nullChar = '\\0';\n\n cout << \"Newline character: \" << newline << \"ending\" << endl;\n cout << \"Tab character: \" << tab << \"ending\" << endl;\n cout << \"Backspace character: \" << backspace << \"ending\" << endl;\n cout << \"Backslash character: \" << backslash << \"ending\" << endl;\n cout << \"Null character: \" << nullChar << \"ending\" << endl;\n}"
},
{
"code": null,
"e": 2317,
"s": 2293,
"text": "This gives the output −"
},
{
"code": null,
"e": 2449,
"s": 2317,
"text": "Newline character: ending\nTab character: ending\nBackspace character: ending\nBackslash character: \\ending\nNull character: ending"
}
] |
Python program to extract only the numbers from a list which have some specific digits | 22 Oct, 2020
Given Elements List, extract numbers with specific digits.
Input : test_list = [3456, 23, 128, 235, 982], dig_list = [2, 3, 5, 4] Output : [23, 235] Explanation : 2, 3 and 2, 3, 5 are in digit list, hence extracted elements.Input : test_list = [3456, 23, 28, 235, 982], dig_list = [2, 3, 5, 4, 8] Output : [23, 28, 235] Explanation : 2, 3; 2, 8 and 2, 3, 5 are in digit list, hence extracted elements.
Method #1 : Using list comprehension + all()
In this, we check for each element in number against the elements from target list to be present, if all are found in list, element is returned.
Python3
# Python3 code to demonstrate working of # Elements with specific digits# Using list comprehension + all() # initializing listtest_list = [345, 23, 128, 235, 982] # printing original listprint("The original list is : " + str(test_list)) # initializing digit list dig_list = [2, 3, 5, 4] # checking for all digits using all()res = [sub for sub in test_list if all(int(ele) in dig_list for ele in str(sub))] # printing result print("Extracted elements : " + str(res))
Output:
The original list is : [345, 23, 128, 235, 982]
Extracted elements : [345, 23, 235]
Method #2 : Using filter() + lambda + all()
In this, filtering of elements is done using filter() + lambda, all() is used to check for all the digits from other list.
Python3
# Python3 code to demonstrate working of # Elements with specific digits# Using filter() + lambda + all() # initializing listtest_list = [345, 23, 128, 235, 982] # printing original listprint("The original list is : " + str(test_list)) # initializing digit list dig_list = [2, 3, 5, 4] # filter() used to filter from logic res = list(filter(lambda sub : all(int(ele) in dig_list for ele in str(sub)), test_list)) # printing result print("Extracted elements : " + str(res))
Output:
The original list is : [345, 23, 128, 235, 982]
Extracted elements : [345, 23, 235]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Oct, 2020"
},
{
"code": null,
"e": 88,
"s": 28,
"text": "Given Elements List, extract numbers with specific digits. "
},
{
"code": null,
"e": 432,
"s": 88,
"text": "Input : test_list = [3456, 23, 128, 235, 982], dig_list = [2, 3, 5, 4] Output : [23, 235] Explanation : 2, 3 and 2, 3, 5 are in digit list, hence extracted elements.Input : test_list = [3456, 23, 28, 235, 982], dig_list = [2, 3, 5, 4, 8] Output : [23, 28, 235] Explanation : 2, 3; 2, 8 and 2, 3, 5 are in digit list, hence extracted elements. "
},
{
"code": null,
"e": 477,
"s": 432,
"text": "Method #1 : Using list comprehension + all()"
},
{
"code": null,
"e": 623,
"s": 477,
"text": "In this, we check for each element in number against the elements from target list to be present, if all are found in list, element is returned."
},
{
"code": null,
"e": 631,
"s": 623,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Elements with specific digits# Using list comprehension + all() # initializing listtest_list = [345, 23, 128, 235, 982] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing digit list dig_list = [2, 3, 5, 4] # checking for all digits using all()res = [sub for sub in test_list if all(int(ele) in dig_list for ele in str(sub))] # printing result print(\"Extracted elements : \" + str(res))",
"e": 1102,
"s": 631,
"text": null
},
{
"code": null,
"e": 1110,
"s": 1102,
"text": "Output:"
},
{
"code": null,
"e": 1194,
"s": 1110,
"text": "The original list is : [345, 23, 128, 235, 982]\nExtracted elements : [345, 23, 235]"
},
{
"code": null,
"e": 1238,
"s": 1194,
"text": "Method #2 : Using filter() + lambda + all()"
},
{
"code": null,
"e": 1361,
"s": 1238,
"text": "In this, filtering of elements is done using filter() + lambda, all() is used to check for all the digits from other list."
},
{
"code": null,
"e": 1369,
"s": 1361,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Elements with specific digits# Using filter() + lambda + all() # initializing listtest_list = [345, 23, 128, 235, 982] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing digit list dig_list = [2, 3, 5, 4] # filter() used to filter from logic res = list(filter(lambda sub : all(int(ele) in dig_list for ele in str(sub)), test_list)) # printing result print(\"Extracted elements : \" + str(res))",
"e": 1847,
"s": 1369,
"text": null
},
{
"code": null,
"e": 1855,
"s": 1847,
"text": "Output:"
},
{
"code": null,
"e": 1939,
"s": 1855,
"text": "The original list is : [345, 23, 128, 235, 982]\nExtracted elements : [345, 23, 235]"
},
{
"code": null,
"e": 1960,
"s": 1939,
"text": "Python list-programs"
},
{
"code": null,
"e": 1967,
"s": 1960,
"text": "Python"
},
{
"code": null,
"e": 1983,
"s": 1967,
"text": "Python Programs"
}
] |
Python String find() method | 08 Jul, 2022
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found then it returns -1.
Syntax:
str.find(sub, start, end)
Parameters:
sub: It is the substring that needs to be searched in the given string.
start: Starting position where the substring needs to be checked within the string.
end: End position is the index of the last value for the specified range. It is excluded while checking.
Note #1: If start and end indexes are not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search.
Returns:
Returns the lowest index of the substring if it is found in a given string. If it’s not found then it returns -1.
Note #2: The find() method is similar to index(). The only difference is find() returns -1 if the searched string is not found and index() throws an exception in this case.
Python3
word = 'geeks for geeks' # returns first occurrence of Substringresult = word.find('geeks')print("Substring 'geeks' found at index:", result) result = word.find('for')print("Substring 'for ' found at index:", result) # How to use find()if (word.find('pawan') != -1): print("Contains given substring ")else: print("Doesn't contains given substring")
Substring 'geeks' found at index: 0
Substring 'for ' found at index: 6
Doesn't contains given substring
Python3
word = 'geeks for geeks' # Substring is searched in 'eks for geeks' print(word.find('ge', 2)) # Substring is searched in 'eks for geeks' print(word.find('geeks ', 2)) # Substring is searched in 's for g' print(word.find('g', 4, 10)) # Substring is searched in 's for g' print(word.find('for ', 4, 11))
10
-1
-1
6
Explanation:
In the first statement, the output is 10 as the start value is given which is 2, so the substring is checked from the second index which is ‘eks for geeks’.
In the second statement, the start value is given as 2 and the substring is given ‘geeks’, so the index position of ‘geeks’ is 10 but due to the last value is being excluded it will only find ‘geek’ which doesn’t matches with the original string, that is why the output is -1.
In the third statement, start value=4, end value=10, and substring = ‘g’ is given, the index position from 4 will be checked for the given substring which is at position 10, which is being excluded as it is the end index.
In the fourth statement, start value =4, end value=11, and substring=’for’ is given, the index position from 4 till 11 will be checked for the given substring and the specified substring is present at index 6, so the output is obtained.
dubey._.ji
AmiyaRanjanRout
sheetal18june
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 217,
"s": 53,
"text": "Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found then it returns -1. "
},
{
"code": null,
"e": 225,
"s": 217,
"text": "Syntax:"
},
{
"code": null,
"e": 251,
"s": 225,
"text": "str.find(sub, start, end)"
},
{
"code": null,
"e": 264,
"s": 251,
"text": "Parameters: "
},
{
"code": null,
"e": 337,
"s": 264,
"text": "sub: It is the substring that needs to be searched in the given string. "
},
{
"code": null,
"e": 422,
"s": 337,
"text": "start: Starting position where the substring needs to be checked within the string. "
},
{
"code": null,
"e": 528,
"s": 422,
"text": "end: End position is the index of the last value for the specified range. It is excluded while checking. "
},
{
"code": null,
"e": 704,
"s": 528,
"text": "Note #1: If start and end indexes are not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search. "
},
{
"code": null,
"e": 714,
"s": 704,
"text": "Returns: "
},
{
"code": null,
"e": 828,
"s": 714,
"text": "Returns the lowest index of the substring if it is found in a given string. If it’s not found then it returns -1."
},
{
"code": null,
"e": 1001,
"s": 828,
"text": "Note #2: The find() method is similar to index(). The only difference is find() returns -1 if the searched string is not found and index() throws an exception in this case."
},
{
"code": null,
"e": 1009,
"s": 1001,
"text": "Python3"
},
{
"code": "word = 'geeks for geeks' # returns first occurrence of Substringresult = word.find('geeks')print(\"Substring 'geeks' found at index:\", result) result = word.find('for')print(\"Substring 'for ' found at index:\", result) # How to use find()if (word.find('pawan') != -1): print(\"Contains given substring \")else: print(\"Doesn't contains given substring\")",
"e": 1367,
"s": 1009,
"text": null
},
{
"code": null,
"e": 1472,
"s": 1367,
"text": "Substring 'geeks' found at index: 0\nSubstring 'for ' found at index: 6\nDoesn't contains given substring\n"
},
{
"code": null,
"e": 1480,
"s": 1472,
"text": "Python3"
},
{
"code": "word = 'geeks for geeks' # Substring is searched in 'eks for geeks' print(word.find('ge', 2)) # Substring is searched in 'eks for geeks' print(word.find('geeks ', 2)) # Substring is searched in 's for g' print(word.find('g', 4, 10)) # Substring is searched in 's for g' print(word.find('for ', 4, 11))",
"e": 1789,
"s": 1480,
"text": null
},
{
"code": null,
"e": 1801,
"s": 1789,
"text": "10\n-1\n-1\n6\n"
},
{
"code": null,
"e": 1814,
"s": 1801,
"text": "Explanation:"
},
{
"code": null,
"e": 1971,
"s": 1814,
"text": "In the first statement, the output is 10 as the start value is given which is 2, so the substring is checked from the second index which is ‘eks for geeks’."
},
{
"code": null,
"e": 2248,
"s": 1971,
"text": "In the second statement, the start value is given as 2 and the substring is given ‘geeks’, so the index position of ‘geeks’ is 10 but due to the last value is being excluded it will only find ‘geek’ which doesn’t matches with the original string, that is why the output is -1."
},
{
"code": null,
"e": 2470,
"s": 2248,
"text": "In the third statement, start value=4, end value=10, and substring = ‘g’ is given, the index position from 4 will be checked for the given substring which is at position 10, which is being excluded as it is the end index."
},
{
"code": null,
"e": 2707,
"s": 2470,
"text": "In the fourth statement, start value =4, end value=11, and substring=’for’ is given, the index position from 4 till 11 will be checked for the given substring and the specified substring is present at index 6, so the output is obtained."
},
{
"code": null,
"e": 2718,
"s": 2707,
"text": "dubey._.ji"
},
{
"code": null,
"e": 2734,
"s": 2718,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 2748,
"s": 2734,
"text": "sheetal18june"
},
{
"code": null,
"e": 2762,
"s": 2748,
"text": "python-string"
},
{
"code": null,
"e": 2769,
"s": 2762,
"text": "Python"
}
] |
Replace values of a DataFrame with the value of another DataFrame in Pandas | 17 Jan, 2022
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas.
It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically. This is a very rich function as it has many methods. This tutorial explains different examples of how to use these methods in practice.
Syntax: DataFrame.replace( old value, new value)
Parameters:
old value: This is old substring to be replaced.
new value: This is new substring, which would replace old substring.
Here we will create some data that we will use in further examples.
Python3
import pandas as pd # initialise data of lists.colors = {'first_set': ['99', '88', '77', '66', '55', '44', '33', '22'], 'second_set': ['1', '2', '3', '4', '5', '6', '7', '8'] } color = {'first_set': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 'second_set': ['VI', 'IN', 'BL', 'GR', 'YE', 'OR', 'RE', 'WI'] }# Calling DataFrame constructor on listdf = pd.DataFrame(colors, columns=['first_set', 'second_set'])df1 = pd.DataFrame(color, columns=['first_set', 'second_set']) # Display the Outputdisplay(df)display(df1)
Output:
Example 1: Replace the “e” value with the “88” value of first_set of a DataFrame.
Python3
# selecting old valuea = df1['first_set'][4] # selecting new valueb = df['first_set'][1] # replace values of one DataFrame# with the value of another DataFramedf1 = df1.replace(a,b) # Display the Outputdisplay(df1)
Output:
Example 2: Replace the “55” value with the “b” value of first_setof a DataFrame.
Python3
# Display the Outputdisplay(df)display(df1) # Selecting old valuea = df['first_set'][4] # Selecting new valueb = df1['first_set'][1] # replace values of one DataFrame with# the value of another DataFramedf = df.replace(a,b) # Display the Outputdisplay(df)
Output:
Example 3: Now let’s replace the ’55’ values with ‘Hello’ values under the ‘first_set’ column and the ‘VI’ values with ‘Geeks’ values under the second_set’ column of a DataFrame.
Python3
#selected valuea = df['first_set'][4]b = df1['second_set'][1] # replace values of one DataFrame with# the value of another DataFramedf = df.replace(a,'Hello') # replace values of one DataFrame with# the value of another DataFramedf1 = df1.replace(b,'Geeks') display (df)display(df1)
Output:
Example 4: Let’s now replace the whole column of one DataFrame with the column of another DataFrame.
Python3
# replace column of one DataFrame with# the column of another DataFramedf['second_set'] = df1.replace(df['first_set'],df['second_set']) display(df)
Output:
Example 5: Here, df1.first_set[df1.first_set == ’66’] = ‘DF1’ means that firstly we are finding ’66’ in first_set of df1, after that we are replacing that value (’66’) with ‘DF1’ for the same position.
Python3
# replacing value of DataFramedf1.first_set[df1.first_set == '66'] = 'DF1'df2.first_set[df2.first_set == 'g'] = 'DF2' # display updated tabledisplay(df1)display(df2)
Output:
Example 6: In this example, we had created another data frame ‘df2’ and ‘df3’ to replace the value of ‘df1’. Here the value of “df2” “df3” will be passed through the update method then it will find the matched entity present in “df1” after finding it will update the value with “df2” “df3” values. Pandas df.update() function to update the values identified the passed indexed in the given Series object.
Syntax: df.update(other)
Parameter :
other: series
Python3
import pandas as pd # Creating dataframedf1 = pd.DataFrame([["rumul", 10, 12, 10], ["rahul", 10, 11, 16], ["purvi", 18, 14, 10], ["ravi", 20, 13, 30]], columns=["Name1", "Maths", "Physics", "Chemistry"]) # setting name1 as index columndf1 = df1.set_index('Name1') display(df1) # Creating another dataframe for# replacementdf2 = pd.DataFrame( [["rahul", 1, 1]], columns=["Name2", "Maths", "Physics"]) df3 = pd.DataFrame( [["purvi", 5, 8]], columns=["Name3", "Maths", "Chemistry"]) # setting name2 and name3 as# index columndf2 = df2.set_index('Name2')df3 = df3.set_index('Name3') # update the values at the# passed indexdf1.update(df2)df1.update(df3) display(df1)
Output:
Example 7: Use of isin method to filter the df and assign the desired row values. Here we selected the common ‘Name’ to filter out data from DataFrame(df1) and DataFrame(df2) after that we replaced it with the value of ‘df2’. for example, rumul’marks are replaced with 5 to 18 marks, rahul’marks are replaced with 20 to 19 marks, etc. Pandas isin() method is used to filter data frames. This method helps in selecting rows with having a particular value in a particular column.
Syntax: DataFrame.isin(values)
Parameters:
values: iterable, Series, List, Tuple, DataFrame or dictionary.
Python3
import pandas as pd # Creating dataframedf1 = pd.DataFrame({'Name': ['rumul', 'rahul', 'ravi', 'imran'], 'Marks': [5, 20, 8, 12]}) df2 = pd.DataFrame({'Name': ['rumul', 'rahul', 'purvi', 'ravi', 'imran'], 'Marks': [18, 19, 13, 11, 15]}) display(df1)display(df2) # replace values of one DataFrame with# the value of another DataFramedf1['Marks'] = df2[df2['Name'].isin(df1['Name'])]['Marks'].values display(df1)
Output:
anikaseth98
adnanirshad158
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. "
},
{
"code": null,
"e": 517,
"s": 151,
"text": "It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically. This is a very rich function as it has many methods. This tutorial explains different examples of how to use these methods in practice."
},
{
"code": null,
"e": 566,
"s": 517,
"text": "Syntax: DataFrame.replace( old value, new value)"
},
{
"code": null,
"e": 578,
"s": 566,
"text": "Parameters:"
},
{
"code": null,
"e": 627,
"s": 578,
"text": "old value: This is old substring to be replaced."
},
{
"code": null,
"e": 696,
"s": 627,
"text": "new value: This is new substring, which would replace old substring."
},
{
"code": null,
"e": 764,
"s": 696,
"text": "Here we will create some data that we will use in further examples."
},
{
"code": null,
"e": 772,
"s": 764,
"text": "Python3"
},
{
"code": "import pandas as pd # initialise data of lists.colors = {'first_set': ['99', '88', '77', '66', '55', '44', '33', '22'], 'second_set': ['1', '2', '3', '4', '5', '6', '7', '8'] } color = {'first_set': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 'second_set': ['VI', 'IN', 'BL', 'GR', 'YE', 'OR', 'RE', 'WI'] }# Calling DataFrame constructor on listdf = pd.DataFrame(colors, columns=['first_set', 'second_set'])df1 = pd.DataFrame(color, columns=['first_set', 'second_set']) # Display the Outputdisplay(df)display(df1)",
"e": 1416,
"s": 772,
"text": null
},
{
"code": null,
"e": 1424,
"s": 1416,
"text": "Output:"
},
{
"code": null,
"e": 1507,
"s": 1424,
"text": "Example 1: Replace the “e” value with the “88” value of first_set of a DataFrame."
},
{
"code": null,
"e": 1515,
"s": 1507,
"text": "Python3"
},
{
"code": "# selecting old valuea = df1['first_set'][4] # selecting new valueb = df['first_set'][1] # replace values of one DataFrame# with the value of another DataFramedf1 = df1.replace(a,b) # Display the Outputdisplay(df1)",
"e": 1731,
"s": 1515,
"text": null
},
{
"code": null,
"e": 1739,
"s": 1731,
"text": "Output:"
},
{
"code": null,
"e": 1821,
"s": 1739,
"text": "Example 2: Replace the “55” value with the “b” value of first_setof a DataFrame."
},
{
"code": null,
"e": 1829,
"s": 1821,
"text": "Python3"
},
{
"code": "# Display the Outputdisplay(df)display(df1) # Selecting old valuea = df['first_set'][4] # Selecting new valueb = df1['first_set'][1] # replace values of one DataFrame with# the value of another DataFramedf = df.replace(a,b) # Display the Outputdisplay(df)",
"e": 2085,
"s": 1829,
"text": null
},
{
"code": null,
"e": 2093,
"s": 2085,
"text": "Output:"
},
{
"code": null,
"e": 2273,
"s": 2093,
"text": "Example 3: Now let’s replace the ’55’ values with ‘Hello’ values under the ‘first_set’ column and the ‘VI’ values with ‘Geeks’ values under the second_set’ column of a DataFrame. "
},
{
"code": null,
"e": 2281,
"s": 2273,
"text": "Python3"
},
{
"code": "#selected valuea = df['first_set'][4]b = df1['second_set'][1] # replace values of one DataFrame with# the value of another DataFramedf = df.replace(a,'Hello') # replace values of one DataFrame with# the value of another DataFramedf1 = df1.replace(b,'Geeks') display (df)display(df1)",
"e": 2565,
"s": 2281,
"text": null
},
{
"code": null,
"e": 2573,
"s": 2565,
"text": "Output:"
},
{
"code": null,
"e": 2674,
"s": 2573,
"text": "Example 4: Let’s now replace the whole column of one DataFrame with the column of another DataFrame."
},
{
"code": null,
"e": 2682,
"s": 2674,
"text": "Python3"
},
{
"code": "# replace column of one DataFrame with# the column of another DataFramedf['second_set'] = df1.replace(df['first_set'],df['second_set']) display(df)",
"e": 2830,
"s": 2682,
"text": null
},
{
"code": null,
"e": 2838,
"s": 2830,
"text": "Output:"
},
{
"code": null,
"e": 3041,
"s": 2838,
"text": " Example 5: Here, df1.first_set[df1.first_set == ’66’] = ‘DF1’ means that firstly we are finding ’66’ in first_set of df1, after that we are replacing that value (’66’) with ‘DF1’ for the same position."
},
{
"code": null,
"e": 3049,
"s": 3041,
"text": "Python3"
},
{
"code": "# replacing value of DataFramedf1.first_set[df1.first_set == '66'] = 'DF1'df2.first_set[df2.first_set == 'g'] = 'DF2' # display updated tabledisplay(df1)display(df2)",
"e": 3215,
"s": 3049,
"text": null
},
{
"code": null,
"e": 3223,
"s": 3215,
"text": "Output:"
},
{
"code": null,
"e": 3628,
"s": 3223,
"text": "Example 6: In this example, we had created another data frame ‘df2’ and ‘df3’ to replace the value of ‘df1’. Here the value of “df2” “df3” will be passed through the update method then it will find the matched entity present in “df1” after finding it will update the value with “df2” “df3” values. Pandas df.update() function to update the values identified the passed indexed in the given Series object."
},
{
"code": null,
"e": 3653,
"s": 3628,
"text": "Syntax: df.update(other)"
},
{
"code": null,
"e": 3665,
"s": 3653,
"text": "Parameter :"
},
{
"code": null,
"e": 3679,
"s": 3665,
"text": "other: series"
},
{
"code": null,
"e": 3687,
"s": 3679,
"text": "Python3"
},
{
"code": "import pandas as pd # Creating dataframedf1 = pd.DataFrame([[\"rumul\", 10, 12, 10], [\"rahul\", 10, 11, 16], [\"purvi\", 18, 14, 10], [\"ravi\", 20, 13, 30]], columns=[\"Name1\", \"Maths\", \"Physics\", \"Chemistry\"]) # setting name1 as index columndf1 = df1.set_index('Name1') display(df1) # Creating another dataframe for# replacementdf2 = pd.DataFrame( [[\"rahul\", 1, 1]], columns=[\"Name2\", \"Maths\", \"Physics\"]) df3 = pd.DataFrame( [[\"purvi\", 5, 8]], columns=[\"Name3\", \"Maths\", \"Chemistry\"]) # setting name2 and name3 as# index columndf2 = df2.set_index('Name2')df3 = df3.set_index('Name3') # update the values at the# passed indexdf1.update(df2)df1.update(df3) display(df1)",
"e": 4483,
"s": 3687,
"text": null
},
{
"code": null,
"e": 4492,
"s": 4483,
"text": "Output: "
},
{
"code": null,
"e": 4972,
"s": 4494,
"text": "Example 7: Use of isin method to filter the df and assign the desired row values. Here we selected the common ‘Name’ to filter out data from DataFrame(df1) and DataFrame(df2) after that we replaced it with the value of ‘df2’. for example, rumul’marks are replaced with 5 to 18 marks, rahul’marks are replaced with 20 to 19 marks, etc. Pandas isin() method is used to filter data frames. This method helps in selecting rows with having a particular value in a particular column."
},
{
"code": null,
"e": 5003,
"s": 4972,
"text": "Syntax: DataFrame.isin(values)"
},
{
"code": null,
"e": 5015,
"s": 5003,
"text": "Parameters:"
},
{
"code": null,
"e": 5079,
"s": 5015,
"text": "values: iterable, Series, List, Tuple, DataFrame or dictionary."
},
{
"code": null,
"e": 5087,
"s": 5079,
"text": "Python3"
},
{
"code": "import pandas as pd # Creating dataframedf1 = pd.DataFrame({'Name': ['rumul', 'rahul', 'ravi', 'imran'], 'Marks': [5, 20, 8, 12]}) df2 = pd.DataFrame({'Name': ['rumul', 'rahul', 'purvi', 'ravi', 'imran'], 'Marks': [18, 19, 13, 11, 15]}) display(df1)display(df2) # replace values of one DataFrame with# the value of another DataFramedf1['Marks'] = df2[df2['Name'].isin(df1['Name'])]['Marks'].values display(df1)",
"e": 5620,
"s": 5087,
"text": null
},
{
"code": null,
"e": 5628,
"s": 5620,
"text": "Output:"
},
{
"code": null,
"e": 5642,
"s": 5630,
"text": "anikaseth98"
},
{
"code": null,
"e": 5657,
"s": 5642,
"text": "adnanirshad158"
},
{
"code": null,
"e": 5664,
"s": 5657,
"text": "Picked"
},
{
"code": null,
"e": 5688,
"s": 5664,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 5711,
"s": 5688,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 5725,
"s": 5711,
"text": "Python-pandas"
},
{
"code": null,
"e": 5732,
"s": 5725,
"text": "Python"
},
{
"code": null,
"e": 5830,
"s": 5732,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5862,
"s": 5830,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5889,
"s": 5862,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5910,
"s": 5889,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5933,
"s": 5910,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5989,
"s": 5933,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 6020,
"s": 5989,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 6062,
"s": 6020,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 6104,
"s": 6062,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 6143,
"s": 6104,
"text": "Python | Get unique values from a list"
}
] |
How to Test Internet on Linux Using speedtest-cli? | 28 Jul, 2020
While troubleshooting your system for slow internet access, the best way to figure is to measure the internet speed first. To check Internet speed on Linux we will be using third party tool speedtest_cli. It is a simple command-line client based on python for measuring internet bandwidth using speedtest.net infrastructure.
Test Download/Upload speed in Linux: You can use this command to test the download and upload speed from the Linux command line, it is a one-time usage command:
wget -O - https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python
Install Speedtest_cli: The above command was a one-time use command, so every time you want to test you need to put a long command in. So you can Install the speedtest_cli in your system using these commands:
wget https://raw.github.com/sivel/speedtest-cli/master/speedtest.py
chmod a+rx speedtest.py
sudo mv speedtest.py /usr/local/bin/speedtest
sudo chown root:root /usr/local/bin/speedtest
Once the installation is done you can simply type “speedtest in the terminal and your results will be there
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 380,
"s": 54,
"text": "While troubleshooting your system for slow internet access, the best way to figure is to measure the internet speed first. To check Internet speed on Linux we will be using third party tool speedtest_cli. It is a simple command-line client based on python for measuring internet bandwidth using speedtest.net infrastructure. "
},
{
"code": null,
"e": 543,
"s": 380,
"text": "Test Download/Upload speed in Linux: You can use this command to test the download and upload speed from the Linux command line, it is a one-time usage command: "
},
{
"code": null,
"e": 637,
"s": 543,
"text": "wget -O - https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python\n"
},
{
"code": null,
"e": 848,
"s": 637,
"text": "Install Speedtest_cli: The above command was a one-time use command, so every time you want to test you need to put a long command in. So you can Install the speedtest_cli in your system using these commands: "
},
{
"code": null,
"e": 1033,
"s": 848,
"text": "wget https://raw.github.com/sivel/speedtest-cli/master/speedtest.py\nchmod a+rx speedtest.py\nsudo mv speedtest.py /usr/local/bin/speedtest\nsudo chown root:root /usr/local/bin/speedtest\n"
},
{
"code": null,
"e": 1145,
"s": 1035,
"text": "Once the installation is done you can simply type “speedtest in the terminal and your results will be there "
},
{
"code": null,
"e": 1156,
"s": 1145,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1254,
"s": 1156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1289,
"s": 1254,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1315,
"s": 1289,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1352,
"s": 1315,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1381,
"s": 1352,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1418,
"s": 1381,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1455,
"s": 1418,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1495,
"s": 1455,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 1529,
"s": 1495,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1568,
"s": 1529,
"text": "Introduction to Linux Operating System"
}
] |
numpy.random.poisson() in Python | 15 Jul, 2020
With the help of numpy.random.poisson() method, we can get the random samples from poisson distribution and return the random samples by using this method.
poisson distribution
Syntax : numpy.random.poisson(lam=1.0, size=None)
Return : Return the random samples as numpy array.
Example #1 :
In this example we can see that by using this numpy.random.poisson() method, we are able to get the random samples from poisson distribution by using this method.
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using poisson() methodgfg = np.random.poisson(10, 1000) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Example #2 :
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using poisson() methodgfg = np.random.poisson(4.5, 500) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "With the help of numpy.random.poisson() method, we can get the random samples from poisson distribution and return the random samples by using this method."
},
{
"code": null,
"e": 205,
"s": 184,
"text": "poisson distribution"
},
{
"code": null,
"e": 255,
"s": 205,
"text": "Syntax : numpy.random.poisson(lam=1.0, size=None)"
},
{
"code": null,
"e": 306,
"s": 255,
"text": "Return : Return the random samples as numpy array."
},
{
"code": null,
"e": 319,
"s": 306,
"text": "Example #1 :"
},
{
"code": null,
"e": 482,
"s": 319,
"text": "In this example we can see that by using this numpy.random.poisson() method, we are able to get the random samples from poisson distribution by using this method."
},
{
"code": null,
"e": 490,
"s": 482,
"text": "Python3"
},
{
"code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using poisson() methodgfg = np.random.poisson(10, 1000) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()",
"e": 681,
"s": 490,
"text": null
},
{
"code": null,
"e": 690,
"s": 681,
"text": "Output :"
},
{
"code": null,
"e": 703,
"s": 690,
"text": "Example #2 :"
},
{
"code": null,
"e": 711,
"s": 703,
"text": "Python3"
},
{
"code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using poisson() methodgfg = np.random.poisson(4.5, 500) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()",
"e": 902,
"s": 711,
"text": null
},
{
"code": null,
"e": 911,
"s": 902,
"text": "Output :"
},
{
"code": null,
"e": 931,
"s": 911,
"text": "Python numpy-Random"
},
{
"code": null,
"e": 944,
"s": 931,
"text": "Python-numpy"
},
{
"code": null,
"e": 951,
"s": 944,
"text": "Python"
}
] |
Product of given N fractions in reduced form | 23 Jun, 2022
Given the Numerator and Denominator of N fractions. The task is to find the product of N fraction and output the answer in reduced form.Examples:
Input : N = 3
num[] = { 1, 2, 5 }
den[] = { 2, 1, 6 }
Output : 5/6
Product of 1/2 * 2/1 * 5/6 is 10/12.
Reduced form of 10/12 is 5/6.
Input : N = 4
num[] = { 1, 2, 5, 9 }
den[] = { 2, 1, 6, 27 }
Output : 5/18
The idea is to find the product of Numerator in a variable, say new_num. Now, find the product of Denominator in another variable, say new_den. Now, to find the answer in Reduced form, find the Greatest Common Divisor of new_num and new_den and divide the new_num and new_den by the calculated GCD.Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find product of N// fractions in reduced form.#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Print the Product of N fraction in Reduced Form.void productReduce(int n, int num[], int den[]){ int new_num = 1, new_den = 1; // finding the product of all N // numerators and denominators. for (int i = 0; i < n; i++) { new_num *= num[i]; new_den *= den[i]; } // Finding GCD of new numerator and // denominator int GCD = gcd(new_num, new_den); // Converting into reduced form. new_num /= GCD; new_den /= GCD; cout << new_num << "/" << new_den << endl;} // Driven Programint main(){ int n = 3; int num[] = { 1, 2, 5 }; int den[] = { 2, 1, 6 }; productReduce(n, num, den); return 0;}
// Java program to find product of N// fractions in reduced form. import java.io.*; class GFG {// Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Print the Product of N fraction in// Reduced Form.static void productReduce(int n, int num[], int den[]){ int new_num = 1, new_den = 1; // finding the product of all N // numerators and denominators. for (int i = 0; i < n; i++) { new_num *= num[i]; new_den *= den[i]; } // Finding GCD of new numerator and // denominator int GCD = gcd(new_num, new_den); // Converting into reduced form. new_num /= GCD; new_den /= GCD; System.out.println(new_num + "/" +new_den);} // Driven Program public static void main (String[] args) { int n = 3; int num[] = { 1, 2, 5 }; int den[] = { 2, 1, 6 }; productReduce(n, num, den); }} //This code is contributed by vt_m.
# Python3 program to find# product of N fractions# in reduced form. # Function to return# gcd of a and bdef gcd(a, b): if (a == 0): return b; return gcd(b % a, a); # Print the Product of N# fraction in Reduced Form.def productReduce(n, num, den): new_num = 1; new_den = 1; # finding the product # of all N numerators # and denominators. for i in range(n): new_num = new_num * num[i]; new_den = new_den * den[i]; # Finding GCD of # new numerator # and denominator GCD = gcd(new_num, new_den); # Converting into # reduced form. new_num = new_num / GCD; new_den = new_den / GCD; print(int(new_num), "/", int(new_den)); # Driver Coden = 3;num = [1, 2, 5];den = [2, 1, 6];productReduce(n, num, den); # This code is contributed# by mits
// C# program to find product of N// fractions in reduced form. using System; class GFG { // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Print the Product of N fraction in // Reduced Form. static void productReduce(int n, int []num, int []den) { int new_num = 1, new_den = 1; // finding the product of all N // numerators and denominators. for (int i = 0; i < n; i++) { new_num *= num[i]; new_den *= den[i]; } // Finding GCD of new numerator and // denominator int GCD = gcd(new_num, new_den); // Converting into reduced form. new_num /= GCD; new_den /= GCD; Console.WriteLine(new_num + "/" +new_den); } // Driven Program public static void Main () { int n = 3; int []num = { 1, 2, 5 }; int []den = { 2, 1, 6 }; productReduce(n, num, den); }} //This code is contributed by vt_m.
<?php// PHP program to find product of N// fractions in reduced form. // Function to return// gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Print the Product of N// fraction in Reduced Form.function productReduce($n, $num, $den){ $new_num = 1; $new_den = 1; // finding the product of all N // numerators and denominators. for ($i = 0; $i < $n; $i++) { $new_num *= $num[$i]; $new_den *= $den[$i]; } // Finding GCD of new // numerator and denominator $GCD = gcd($new_num, $new_den); // Converting into reduced form. $new_num /= $GCD; $new_den /= $GCD; echo $new_num , "/" , $new_den ,"\n";} // Driver Code $n = 3; $num = array(1, 2, 5); $den = array(2, 1, 6); productReduce($n, $num, $den); // This code is contributed by ajit?>
<script> // JavaScript program to find product of N// fractions in reduced form. // Function to return gcd of a and bfunction gcd( a, b){ if (a == 0) return b; return gcd(b % a, a);} // Print the Product of N fraction in Reduced Form. function productReduce( n, num , den){ let new_num = 1, new_den = 1; // finding the product of all N // numerators and denominators. for (let i = 0; i < n; i++) { new_num *= num[i]; new_den *= den[i]; } // Finding GCD of new numerator and // denominator let GCD = gcd(new_num, new_den); // Converting into reduced form. new_num /= GCD; new_den /= GCD; document.write( new_num + "/" + new_den);} // Driven Program let n = 3; let num = [ 1, 2, 5 ]; let den = [ 2, 1, 6 ]; productReduce(n, num, den); // This code contributed by aashish1995 </script>
Output :
5/6
Time Complexity: O(n + log(min(a,b))) Auxiliary Space: O(log(min(a,b)))
How to avoid overflow? The above solution causes overflow for large numbers. We can avoid overflow by first finding prime factors of all numerators and denominators. Once we have found prime factors, we can cancel common prime factors.Note : When you are asked to represent the answer in form of {P \times {Q} ^ {-1}} . For these questions, first convert the numerator and denominator in reducible form P / Q as explained above. Then, find modular multiplicative inverse of Q with respect to a prime number m (Generally, 10^9 + 7) which is given in question. After finding modular multiplicative inverse of Q, multiply it with P and take modulo with given prime number m which gives us our required output.// Thanks VaiBzZk for suggesting this condition.
Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
Mithun Kumar
aashish1995
codewithrathi
Fraction
GCD-LCM
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Count all possible paths from top left to bottom right of a mXn matrix
Product of Array except itself | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 200,
"s": 52,
"text": "Given the Numerator and Denominator of N fractions. The task is to find the product of N fraction and output the answer in reduced form.Examples: "
},
{
"code": null,
"e": 442,
"s": 200,
"text": "Input : N = 3\n num[] = { 1, 2, 5 }\n den[] = { 2, 1, 6 }\nOutput : 5/6\nProduct of 1/2 * 2/1 * 5/6 is 10/12.\nReduced form of 10/12 is 5/6.\n\nInput : N = 4\n num[] = { 1, 2, 5, 9 }\n den[] = { 2, 1, 6, 27 }\nOutput : 5/18"
},
{
"code": null,
"e": 790,
"s": 444,
"text": "The idea is to find the product of Numerator in a variable, say new_num. Now, find the product of Denominator in another variable, say new_den. Now, to find the answer in Reduced form, find the Greatest Common Divisor of new_num and new_den and divide the new_num and new_den by the calculated GCD.Below is the implementation of this approach: "
},
{
"code": null,
"e": 794,
"s": 790,
"text": "C++"
},
{
"code": null,
"e": 799,
"s": 794,
"text": "Java"
},
{
"code": null,
"e": 807,
"s": 799,
"text": "Python3"
},
{
"code": null,
"e": 810,
"s": 807,
"text": "C#"
},
{
"code": null,
"e": 814,
"s": 810,
"text": "PHP"
},
{
"code": null,
"e": 825,
"s": 814,
"text": "Javascript"
},
{
"code": "// CPP program to find product of N// fractions in reduced form.#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Print the Product of N fraction in Reduced Form.void productReduce(int n, int num[], int den[]){ int new_num = 1, new_den = 1; // finding the product of all N // numerators and denominators. for (int i = 0; i < n; i++) { new_num *= num[i]; new_den *= den[i]; } // Finding GCD of new numerator and // denominator int GCD = gcd(new_num, new_den); // Converting into reduced form. new_num /= GCD; new_den /= GCD; cout << new_num << \"/\" << new_den << endl;} // Driven Programint main(){ int n = 3; int num[] = { 1, 2, 5 }; int den[] = { 2, 1, 6 }; productReduce(n, num, den); return 0;}",
"e": 1707,
"s": 825,
"text": null
},
{
"code": "// Java program to find product of N// fractions in reduced form. import java.io.*; class GFG {// Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Print the Product of N fraction in// Reduced Form.static void productReduce(int n, int num[], int den[]){ int new_num = 1, new_den = 1; // finding the product of all N // numerators and denominators. for (int i = 0; i < n; i++) { new_num *= num[i]; new_den *= den[i]; } // Finding GCD of new numerator and // denominator int GCD = gcd(new_num, new_den); // Converting into reduced form. new_num /= GCD; new_den /= GCD; System.out.println(new_num + \"/\" +new_den);} // Driven Program public static void main (String[] args) { int n = 3; int num[] = { 1, 2, 5 }; int den[] = { 2, 1, 6 }; productReduce(n, num, den); }} //This code is contributed by vt_m.",
"e": 2730,
"s": 1707,
"text": null
},
{
"code": "# Python3 program to find# product of N fractions# in reduced form. # Function to return# gcd of a and bdef gcd(a, b): if (a == 0): return b; return gcd(b % a, a); # Print the Product of N# fraction in Reduced Form.def productReduce(n, num, den): new_num = 1; new_den = 1; # finding the product # of all N numerators # and denominators. for i in range(n): new_num = new_num * num[i]; new_den = new_den * den[i]; # Finding GCD of # new numerator # and denominator GCD = gcd(new_num, new_den); # Converting into # reduced form. new_num = new_num / GCD; new_den = new_den / GCD; print(int(new_num), \"/\", int(new_den)); # Driver Coden = 3;num = [1, 2, 5];den = [2, 1, 6];productReduce(n, num, den); # This code is contributed# by mits",
"e": 3566,
"s": 2730,
"text": null
},
{
"code": "// C# program to find product of N// fractions in reduced form. using System; class GFG { // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Print the Product of N fraction in // Reduced Form. static void productReduce(int n, int []num, int []den) { int new_num = 1, new_den = 1; // finding the product of all N // numerators and denominators. for (int i = 0; i < n; i++) { new_num *= num[i]; new_den *= den[i]; } // Finding GCD of new numerator and // denominator int GCD = gcd(new_num, new_den); // Converting into reduced form. new_num /= GCD; new_den /= GCD; Console.WriteLine(new_num + \"/\" +new_den); } // Driven Program public static void Main () { int n = 3; int []num = { 1, 2, 5 }; int []den = { 2, 1, 6 }; productReduce(n, num, den); }} //This code is contributed by vt_m.",
"e": 4716,
"s": 3566,
"text": null
},
{
"code": "<?php// PHP program to find product of N// fractions in reduced form. // Function to return// gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Print the Product of N// fraction in Reduced Form.function productReduce($n, $num, $den){ $new_num = 1; $new_den = 1; // finding the product of all N // numerators and denominators. for ($i = 0; $i < $n; $i++) { $new_num *= $num[$i]; $new_den *= $den[$i]; } // Finding GCD of new // numerator and denominator $GCD = gcd($new_num, $new_den); // Converting into reduced form. $new_num /= $GCD; $new_den /= $GCD; echo $new_num , \"/\" , $new_den ,\"\\n\";} // Driver Code $n = 3; $num = array(1, 2, 5); $den = array(2, 1, 6); productReduce($n, $num, $den); // This code is contributed by ajit?>",
"e": 5573,
"s": 4716,
"text": null
},
{
"code": "<script> // JavaScript program to find product of N// fractions in reduced form. // Function to return gcd of a and bfunction gcd( a, b){ if (a == 0) return b; return gcd(b % a, a);} // Print the Product of N fraction in Reduced Form. function productReduce( n, num , den){ let new_num = 1, new_den = 1; // finding the product of all N // numerators and denominators. for (let i = 0; i < n; i++) { new_num *= num[i]; new_den *= den[i]; } // Finding GCD of new numerator and // denominator let GCD = gcd(new_num, new_den); // Converting into reduced form. new_num /= GCD; new_den /= GCD; document.write( new_num + \"/\" + new_den);} // Driven Program let n = 3; let num = [ 1, 2, 5 ]; let den = [ 2, 1, 6 ]; productReduce(n, num, den); // This code contributed by aashish1995 </script>",
"e": 6442,
"s": 5573,
"text": null
},
{
"code": null,
"e": 6453,
"s": 6442,
"text": "Output : "
},
{
"code": null,
"e": 6457,
"s": 6453,
"text": "5/6"
},
{
"code": null,
"e": 6529,
"s": 6457,
"text": "Time Complexity: O(n + log(min(a,b))) Auxiliary Space: O(log(min(a,b)))"
},
{
"code": null,
"e": 7284,
"s": 6529,
"text": "How to avoid overflow? The above solution causes overflow for large numbers. We can avoid overflow by first finding prime factors of all numerators and denominators. Once we have found prime factors, we can cancel common prime factors.Note : When you are asked to represent the answer in form of {P \\times {Q} ^ {-1}} . For these questions, first convert the numerator and denominator in reducible form P / Q as explained above. Then, find modular multiplicative inverse of Q with respect to a prime number m (Generally, 10^9 + 7) which is given in question. After finding modular multiplicative inverse of Q, multiply it with P and take modulo with given prime number m which gives us our required output.// Thanks VaiBzZk for suggesting this condition."
},
{
"code": null,
"e": 7552,
"s": 7284,
"text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 7558,
"s": 7552,
"text": "jit_t"
},
{
"code": null,
"e": 7571,
"s": 7558,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7583,
"s": 7571,
"text": "aashish1995"
},
{
"code": null,
"e": 7597,
"s": 7583,
"text": "codewithrathi"
},
{
"code": null,
"e": 7606,
"s": 7597,
"text": "Fraction"
},
{
"code": null,
"e": 7614,
"s": 7606,
"text": "GCD-LCM"
},
{
"code": null,
"e": 7627,
"s": 7614,
"text": "Mathematical"
},
{
"code": null,
"e": 7640,
"s": 7627,
"text": "Mathematical"
},
{
"code": null,
"e": 7738,
"s": 7640,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7770,
"s": 7738,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 7816,
"s": 7770,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 7860,
"s": 7816,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 7909,
"s": 7860,
"text": "Find next greater number with same set of digits"
},
{
"code": null,
"e": 7951,
"s": 7909,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 7983,
"s": 7951,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 8018,
"s": 7983,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 8043,
"s": 8018,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 8114,
"s": 8043,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
Properties of Window Object | 31 Aug, 2021
The window object is the topmost object of DOM hierarchy. It represents a browser window or frame that displays the contents of the webpage. Whenever a window appears on the screen to display the contents of document, the window object is created. The properties and methods of Window object that are commonly used are listed in the below table:
Properties of the Window Object
Purpose
To access the properties of the window object, you will specify object name followed by a period symbol (.) and the property name.
Syntax:
window.property_name
Example:
HTML
<!DOCTYPE html><html> <head> <script language="JavaScript"> function winopen() { window.open("https://www.geeksforgeeks.org") } function showstatus() { window.status = "Opening GeeksforGeeks Home page"; } </script></head> <body onload="showstatus()"> <input type="button" name="btn" value="Open GeeksforGeeks" onclick="winopen()"></body> </html>
Output:
Before Click the Button:
After Click the button:
gabaa406
JavaScript-Properties
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 374,
"s": 28,
"text": "The window object is the topmost object of DOM hierarchy. It represents a browser window or frame that displays the contents of the webpage. Whenever a window appears on the screen to display the contents of document, the window object is created. The properties and methods of Window object that are commonly used are listed in the below table:"
},
{
"code": null,
"e": 406,
"s": 374,
"text": "Properties of the Window Object"
},
{
"code": null,
"e": 414,
"s": 406,
"text": "Purpose"
},
{
"code": null,
"e": 547,
"s": 414,
"text": "To access the properties of the window object, you will specify object name followed by a period symbol (.) and the property name. "
},
{
"code": null,
"e": 555,
"s": 547,
"text": "Syntax:"
},
{
"code": null,
"e": 576,
"s": 555,
"text": "window.property_name"
},
{
"code": null,
"e": 585,
"s": 576,
"text": "Example:"
},
{
"code": null,
"e": 590,
"s": 585,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script language=\"JavaScript\"> function winopen() { window.open(\"https://www.geeksforgeeks.org\") } function showstatus() { window.status = \"Opening GeeksforGeeks Home page\"; } </script></head> <body onload=\"showstatus()\"> <input type=\"button\" name=\"btn\" value=\"Open GeeksforGeeks\" onclick=\"winopen()\"></body> </html>",
"e": 1024,
"s": 590,
"text": null
},
{
"code": null,
"e": 1032,
"s": 1024,
"text": "Output:"
},
{
"code": null,
"e": 1057,
"s": 1032,
"text": "Before Click the Button:"
},
{
"code": null,
"e": 1081,
"s": 1057,
"text": "After Click the button:"
},
{
"code": null,
"e": 1090,
"s": 1081,
"text": "gabaa406"
},
{
"code": null,
"e": 1112,
"s": 1090,
"text": "JavaScript-Properties"
},
{
"code": null,
"e": 1123,
"s": 1112,
"text": "JavaScript"
},
{
"code": null,
"e": 1140,
"s": 1123,
"text": "Web Technologies"
}
] |
Spring Boot – MongoRepository with Example | 03 Jan, 2022
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:
It allows avoiding heavy configuration of XML which is present in spring
It provides easy maintenance and creation of REST endpoints
It includes embedded Tomcat-server
Deployment is very easy, war and jar files can be easily deployed in the tomcat server
For more information please refer to this article: Introduction to Spring Boot. In this article, we are going to discuss how to use MongoRepository to manage data in a Spring Boot application.
MongoRepository is an interface provided by Spring Data in the package org.springframework.data.mongodb.repository. MongoRepository extends the PagingAndSortingRepository and QueryByExampleExecutor interfaces that further extend the CrudRepository interface. MongoRepository provides all the necessary methods which help to create a CRUD application and it also supports the custom derived query methods.
Syntax:
public interface MongoRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>
Where:
T: Domain type that repository manages (Generally the Entity/Model class name)
ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)
Illustration:
public interface BookRepo extends MongoRepository<Book, Integer> {}
Some of the most important methods that are available inside the JpaRepository are given below
Method 1: saveAll(): It saves all given entities.
Syntax:
<S extends T> List<S> saveAll(Iterable<S> entities)
Parameters: Entities, must not be null nor must they contain null.
Return Type: The saved entities; will never be null. The returned Iterable will have the same size as the Iterable passed as an argument.
Exception Thrown: IllegalArgumentException in case the given entities or one of its entities is null.
Method 2: insert(): Inserts the given entity. Assumes the instance to be new to be able to apply insertion optimizations. Use the returned instance for further operations as the save operation might have changed the entity instance completely.
Syntax:
<S extends T> S insert(S entity)
Parameters: entity – must not be null
Return Type: the saved entity
Method 3. findAll(): Returns all instances of the type.
Syntax:
Iterable<T> findAll()
Return Type: All entities
Implementation:
We will be making a Spring Boot application that manages a Book entity with MongoRepository. The data is saved in the MongoDB database. We use a RESTful controller.
Step 1: Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project.
Step 2: Add the following dependency
Spring Web
MongoDB
Lombok
DevTools
Below is the complete code for the pom.xml file.
XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.globallogic</groupId> <artifactId>spring-mongodb</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-mongodb</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
Step 3: Create 3 packages and create some classes and interfaces inside these packages as seen in the below image
model
repository
controller
Note:
Green Rounded Icon ‘I’ Buttons are Interface
Blue Rounded Icon ‘C’ Buttons are Classes
Step 4: Inside the entity package
Creating a simple POJO class inside the Book.java file.
Java
// Java Program to Illustrate Book File // Importing required classesimport lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document; // Annotations@Data@NoArgsConstructor@AllArgsConstructor@Document(collection = "Book") // Classpublic class Book { // Attributes @Id private int id; private String bookName; private String authorName;}
Step 5: Inside the repository package
Create a simple interface and name the interface as BookRepo. This interface is going to extend the MongoRepository as we have discussed above.
Java
// java Program to Illustrate BookRepo File import com.globallogic.spring.mongodb.model.Book;import org.springframework.data.mongodb.repository.MongoRepository; public interface BookRepo extends MongoRepository<Book, Integer> {}
Step 6: Inside the controller package
Inside the package create one class named as BookController.
Java
import com.globallogic.spring.mongodb.model.Book;import com.globallogic.spring.mongodb.repository.BookRepo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; import java.util.List; // Annotation @RestController // Class public class BookController { @Autowired private BookRepo repo; @PostMapping("/addBook") public String saveBook(@RequestBody Book book){ repo.save(book); return "Added Successfully"; } @GetMapping("/findAllBooks") public List<Book> getBooks() { return repo.findAll(); } @DeleteMapping("/delete/{id}") public String deleteBook(@PathVariable int id){ repo.deleteById(id); return "Deleted Successfully"; } }
Step 7: Below is the code for the application.properties file
server.port = 8989
# MongoDB Configuration
server.port:8989
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=BookStore
Step 8: Inside the MongoDB Compass
Go to your MongoDB Compass and create a Database named BookStore and inside the database create a collection named Book as seen in the below image
Now run your application and let’s test the endpoints in Postman and also refer to our MongoDB Compass.
Endpoint 1: POST – http://localhost:8989/addBook
Endpoint 2: GET – http://localhost:8989/findAllBooks
Endpoint 3: DELETE – http://localhost:8989/delete/1329
Finally, MongoDB Compass is as depicted in the below image as shown below as follows:
Java-Spring-Boot
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 502,
"s": 28,
"text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:"
},
{
"code": null,
"e": 575,
"s": 502,
"text": "It allows avoiding heavy configuration of XML which is present in spring"
},
{
"code": null,
"e": 635,
"s": 575,
"text": "It provides easy maintenance and creation of REST endpoints"
},
{
"code": null,
"e": 670,
"s": 635,
"text": "It includes embedded Tomcat-server"
},
{
"code": null,
"e": 757,
"s": 670,
"text": "Deployment is very easy, war and jar files can be easily deployed in the tomcat server"
},
{
"code": null,
"e": 950,
"s": 757,
"text": "For more information please refer to this article: Introduction to Spring Boot. In this article, we are going to discuss how to use MongoRepository to manage data in a Spring Boot application."
},
{
"code": null,
"e": 1355,
"s": 950,
"text": "MongoRepository is an interface provided by Spring Data in the package org.springframework.data.mongodb.repository. MongoRepository extends the PagingAndSortingRepository and QueryByExampleExecutor interfaces that further extend the CrudRepository interface. MongoRepository provides all the necessary methods which help to create a CRUD application and it also supports the custom derived query methods."
},
{
"code": null,
"e": 1363,
"s": 1355,
"text": "Syntax:"
},
{
"code": null,
"e": 1470,
"s": 1363,
"text": "public interface MongoRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>"
},
{
"code": null,
"e": 1477,
"s": 1470,
"text": "Where:"
},
{
"code": null,
"e": 1556,
"s": 1477,
"text": "T: Domain type that repository manages (Generally the Entity/Model class name)"
},
{
"code": null,
"e": 1701,
"s": 1556,
"text": "ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)"
},
{
"code": null,
"e": 1715,
"s": 1701,
"text": "Illustration:"
},
{
"code": null,
"e": 1783,
"s": 1715,
"text": "public interface BookRepo extends MongoRepository<Book, Integer> {}"
},
{
"code": null,
"e": 1878,
"s": 1783,
"text": "Some of the most important methods that are available inside the JpaRepository are given below"
},
{
"code": null,
"e": 1928,
"s": 1878,
"text": "Method 1: saveAll(): It saves all given entities."
},
{
"code": null,
"e": 1936,
"s": 1928,
"text": "Syntax:"
},
{
"code": null,
"e": 1988,
"s": 1936,
"text": "<S extends T> List<S> saveAll(Iterable<S> entities)"
},
{
"code": null,
"e": 2055,
"s": 1988,
"text": "Parameters: Entities, must not be null nor must they contain null."
},
{
"code": null,
"e": 2193,
"s": 2055,
"text": "Return Type: The saved entities; will never be null. The returned Iterable will have the same size as the Iterable passed as an argument."
},
{
"code": null,
"e": 2295,
"s": 2193,
"text": "Exception Thrown: IllegalArgumentException in case the given entities or one of its entities is null."
},
{
"code": null,
"e": 2540,
"s": 2295,
"text": "Method 2: insert(): Inserts the given entity. Assumes the instance to be new to be able to apply insertion optimizations. Use the returned instance for further operations as the save operation might have changed the entity instance completely. "
},
{
"code": null,
"e": 2548,
"s": 2540,
"text": "Syntax:"
},
{
"code": null,
"e": 2581,
"s": 2548,
"text": "<S extends T> S insert(S entity)"
},
{
"code": null,
"e": 2619,
"s": 2581,
"text": "Parameters: entity – must not be null"
},
{
"code": null,
"e": 2649,
"s": 2619,
"text": "Return Type: the saved entity"
},
{
"code": null,
"e": 2705,
"s": 2649,
"text": "Method 3. findAll(): Returns all instances of the type."
},
{
"code": null,
"e": 2713,
"s": 2705,
"text": "Syntax:"
},
{
"code": null,
"e": 2735,
"s": 2713,
"text": "Iterable<T> findAll()"
},
{
"code": null,
"e": 2761,
"s": 2735,
"text": "Return Type: All entities"
},
{
"code": null,
"e": 2777,
"s": 2761,
"text": "Implementation:"
},
{
"code": null,
"e": 2942,
"s": 2777,
"text": "We will be making a Spring Boot application that manages a Book entity with MongoRepository. The data is saved in the MongoDB database. We use a RESTful controller."
},
{
"code": null,
"e": 3033,
"s": 2942,
"text": "Step 1: Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project. "
},
{
"code": null,
"e": 3070,
"s": 3033,
"text": "Step 2: Add the following dependency"
},
{
"code": null,
"e": 3081,
"s": 3070,
"text": "Spring Web"
},
{
"code": null,
"e": 3089,
"s": 3081,
"text": "MongoDB"
},
{
"code": null,
"e": 3096,
"s": 3089,
"text": "Lombok"
},
{
"code": null,
"e": 3105,
"s": 3096,
"text": "DevTools"
},
{
"code": null,
"e": 3155,
"s": 3105,
"text": "Below is the complete code for the pom.xml file. "
},
{
"code": null,
"e": 3159,
"s": 3155,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.globallogic</groupId> <artifactId>spring-mongodb</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-mongodb</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>",
"e": 5459,
"s": 3159,
"text": null
},
{
"code": null,
"e": 5573,
"s": 5459,
"text": "Step 3: Create 3 packages and create some classes and interfaces inside these packages as seen in the below image"
},
{
"code": null,
"e": 5579,
"s": 5573,
"text": "model"
},
{
"code": null,
"e": 5590,
"s": 5579,
"text": "repository"
},
{
"code": null,
"e": 5601,
"s": 5590,
"text": "controller"
},
{
"code": null,
"e": 5607,
"s": 5601,
"text": "Note:"
},
{
"code": null,
"e": 5652,
"s": 5607,
"text": "Green Rounded Icon ‘I’ Buttons are Interface"
},
{
"code": null,
"e": 5694,
"s": 5652,
"text": "Blue Rounded Icon ‘C’ Buttons are Classes"
},
{
"code": null,
"e": 5728,
"s": 5694,
"text": "Step 4: Inside the entity package"
},
{
"code": null,
"e": 5784,
"s": 5728,
"text": "Creating a simple POJO class inside the Book.java file."
},
{
"code": null,
"e": 5789,
"s": 5784,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Book File // Importing required classesimport lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document; // Annotations@Data@NoArgsConstructor@AllArgsConstructor@Document(collection = \"Book\") // Classpublic class Book { // Attributes @Id private int id; private String bookName; private String authorName;}",
"e": 6274,
"s": 5789,
"text": null
},
{
"code": null,
"e": 6312,
"s": 6274,
"text": "Step 5: Inside the repository package"
},
{
"code": null,
"e": 6456,
"s": 6312,
"text": "Create a simple interface and name the interface as BookRepo. This interface is going to extend the MongoRepository as we have discussed above."
},
{
"code": null,
"e": 6461,
"s": 6456,
"text": "Java"
},
{
"code": "// java Program to Illustrate BookRepo File import com.globallogic.spring.mongodb.model.Book;import org.springframework.data.mongodb.repository.MongoRepository; public interface BookRepo extends MongoRepository<Book, Integer> {}",
"e": 6695,
"s": 6461,
"text": null
},
{
"code": null,
"e": 6733,
"s": 6695,
"text": "Step 6: Inside the controller package"
},
{
"code": null,
"e": 6794,
"s": 6733,
"text": "Inside the package create one class named as BookController."
},
{
"code": null,
"e": 6799,
"s": 6794,
"text": "Java"
},
{
"code": "import com.globallogic.spring.mongodb.model.Book;import com.globallogic.spring.mongodb.repository.BookRepo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; import java.util.List; // Annotation @RestController // Class public class BookController { @Autowired private BookRepo repo; @PostMapping(\"/addBook\") public String saveBook(@RequestBody Book book){ repo.save(book); return \"Added Successfully\"; } @GetMapping(\"/findAllBooks\") public List<Book> getBooks() { return repo.findAll(); } @DeleteMapping(\"/delete/{id}\") public String deleteBook(@PathVariable int id){ repo.deleteById(id); return \"Deleted Successfully\"; } }",
"e": 7589,
"s": 6799,
"text": null
},
{
"code": null,
"e": 7651,
"s": 7589,
"text": "Step 7: Below is the code for the application.properties file"
},
{
"code": null,
"e": 7817,
"s": 7651,
"text": "server.port = 8989\n\n# MongoDB Configuration\nserver.port:8989\nspring.data.mongodb.host=localhost\nspring.data.mongodb.port=27017\nspring.data.mongodb.database=BookStore"
},
{
"code": null,
"e": 7852,
"s": 7817,
"text": "Step 8: Inside the MongoDB Compass"
},
{
"code": null,
"e": 7999,
"s": 7852,
"text": "Go to your MongoDB Compass and create a Database named BookStore and inside the database create a collection named Book as seen in the below image"
},
{
"code": null,
"e": 8103,
"s": 7999,
"text": "Now run your application and let’s test the endpoints in Postman and also refer to our MongoDB Compass."
},
{
"code": null,
"e": 8152,
"s": 8103,
"text": "Endpoint 1: POST – http://localhost:8989/addBook"
},
{
"code": null,
"e": 8205,
"s": 8152,
"text": "Endpoint 2: GET – http://localhost:8989/findAllBooks"
},
{
"code": null,
"e": 8260,
"s": 8205,
"text": "Endpoint 3: DELETE – http://localhost:8989/delete/1329"
},
{
"code": null,
"e": 8346,
"s": 8260,
"text": "Finally, MongoDB Compass is as depicted in the below image as shown below as follows:"
},
{
"code": null,
"e": 8363,
"s": 8346,
"text": "Java-Spring-Boot"
},
{
"code": null,
"e": 8368,
"s": 8363,
"text": "Java"
},
{
"code": null,
"e": 8373,
"s": 8368,
"text": "Java"
},
{
"code": null,
"e": 8471,
"s": 8373,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8522,
"s": 8471,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 8553,
"s": 8522,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 8572,
"s": 8553,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 8602,
"s": 8572,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 8620,
"s": 8602,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 8635,
"s": 8620,
"text": "Stream In Java"
},
{
"code": null,
"e": 8655,
"s": 8635,
"text": "Collections in Java"
},
{
"code": null,
"e": 8687,
"s": 8655,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 8711,
"s": 8687,
"text": "Singleton Class in Java"
}
] |
Working with excel files using Pandas | 19 Feb, 2020
Excel sheet is one of the most ubiquitous forms of files in the IT Industry. Everyone who uses a computer at one time or the other have come across and worked with excel spreadsheets. This popularity of excel is due to its vast range of applications in the field of storing and manipulation of data in a tabular and systematic form. Moreover, excel sheets are very instinctive and user-friendly, which makes it ideal for manipulating large datasets even for less technical folks. If you are looking for places to learn to manipulate and automate stuff in excel files using Python, look no more. You are at the right place.
In this article, you will learn how to use Pandas to work with Excel spreadsheets. At the end of the article, you will have the knowledge of:
Necessary modules needed for this and how to set them up in your system.
Reading data from excel file into pandas using Python.
Exploring the data from excel files in Pandas.
Using functions to manipulate and reshape the data in Pandas.
To install pandas in Anaconda, we can use the following command in Anaconda Terminal:
conda install pandas
To install pandas in regular Python (Non-Anaconda), we can use the following command in the command prompt:
pip install pandas
First of all, we need to import the pandas module which can be done by running the command:
import pandas as pds
Input File: Let’s suppose the excel file looks like this
Sheet 1:
Sheet 2:
Now we can import the excel file using the read_excel function in pandas, as shown below:
file =('path_of_excel_file')newData = pds.read_excel(file)newData
Output:
The second statement reads the data from excel and stores it into a pandas Data Frame which is represented by the variable newData. If there are multiple sheets in the excel workbook, the command will import data of the first sheet. To make a data frame with all the sheets in the workbook, the easiest method is to create different data frames separately and then concatenate them. The read_excel method takes argument sheet_name and index_col where we can specify the sheet of which the data frame should be made of and index_col specifies the title column.
Example:
sheet1 = pds.read_excel(file, sheet_name = 0, index_col = 0) sheet2 = pds.read_excel(file, sheet_name = 1, index_col = 0) newData = pds.concat([sheet1, sheet2])
The third statement concatenates both the sheets. Now to check the whole data frame, we can simply run the following command:
newData
Output:
To view 5 columns from the top and from the bottom of the data frame, we can run the command:
newData.head()newData.tail()
Output:
This head() and tail() method also take arguments as numbers for the number of columns to show.The shape() method can be used to view the number of rows and columns in the data frame as follows:
newData.shape
Output:
If any column contains numerical data, we can sort that column using the sort_values() method in pandas as follows:
sorted_column = newData.sort_values(['Height'], ascending = False)
Now, lets suppose we want the top 5 values of the sorted column, we can use the head() method here:
sorted_column['Height'].head(5)
Output:
We can do that with any numerical column of the data frame as shown below:
newData['Weight'].head()
Output:
Now, suppose our data is mostly numerical. We can get the statistical information like mean, max, min, etc. about the data frame using the describe() method as shown below:
newData.describe()
Output:
This can also be done separately for all the numerical columns using the following command:
newData['Weight'].mean()
Output:
Other statistical information can also be calculated using the respective methods.Like in excel, formulas can also be applied and calculated columns can be created as follows:
newData['calculated_column']= newData[“Height”] + newData[“Weight”]newData['calculated_column'].head()
Output:
After operating on the data in the data frame, we can export the data back to an excel file using the method to_excel. For this we need to specify an output excel file where the transformed data is to be written, as shown below:
newData.to_excel('Output File.xlsx')
Output:
Python-pandas
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Queue in Python
Defaultdict in Python
Read a file line by line in Python
Stack in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 651,
"s": 28,
"text": "Excel sheet is one of the most ubiquitous forms of files in the IT Industry. Everyone who uses a computer at one time or the other have come across and worked with excel spreadsheets. This popularity of excel is due to its vast range of applications in the field of storing and manipulation of data in a tabular and systematic form. Moreover, excel sheets are very instinctive and user-friendly, which makes it ideal for manipulating large datasets even for less technical folks. If you are looking for places to learn to manipulate and automate stuff in excel files using Python, look no more. You are at the right place."
},
{
"code": null,
"e": 793,
"s": 651,
"text": "In this article, you will learn how to use Pandas to work with Excel spreadsheets. At the end of the article, you will have the knowledge of:"
},
{
"code": null,
"e": 866,
"s": 793,
"text": "Necessary modules needed for this and how to set them up in your system."
},
{
"code": null,
"e": 921,
"s": 866,
"text": "Reading data from excel file into pandas using Python."
},
{
"code": null,
"e": 968,
"s": 921,
"text": "Exploring the data from excel files in Pandas."
},
{
"code": null,
"e": 1030,
"s": 968,
"text": "Using functions to manipulate and reshape the data in Pandas."
},
{
"code": null,
"e": 1116,
"s": 1030,
"text": "To install pandas in Anaconda, we can use the following command in Anaconda Terminal:"
},
{
"code": null,
"e": 1138,
"s": 1116,
"text": "conda install pandas\n"
},
{
"code": null,
"e": 1246,
"s": 1138,
"text": "To install pandas in regular Python (Non-Anaconda), we can use the following command in the command prompt:"
},
{
"code": null,
"e": 1266,
"s": 1246,
"text": "pip install pandas\n"
},
{
"code": null,
"e": 1358,
"s": 1266,
"text": "First of all, we need to import the pandas module which can be done by running the command:"
},
{
"code": "import pandas as pds",
"e": 1379,
"s": 1358,
"text": null
},
{
"code": null,
"e": 1436,
"s": 1379,
"text": "Input File: Let’s suppose the excel file looks like this"
},
{
"code": null,
"e": 1445,
"s": 1436,
"text": "Sheet 1:"
},
{
"code": null,
"e": 1454,
"s": 1445,
"text": "Sheet 2:"
},
{
"code": null,
"e": 1544,
"s": 1454,
"text": "Now we can import the excel file using the read_excel function in pandas, as shown below:"
},
{
"code": "file =('path_of_excel_file')newData = pds.read_excel(file)newData",
"e": 1610,
"s": 1544,
"text": null
},
{
"code": null,
"e": 1618,
"s": 1610,
"text": "Output:"
},
{
"code": null,
"e": 2178,
"s": 1618,
"text": "The second statement reads the data from excel and stores it into a pandas Data Frame which is represented by the variable newData. If there are multiple sheets in the excel workbook, the command will import data of the first sheet. To make a data frame with all the sheets in the workbook, the easiest method is to create different data frames separately and then concatenate them. The read_excel method takes argument sheet_name and index_col where we can specify the sheet of which the data frame should be made of and index_col specifies the title column."
},
{
"code": null,
"e": 2187,
"s": 2178,
"text": "Example:"
},
{
"code": "sheet1 = pds.read_excel(file, sheet_name = 0, index_col = 0) sheet2 = pds.read_excel(file, sheet_name = 1, index_col = 0) newData = pds.concat([sheet1, sheet2])",
"e": 2446,
"s": 2187,
"text": null
},
{
"code": null,
"e": 2572,
"s": 2446,
"text": "The third statement concatenates both the sheets. Now to check the whole data frame, we can simply run the following command:"
},
{
"code": "newData",
"e": 2580,
"s": 2572,
"text": null
},
{
"code": null,
"e": 2588,
"s": 2580,
"text": "Output:"
},
{
"code": null,
"e": 2682,
"s": 2588,
"text": "To view 5 columns from the top and from the bottom of the data frame, we can run the command:"
},
{
"code": "newData.head()newData.tail()",
"e": 2711,
"s": 2682,
"text": null
},
{
"code": null,
"e": 2719,
"s": 2711,
"text": "Output:"
},
{
"code": null,
"e": 2914,
"s": 2719,
"text": "This head() and tail() method also take arguments as numbers for the number of columns to show.The shape() method can be used to view the number of rows and columns in the data frame as follows:"
},
{
"code": "newData.shape",
"e": 2928,
"s": 2914,
"text": null
},
{
"code": null,
"e": 2936,
"s": 2928,
"text": "Output:"
},
{
"code": null,
"e": 3052,
"s": 2936,
"text": "If any column contains numerical data, we can sort that column using the sort_values() method in pandas as follows:"
},
{
"code": "sorted_column = newData.sort_values(['Height'], ascending = False)",
"e": 3119,
"s": 3052,
"text": null
},
{
"code": null,
"e": 3219,
"s": 3119,
"text": "Now, lets suppose we want the top 5 values of the sorted column, we can use the head() method here:"
},
{
"code": "sorted_column['Height'].head(5)",
"e": 3251,
"s": 3219,
"text": null
},
{
"code": null,
"e": 3259,
"s": 3251,
"text": "Output:"
},
{
"code": null,
"e": 3334,
"s": 3259,
"text": "We can do that with any numerical column of the data frame as shown below:"
},
{
"code": "newData['Weight'].head()",
"e": 3359,
"s": 3334,
"text": null
},
{
"code": null,
"e": 3367,
"s": 3359,
"text": "Output:"
},
{
"code": null,
"e": 3540,
"s": 3367,
"text": "Now, suppose our data is mostly numerical. We can get the statistical information like mean, max, min, etc. about the data frame using the describe() method as shown below:"
},
{
"code": "newData.describe()",
"e": 3559,
"s": 3540,
"text": null
},
{
"code": null,
"e": 3567,
"s": 3559,
"text": "Output:"
},
{
"code": null,
"e": 3659,
"s": 3567,
"text": "This can also be done separately for all the numerical columns using the following command:"
},
{
"code": "newData['Weight'].mean()",
"e": 3684,
"s": 3659,
"text": null
},
{
"code": null,
"e": 3692,
"s": 3684,
"text": "Output:"
},
{
"code": null,
"e": 3868,
"s": 3692,
"text": "Other statistical information can also be calculated using the respective methods.Like in excel, formulas can also be applied and calculated columns can be created as follows:"
},
{
"code": "newData['calculated_column']= newData[“Height”] + newData[“Weight”]newData['calculated_column'].head()",
"e": 3971,
"s": 3868,
"text": null
},
{
"code": null,
"e": 3979,
"s": 3971,
"text": "Output:"
},
{
"code": null,
"e": 4208,
"s": 3979,
"text": "After operating on the data in the data frame, we can export the data back to an excel file using the method to_excel. For this we need to specify an output excel file where the transformed data is to be written, as shown below:"
},
{
"code": "newData.to_excel('Output File.xlsx')",
"e": 4245,
"s": 4208,
"text": null
},
{
"code": null,
"e": 4253,
"s": 4245,
"text": "Output:"
},
{
"code": null,
"e": 4267,
"s": 4253,
"text": "Python-pandas"
},
{
"code": null,
"e": 4291,
"s": 4267,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 4298,
"s": 4291,
"text": "Python"
},
{
"code": null,
"e": 4317,
"s": 4298,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4415,
"s": 4317,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4445,
"s": 4415,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4490,
"s": 4445,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 4540,
"s": 4490,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 4562,
"s": 4540,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4578,
"s": 4562,
"text": "Deque in Python"
},
{
"code": null,
"e": 4594,
"s": 4578,
"text": "Queue in Python"
},
{
"code": null,
"e": 4616,
"s": 4594,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 4651,
"s": 4616,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4667,
"s": 4651,
"text": "Stack in Python"
}
] |
ascii() in Python program | In this tutorial, we are going to learn about the ascii() function.
ascii(object) function takes one argument and returns a printable representation of the object.
Let's see some examples.
# intializing non printable characters
string = '¢'
# printing the above character using ascii(object)
print(ascii(string))
If you run the above code, you will get the following results.
'\xa2'
# intializing non printable characters
name = 'HÃFÆËŽ'
# printing the above character using ascii(object)
print(ascii(name))
If you run the above code, you will get the following results.
'H\xc3F\xc6\xcb\u017d'
# intializing non printable characters
strings = ['HÃFÆËŽ', '®', '©Òpy']
# printing the above character using ascii(object)
print(ascii(strings))
If you run the above code, you will get the following results.
['H\xc3F\xc6\xcb\u017d', '\xae', '\xa9\xd2py']
If you have any doubts in the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "In this tutorial, we are going to learn about the ascii() function."
},
{
"code": null,
"e": 1226,
"s": 1130,
"text": "ascii(object) function takes one argument and returns a printable representation of the object."
},
{
"code": null,
"e": 1251,
"s": 1226,
"text": "Let's see some examples."
},
{
"code": null,
"e": 1375,
"s": 1251,
"text": "# intializing non printable characters\nstring = '¢'\n# printing the above character using ascii(object)\nprint(ascii(string))"
},
{
"code": null,
"e": 1438,
"s": 1375,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 1446,
"s": 1438,
"text": "'\\xa2'\n"
},
{
"code": null,
"e": 1574,
"s": 1446,
"text": "# intializing non printable characters\nname = 'HÃFÆËŽ'\n# printing the above character using ascii(object)\nprint(ascii(name))"
},
{
"code": null,
"e": 1637,
"s": 1574,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 1661,
"s": 1637,
"text": "'H\\xc3F\\xc6\\xcb\\u017d'\n"
},
{
"code": null,
"e": 1811,
"s": 1661,
"text": "# intializing non printable characters\nstrings = ['HÃFÆËŽ', '®', '©Òpy']\n# printing the above character using ascii(object)\nprint(ascii(strings))"
},
{
"code": null,
"e": 1874,
"s": 1811,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 1922,
"s": 1874,
"text": "['H\\xc3F\\xc6\\xcb\\u017d', '\\xae', '\\xa9\\xd2py']\n"
},
{
"code": null,
"e": 1999,
"s": 1922,
"text": "If you have any doubts in the tutorial, mention them in the comment section."
}
] |
Sum of subset differences | Practice | GeeksforGeeks | Given an array S consisting of n numbers, find the sum of difference between last and first element of each subset.
For example for set 5,8 there are 3 subsets possible
5 (difference is 5-5 = 0 as 5 is the only last and first element)
8 (difference is 8-8 = 0 as 8 is the only last and first element)
5 8 (difference is 8-5 = 3 as 8 is the last element and 5 is the first element)
thus difference sum is 0+0+3 = 3
You are required to complete the function which returns an integer denoting the sum of difference between last and first element for each subset of array S.
Note: Elements in the subset should be in the same order as in the set S.
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains 2 lines the first line of input contains an integer N denoting the size of the array A. In the next line are N space separated values of the array A.
Output:
For each test case in a new line output will be the sum of difference between last and first element of each subset of array S.
Constraints:
1<=T<=100
1<=N<=20
1<=A[]<=1000
Example(To be used only for expected output) :
Input:
2
4
5 2 9 6
3
1 2 3
Output
21
6
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
_luffy_2 months ago
int ans=0; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { ans+= (S[j] - S[i])*pow(2,(j- i - 1)); } } return ans;
0
imaniket2 months ago
int sumDiff(int S[], int n)
{
int sum=0;
for(int i=0; i<n; i++){
for(int j=i; j<n; j++){
sum+= (S[j]-S[i])*(pow(2, j-i-1));
}
}
return sum;
}
0
ayerajkumar2 months ago
class GfG
{
int sumDiff(int S[], int n)
{
int ans=0;
for(int i=n-1; i>0; i--){
for(int j=0; j<i; j++){
ans+=(S[i]-S[j])*Math.pow(2,i-j-1);
}
}return ans;
}
}
// Subsets are: // {5}, last(s)-first(s) = 0. // {2}, last(s)-first(s) = 0. // {9}, last(s)-first(s) = 0. // {6}, last(s)-first(s) = 0. // {5,2}, last(s)-first(s) = -3. // {5,9}, last(s)-first(s) = 4. // {5,2,9}, last(s)-first(s) = 4. // {5,6}, last(s)-first(s) = 1. // {5,2,9,6}, last(s)-first(s) = 1. // {5,2,6}, last(s)-first(s) = 1. // {5,9,6}, last(s)-first(s) = 1. // {2,9}, last(s)-first(s) = 7. // {2,6}, last(s)-first(s) = 4. // {2,9,6}, last(s)-first(s) = 4. // {9,6}, last(s)-first(s) = -3.
+1
chessnoobdj4 months ago
C++
int sumDiff(int S[], int n)
{
int ans = 0;
for(int i=n-1; i>0; i--){
for(int j=0; j<i; j++)
ans += (S[i]-S[j])*pow(2, i-j-1);
}
return ans;
}
0
D Sathwik9 months ago
D Sathwik
https://uploads.disquscdn.c...
0
Tushar Sharma2 years ago
Tushar Sharma
Simplest O(n) solution || One Traversal || No Auxiliary Space || 0.01s
//By Tushar Sharma
https://ide.geeksforgeeks.o...
int sumDiff(int S[], int n){ int sum=0; for(int i=0;i<n;i++) {sum+="((pow(2,i)-1)*S[i])-((pow(2,n-i-1)-1)*S[i]);}" return="" sum;="" }="">
0
Prateek Gole2 years ago
Prateek Gole
0.01 simplest java solnhttps://uploads.disquscdn.c...
0
Prateek Gole
This comment was deleted.
0
TUSHAR RAINA5 years ago
TUSHAR RAINA
please explain any one of given test case, i am unable to understand it.
0
ASHISH KUMAR SINGH
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 1757,
"s": 238,
"text": "Given an array S consisting of n numbers, find the sum of difference between last and first element of each subset.\nFor example for set 5,8 there are 3 subsets possible\n5 (difference is 5-5 = 0 as 5 is the only last and first element)\n8 (difference is 8-8 = 0 as 8 is the only last and first element)\n5 8 (difference is 8-5 = 3 as 8 is the last element and 5 is the first element)\nthus difference sum is 0+0+3 = 3\nYou are required to complete the function which returns an integer denoting the sum of difference between last and first element for each subset of array S.\n\nNote: Elements in the subset should be in the same order as in the set S.\n\nInput:\nThe first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains 2 lines the first line of input contains an integer N denoting the size of the array A. In the next line are N space separated values of the array A.\n\nOutput:\nFor each test case in a new line output will be the sum of difference between last and first element of each subset of array S.\n\nConstraints:\n1<=T<=100\n1<=N<=20\n1<=A[]<=1000\n\nExample(To be used only for expected output) :\nInput:\n2\n4\n5 2 9 6\n3\n1 2 3 \nOutput\n21\n6\n\nNote:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1759,
"s": 1757,
"text": "0"
},
{
"code": null,
"e": 1779,
"s": 1759,
"text": "_luffy_2 months ago"
},
{
"code": null,
"e": 1929,
"s": 1779,
"text": "int ans=0; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { ans+= (S[j] - S[i])*pow(2,(j- i - 1)); } } return ans;"
},
{
"code": null,
"e": 1931,
"s": 1929,
"text": "0"
},
{
"code": null,
"e": 1952,
"s": 1931,
"text": "imaniket2 months ago"
},
{
"code": null,
"e": 2143,
"s": 1952,
"text": "int sumDiff(int S[], int n)\n{\n int sum=0;\n for(int i=0; i<n; i++){\n for(int j=i; j<n; j++){\n sum+= (S[j]-S[i])*(pow(2, j-i-1));\n }\n }\n \n return sum;\n}"
},
{
"code": null,
"e": 2145,
"s": 2143,
"text": "0"
},
{
"code": null,
"e": 2169,
"s": 2145,
"text": "ayerajkumar2 months ago"
},
{
"code": null,
"e": 2385,
"s": 2169,
"text": "class GfG\n{\n int sumDiff(int S[], int n)\n {\n\t int ans=0;\n\t for(int i=n-1; i>0; i--){\n\t for(int j=0; j<i; j++){\n\t ans+=(S[i]-S[j])*Math.pow(2,i-j-1);\n\t }\n\t }return ans;\n }\n}"
},
{
"code": null,
"e": 3083,
"s": 2385,
"text": " // Subsets are: // {5}, last(s)-first(s) = 0. // {2}, last(s)-first(s) = 0. // {9}, last(s)-first(s) = 0. // {6}, last(s)-first(s) = 0. // {5,2}, last(s)-first(s) = -3. // {5,9}, last(s)-first(s) = 4. // {5,2,9}, last(s)-first(s) = 4. // {5,6}, last(s)-first(s) = 1. // {5,2,9,6}, last(s)-first(s) = 1. // {5,2,6}, last(s)-first(s) = 1. // {5,9,6}, last(s)-first(s) = 1. // {2,9}, last(s)-first(s) = 7. // {2,6}, last(s)-first(s) = 4. // {2,9,6}, last(s)-first(s) = 4. // {9,6}, last(s)-first(s) = -3."
},
{
"code": null,
"e": 3086,
"s": 3083,
"text": "+1"
},
{
"code": null,
"e": 3110,
"s": 3086,
"text": "chessnoobdj4 months ago"
},
{
"code": null,
"e": 3114,
"s": 3110,
"text": "C++"
},
{
"code": null,
"e": 3292,
"s": 3114,
"text": "int sumDiff(int S[], int n)\n{\n int ans = 0;\n for(int i=n-1; i>0; i--){\n for(int j=0; j<i; j++)\n ans += (S[i]-S[j])*pow(2, i-j-1);\n }\n return ans;\n}"
},
{
"code": null,
"e": 3294,
"s": 3292,
"text": "0"
},
{
"code": null,
"e": 3316,
"s": 3294,
"text": "D Sathwik9 months ago"
},
{
"code": null,
"e": 3326,
"s": 3316,
"text": "D Sathwik"
},
{
"code": null,
"e": 3357,
"s": 3326,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 3359,
"s": 3357,
"text": "0"
},
{
"code": null,
"e": 3384,
"s": 3359,
"text": "Tushar Sharma2 years ago"
},
{
"code": null,
"e": 3398,
"s": 3384,
"text": "Tushar Sharma"
},
{
"code": null,
"e": 3469,
"s": 3398,
"text": "Simplest O(n) solution || One Traversal || No Auxiliary Space || 0.01s"
},
{
"code": null,
"e": 3488,
"s": 3469,
"text": "//By Tushar Sharma"
},
{
"code": null,
"e": 3519,
"s": 3488,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 3664,
"s": 3519,
"text": "int sumDiff(int S[], int n){ int sum=0; for(int i=0;i<n;i++) {sum+=\"((pow(2,i)-1)*S[i])-((pow(2,n-i-1)-1)*S[i]);}\" return=\"\" sum;=\"\" }=\"\">"
},
{
"code": null,
"e": 3666,
"s": 3664,
"text": "0"
},
{
"code": null,
"e": 3690,
"s": 3666,
"text": "Prateek Gole2 years ago"
},
{
"code": null,
"e": 3703,
"s": 3690,
"text": "Prateek Gole"
},
{
"code": null,
"e": 3757,
"s": 3703,
"text": "0.01 simplest java solnhttps://uploads.disquscdn.c..."
},
{
"code": null,
"e": 3759,
"s": 3757,
"text": "0"
},
{
"code": null,
"e": 3772,
"s": 3759,
"text": "Prateek Gole"
},
{
"code": null,
"e": 3798,
"s": 3772,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3800,
"s": 3798,
"text": "0"
},
{
"code": null,
"e": 3824,
"s": 3800,
"text": "TUSHAR RAINA5 years ago"
},
{
"code": null,
"e": 3837,
"s": 3824,
"text": "TUSHAR RAINA"
},
{
"code": null,
"e": 3910,
"s": 3837,
"text": "please explain any one of given test case, i am unable to understand it."
},
{
"code": null,
"e": 3912,
"s": 3910,
"text": "0"
},
{
"code": null,
"e": 3931,
"s": 3912,
"text": "ASHISH KUMAR SINGH"
},
{
"code": null,
"e": 3957,
"s": 3931,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4103,
"s": 3957,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4139,
"s": 4103,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4149,
"s": 4139,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4159,
"s": 4149,
"text": "\nContest\n"
},
{
"code": null,
"e": 4222,
"s": 4159,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4370,
"s": 4222,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4578,
"s": 4370,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 4684,
"s": 4578,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to use findViewById in Fragment? | This example demonstrate about How to use findViewById in Fragment
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "match_parent"
android:layout_height = "match_parent">
<LinearLayout
android:id = "@+id/linearlayout01"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:background = "#ccc"
android:layout_weight = "1"
android:orientation = "vertical">
<fragment android:name = "com.example.myapplication.FirstFragment"
android:id = "@+id/frag_1"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent" />
</LinearLayout>
<LinearLayout
android:id = "@+id/linearlayout02"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:layout_weight = "1"
android:background = "#eee"
android:orientation = "vertical">
<fragment android:name = "com.example.myapplication.SecondFragment"
android:id = "@+id/frag_2"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent" />
</LinearLayout>
</LinearLayout>
In the above code, we have taken two fragments.
Step 3 − Add the following code to src/MainActivity.java
<?xml version = "1.0" encoding = "utf-8"?>
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Step 4 − Add the following code to src/ FirstFragment.java
<?xml version = "1.0" encoding = "utf-8"?>
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment, null);
TextView but = (TextView) root.findViewById(R.id.text);
return root;
}
}
Step 4 − Add the following code to src/ SecondFragment.java
<?xml version = "1.0" encoding = "utf-8"?>
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment {
TextView textView;
View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment, container, false);
return view;
}
}
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 –
Click here to download the project code | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "This example demonstrate about How to use findViewById in Fragment"
},
{
"code": null,
"e": 1258,
"s": 1129,
"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": 1323,
"s": 1258,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2532,
"s": 1323,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:orientation = \"vertical\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\">\n <LinearLayout\n android:id = \"@+id/linearlayout01\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\"\n android:background = \"#ccc\"\n android:layout_weight = \"1\"\n android:orientation = \"vertical\">\n <fragment android:name = \"com.example.myapplication.FirstFragment\"\n android:id = \"@+id/frag_1\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\" />\n </LinearLayout>\n <LinearLayout\n android:id = \"@+id/linearlayout02\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\"\n android:layout_weight = \"1\"\n android:background = \"#eee\"\n android:orientation = \"vertical\">\n <fragment android:name = \"com.example.myapplication.SecondFragment\"\n android:id = \"@+id/frag_2\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\" />\n </LinearLayout>\n</LinearLayout>"
},
{
"code": null,
"e": 2580,
"s": 2532,
"text": "In the above code, we have taken two fragments."
},
{
"code": null,
"e": 2637,
"s": 2580,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2968,
"s": 2637,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\nimport android.os.Bundle;\nimport android.support.v4.app.FragmentActivity;\npublic class MainActivity extends FragmentActivity {\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}"
},
{
"code": null,
"e": 3027,
"s": 2968,
"text": "Step 4 − Add the following code to src/ FirstFragment.java"
},
{
"code": null,
"e": 3589,
"s": 3027,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\nimport android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\npublic class FirstFragment extends Fragment {\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment, null);\n TextView but = (TextView) root.findViewById(R.id.text);\n return root;\n }\n}"
},
{
"code": null,
"e": 3649,
"s": 3589,
"text": "Step 4 − Add the following code to src/ SecondFragment.java"
},
{
"code": null,
"e": 4305,
"s": 3649,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\npublic class SecondFragment extends Fragment {\n TextView textView;\n View view;\n @Nullable\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n view = inflater.inflate(R.layout.fragment, container, false);\n return view;\n }\n}"
},
{
"code": null,
"e": 4652,
"s": 4305,
"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": 4692,
"s": 4652,
"text": "Click here to download the project code"
}
] |
JavaScript - Array join() Method | Javascript array join() method joins all the elements of an array into a string.
Its syntax is as follows −
array.join(separator);
separator − Specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma.
Returns a string after joining all the array elements.
Try the following example.
<html>
<head>
<title>JavaScript Array join Method</title>
</head>
<body>
<script type = "text/javascript">
var arr = new Array("First","Second","Third");
var str = arr.join();
document.write("str : " + str );
var str = arr.join(", ");
document.write("<br />str : " + str );
var str = arr.join(" + ");
document.write("<br />str : " + str );
</script>
</body>
</html>
str : First,Second,Third
str : First, Second, Third
str : First + Second + Third
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2547,
"s": 2466,
"text": "Javascript array join() method joins all the elements of an array into a string."
},
{
"code": null,
"e": 2574,
"s": 2547,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2598,
"s": 2574,
"text": "array.join(separator);\n"
},
{
"code": null,
"e": 2728,
"s": 2598,
"text": "separator − Specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma."
},
{
"code": null,
"e": 2783,
"s": 2728,
"text": "Returns a string after joining all the array elements."
},
{
"code": null,
"e": 2810,
"s": 2783,
"text": "Try the following example."
},
{
"code": null,
"e": 3315,
"s": 2810,
"text": "<html>\n <head>\n <title>JavaScript Array join Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var arr = new Array(\"First\",\"Second\",\"Third\");\n \n var str = arr.join();\n document.write(\"str : \" + str ); \n \n var str = arr.join(\", \");\n document.write(\"<br />str : \" + str ); \n \n var str = arr.join(\" + \");\n document.write(\"<br />str : \" + str ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3399,
"s": 3315,
"text": "str : First,Second,Third\nstr : First, Second, Third\nstr : First + Second + Third \n"
},
{
"code": null,
"e": 3434,
"s": 3399,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3448,
"s": 3434,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3482,
"s": 3448,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3496,
"s": 3482,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3531,
"s": 3496,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3548,
"s": 3531,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3583,
"s": 3548,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3600,
"s": 3583,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3633,
"s": 3600,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3661,
"s": 3633,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3695,
"s": 3661,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3723,
"s": 3695,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3730,
"s": 3723,
"text": " Print"
},
{
"code": null,
"e": 3741,
"s": 3730,
"text": " Add Notes"
}
] |
How do I add Vibrate and sound for Notification in Android? | This example demonstrate about How do I add Vibrate and sound for Notification 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" ?>
<android.support.constraint.ConstraintLayout
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 :padding= "16dp"
tools :context= ".MainActivity" >
<Button
android :id= "@+id/btnCreateNotification"
android :layout_width= "0dp"
android :layout_height= "wrap_content"
android :text= "Create notification"
app :layout_constraintBottom_toBottomOf= "parent"
app :layout_constraintEnd_toEndOf= "parent"
app :layout_constraintStart_toStartOf= "parent"
app :layout_constraintTop_toTopOf= "parent" />
</android.support.constraint.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.notifyme;
import android.app.NotificationManager;
import android.content.Context;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private final static String default_notification_channel_id = "default" ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
Button btnCreateNotification = findViewById(R.id. btnCreateNotification );
btnCreateNotification.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick (View v) {
Uri alarmSound = RingtoneManager. getDefaultUri (RingtoneManager. TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity.this,
default_notification_channel_id )
.setSmallIcon(R.drawable. ic_launcher_foreground )
.setVibrate( new long []{ 1000 , 1000 , 1000 , 1000 , 1000 })
.setContentTitle( "Test" )
.setSound(alarmSound)
.setContentText( "Hello! This is my first push notification" ) ;
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(( int ) System. currentTimeMillis (), mBuilder.build());
}
});
}
}
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.tutorialspoint.com.notifyme" >
<uses-permission android :name= "android.permission.VIBRATE" />
<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>
<service
android :name= ".MyFirebaseMessagingService"
android :exported= "false" >
<intent-filter>
<action android :name= "com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</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 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": 1152,
"s": 1062,
"text": "This example demonstrate about How do I add Vibrate and sound for Notification in Android"
},
{
"code": null,
"e": 1281,
"s": 1152,
"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": 1346,
"s": 1281,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2200,
"s": 1346,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<android.support.constraint.ConstraintLayout\n 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 :padding= \"16dp\"\n tools :context= \".MainActivity\" >\n <Button\n android :id= \"@+id/btnCreateNotification\"\n android :layout_width= \"0dp\"\n android :layout_height= \"wrap_content\"\n android :text= \"Create notification\"\n app :layout_constraintBottom_toBottomOf= \"parent\"\n app :layout_constraintEnd_toEndOf= \"parent\"\n app :layout_constraintStart_toStartOf= \"parent\"\n app :layout_constraintTop_toTopOf= \"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2257,
"s": 2200,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3977,
"s": 2257,
"text": "package app.tutorialspoint.com.notifyme;\nimport android.app.NotificationManager;\nimport android.content.Context;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.support.v4.app.NotificationCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport java.util.Objects;\npublic class MainActivity extends AppCompatActivity {\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState);\n setContentView(R.layout. activity_main );\n Button btnCreateNotification = findViewById(R.id. btnCreateNotification );\n btnCreateNotification.setOnClickListener( new View.OnClickListener() {\n @Override\n public void onClick (View v) {\n Uri alarmSound = RingtoneManager. getDefaultUri (RingtoneManager. TYPE_NOTIFICATION);\n NotificationCompat.Builder mBuilder =\n new NotificationCompat.Builder(MainActivity.this,\n default_notification_channel_id )\n .setSmallIcon(R.drawable. ic_launcher_foreground )\n .setVibrate( new long []{ 1000 , 1000 , 1000 , 1000 , 1000 })\n .setContentTitle( \"Test\" )\n .setSound(alarmSound)\n .setContentText( \"Hello! This is my first push notification\" ) ;\n NotificationManager mNotificationManager = (NotificationManager)\n getSystemService(Context.NOTIFICATION_SERVICE);\n mNotificationManager.notify(( int ) System. currentTimeMillis (), mBuilder.build());\n }\n });\n }\n}"
},
{
"code": null,
"e": 4032,
"s": 3977,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5069,
"s": 4032,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name= \"android.permission.VIBRATE\" />\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 <service\n android :name= \".MyFirebaseMessagingService\"\n android :exported= \"false\" >\n <intent-filter>\n <action android :name= \"com.google.firebase.MESSAGING_EVENT\" />\n </intent-filter>\n </service>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5417,
"s": 5069,
"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 –"
}
] |
Const vs Static vs Readonly in C# | Constant fields are the fields that cannot be modified. At the time of declaration, you need to assign a value to it.
const int a = 5;
If the static modifier is applied to a class then you cannot instantiate the class using the new keyword. You can use the static keyword on methods, properties, classes, constructors, etc.
static int a = 10;
A Readonly field is initialized at the time of declaration or you can also set it within the constructor.
Let us see an example in which the readonly field is initialized inside the constructor.
class Demo {
readonly int a;
public Demo( ) {
a = 5;
}
} | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "Constant fields are the fields that cannot be modified. At the time of declaration, you need to assign a value to it."
},
{
"code": null,
"e": 1197,
"s": 1180,
"text": "const int a = 5;"
},
{
"code": null,
"e": 1386,
"s": 1197,
"text": "If the static modifier is applied to a class then you cannot instantiate the class using the new keyword. You can use the static keyword on methods, properties, classes, constructors, etc."
},
{
"code": null,
"e": 1405,
"s": 1386,
"text": "static int a = 10;"
},
{
"code": null,
"e": 1511,
"s": 1405,
"text": "A Readonly field is initialized at the time of declaration or you can also set it within the constructor."
},
{
"code": null,
"e": 1600,
"s": 1511,
"text": "Let us see an example in which the readonly field is initialized inside the constructor."
},
{
"code": null,
"e": 1672,
"s": 1600,
"text": "class Demo {\n readonly int a;\n public Demo( ) {\n a = 5;\n }\n}"
}
] |
JavaScript Strings | JavaScript strings are for storing and manipulating text.
A JavaScript string is zero or more characters written inside quotes.
You can use single or double quotes:
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
To find the length of a string, use the built-in length property:
Because strings must be written within quotes, JavaScript will misunderstand this string:
The string will be chopped to "We are the so-called ".
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
The sequence \" inserts a double quote in a string:
The sequence \' inserts a single quote in a string:
The sequence \\ inserts a backslash in a string:
Six other escape sequences are valid in JavaScript:
The 6 escape characters above were originally designed to control
typewriters, teletypes, and fax machines. They do not make any sense in HTML.
For best readability, programmers often like to avoid code lines longer than
80 characters.
If a JavaScript statement does not fit on one line, the best place to break
it is after an operator:
You can also break up a code line within a text string with a single backslash:
The \ method is not the preferred method. It might not have universal support.Some browsers do
not allow spaces behind the \ character.
A safer way to break up a string, is to use string
addition:
You cannot break up a code line with a backslash:
Normally, JavaScript strings are primitive values, created from literals:
But strings can also be defined as objects with the keyword new:
Do not create Strings objects.
The new keyword complicates the code and slows down execution speed.
String objects can produce unexpected results:
When using the == operator, x and y are equal:
When using the === operator, x and y are not equal:
Note the difference between (x==y) and (x===y).
(x == y) true or false?
(x === y) true or false?
Comparing two JavaScript objects always returns false.
For a complete String reference, go to our:
Complete JavaScript String Reference.
The reference contains descriptions and examples of all string properties and methods.
Use the length property to alert the length of txt.
let txt = "Hello World!";
let x = ;
alert(x);
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 58,
"s": 0,
"text": "JavaScript strings are for storing and manipulating text."
},
{
"code": null,
"e": 128,
"s": 58,
"text": "A JavaScript string is zero or more characters written inside quotes."
},
{
"code": null,
"e": 165,
"s": 128,
"text": "You can use single or double quotes:"
},
{
"code": null,
"e": 265,
"s": 165,
"text": "You can use quotes inside a string, as long as they don't match the quotes \nsurrounding the string:"
},
{
"code": null,
"e": 331,
"s": 265,
"text": "To find the length of a string, use the built-in length property:"
},
{
"code": null,
"e": 421,
"s": 331,
"text": "Because strings must be written within quotes, JavaScript will misunderstand this string:"
},
{
"code": null,
"e": 476,
"s": 421,
"text": "The string will be chopped to \"We are the so-called \"."
},
{
"code": null,
"e": 554,
"s": 476,
"text": "The solution to avoid this problem, is to use the backslash escape character."
},
{
"code": null,
"e": 638,
"s": 554,
"text": "The backslash (\\) escape character turns special characters into string characters:"
},
{
"code": null,
"e": 691,
"s": 638,
"text": "The sequence \\\" inserts a double quote in a string:"
},
{
"code": null,
"e": 746,
"s": 693,
"text": "The sequence \\' inserts a single quote in a string:"
},
{
"code": null,
"e": 798,
"s": 748,
"text": "The sequence \\\\ inserts a backslash in a string:"
},
{
"code": null,
"e": 852,
"s": 800,
"text": "Six other escape sequences are valid in JavaScript:"
},
{
"code": null,
"e": 998,
"s": 852,
"text": "The 6 escape characters above were originally designed to control \ntypewriters, teletypes, and fax machines. They do not make any sense in HTML. "
},
{
"code": null,
"e": 1091,
"s": 998,
"text": "For best readability, programmers often like to avoid code lines longer than \n80 characters."
},
{
"code": null,
"e": 1193,
"s": 1091,
"text": "If a JavaScript statement does not fit on one line, the best place to break \nit is after an operator:"
},
{
"code": null,
"e": 1273,
"s": 1193,
"text": "You can also break up a code line within a text string with a single backslash:"
},
{
"code": null,
"e": 1410,
"s": 1273,
"text": "The \\ method is not the preferred method. It might not have universal support.Some browsers do \nnot allow spaces behind the \\ character."
},
{
"code": null,
"e": 1472,
"s": 1410,
"text": "A safer way to break up a string, is to use string \naddition:"
},
{
"code": null,
"e": 1522,
"s": 1472,
"text": "You cannot break up a code line with a backslash:"
},
{
"code": null,
"e": 1596,
"s": 1522,
"text": "Normally, JavaScript strings are primitive values, created from literals:"
},
{
"code": null,
"e": 1661,
"s": 1596,
"text": "But strings can also be defined as objects with the keyword new:"
},
{
"code": null,
"e": 1692,
"s": 1661,
"text": "Do not create Strings objects."
},
{
"code": null,
"e": 1761,
"s": 1692,
"text": "The new keyword complicates the code and slows down execution speed."
},
{
"code": null,
"e": 1808,
"s": 1761,
"text": "String objects can produce unexpected results:"
},
{
"code": null,
"e": 1856,
"s": 1808,
"text": " When using the == operator, x and y are equal:"
},
{
"code": null,
"e": 1910,
"s": 1856,
"text": "When using the === operator, x and y are not equal:\n\n"
},
{
"code": null,
"e": 1958,
"s": 1910,
"text": "Note the difference between (x==y) and (x===y)."
},
{
"code": null,
"e": 1982,
"s": 1958,
"text": "(x == y) true or false?"
},
{
"code": null,
"e": 2007,
"s": 1982,
"text": "(x === y) true or false?"
},
{
"code": null,
"e": 2062,
"s": 2007,
"text": "Comparing two JavaScript objects always returns false."
},
{
"code": null,
"e": 2106,
"s": 2062,
"text": "For a complete String reference, go to our:"
},
{
"code": null,
"e": 2144,
"s": 2106,
"text": "Complete JavaScript String Reference."
},
{
"code": null,
"e": 2231,
"s": 2144,
"text": "The reference contains descriptions and examples of all string properties and methods."
},
{
"code": null,
"e": 2283,
"s": 2231,
"text": "Use the length property to alert the length of txt."
},
{
"code": null,
"e": 2330,
"s": 2283,
"text": "let txt = \"Hello World!\";\nlet x = ;\nalert(x);\n"
},
{
"code": null,
"e": 2349,
"s": 2330,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2382,
"s": 2349,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2424,
"s": 2382,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2531,
"s": 2424,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2550,
"s": 2531,
"text": "[email protected]"
}
] |
C++ Library - <bitset> | Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit.
As it emulates array, its index also starts from 0th position. Individual bit from bitset can be accessed using subscript operator. For instance to access first element of bitset foo use foo[0].
Bitset class provides constructors to create bitset from integer as well as from strings. The size of the bitset is fixed at compile time. STL provides vector<bool> class that provides dynamic resize functionality.
Below is definition of std::bitset from <bitset> header file
template <size_t N> class bitset;
N − Size of the bitset.
Following member types can be used as parameters or return type by member functions.
Below is list of all methods from <bitset> header.
Constructs bitset container and initialize it with zero.
Constructs bitset container and initialize it with the bit value of val.
Constructs and initializes a bitset container from C++ string object.
Constructs and initializes a bitset container from c-style string.
This is embedded class which provides l-value that can be returned from std::bitset::operator[].
Performs bitwise AND operation on current bitset object.
Performs bitwise OR operation on current bitset object.
Performs bitwise XOR operation on current bitset object.
Performs bitwise left SHIFT operation on current bitset object.
Performs bitwise right SHIFT operation on current bitset object.
Performs bitwise NOT operation on bitset.
Performs bitwise left SHIFT operation on bitset.
Performs bitwise right SHIFT operation on bitset.
Test whether two bitsets are equal or not.
Test whether two bitsets are equal or not.
Performs bitwise AND operation on bitset.
Performs bitwise OR operation on bitset.
Performs bitwise XOR operation on bitset.
Extracts upto N bits from is and stores into another bitset x.
Inserts bitset x to the character stream os.
Tests whether all bits from bitset are set or not.
Tests whether at least one bit from bitset is set or not.
Count number of set bits from bitset.
Toggles all bits from bitset.
Toggles single bit from bitset.
Tests whether all bits are unset or not.
Returns the value of bit at position pos.
Returns the reference of bit at position pos.
Reset all bits of bitset to zero.
Reset single bit of bitset to zero.
Set all bits from bitset to one.
Set single bit from bitset to either one or zero.
Reports the size of the bitset.
Tests whether Nth bit is set or not.
Converts bitset object to string object.
Convert bitset to unsigned long long.
Convert bitset to unsigned long.
Returns hash value based on the provided bitset.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2876,
"s": 2603,
"text": "Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit."
},
{
"code": null,
"e": 3071,
"s": 2876,
"text": "As it emulates array, its index also starts from 0th position. Individual bit from bitset can be accessed using subscript operator. For instance to access first element of bitset foo use foo[0]."
},
{
"code": null,
"e": 3286,
"s": 3071,
"text": "Bitset class provides constructors to create bitset from integer as well as from strings. The size of the bitset is fixed at compile time. STL provides vector<bool> class that provides dynamic resize functionality."
},
{
"code": null,
"e": 3347,
"s": 3286,
"text": "Below is definition of std::bitset from <bitset> header file"
},
{
"code": null,
"e": 3381,
"s": 3347,
"text": "template <size_t N> class bitset;"
},
{
"code": null,
"e": 3405,
"s": 3381,
"text": "N − Size of the bitset."
},
{
"code": null,
"e": 3490,
"s": 3405,
"text": "Following member types can be used as parameters or return type by member functions."
},
{
"code": null,
"e": 3541,
"s": 3490,
"text": "Below is list of all methods from <bitset> header."
},
{
"code": null,
"e": 3598,
"s": 3541,
"text": "Constructs bitset container and initialize it with zero."
},
{
"code": null,
"e": 3671,
"s": 3598,
"text": "Constructs bitset container and initialize it with the bit value of val."
},
{
"code": null,
"e": 3741,
"s": 3671,
"text": "Constructs and initializes a bitset container from C++ string object."
},
{
"code": null,
"e": 3808,
"s": 3741,
"text": "Constructs and initializes a bitset container from c-style string."
},
{
"code": null,
"e": 3905,
"s": 3808,
"text": "This is embedded class which provides l-value that can be returned from std::bitset::operator[]."
},
{
"code": null,
"e": 3962,
"s": 3905,
"text": "Performs bitwise AND operation on current bitset object."
},
{
"code": null,
"e": 4018,
"s": 3962,
"text": "Performs bitwise OR operation on current bitset object."
},
{
"code": null,
"e": 4075,
"s": 4018,
"text": "Performs bitwise XOR operation on current bitset object."
},
{
"code": null,
"e": 4139,
"s": 4075,
"text": "Performs bitwise left SHIFT operation on current bitset object."
},
{
"code": null,
"e": 4204,
"s": 4139,
"text": "Performs bitwise right SHIFT operation on current bitset object."
},
{
"code": null,
"e": 4246,
"s": 4204,
"text": "Performs bitwise NOT operation on bitset."
},
{
"code": null,
"e": 4295,
"s": 4246,
"text": "Performs bitwise left SHIFT operation on bitset."
},
{
"code": null,
"e": 4345,
"s": 4295,
"text": "Performs bitwise right SHIFT operation on bitset."
},
{
"code": null,
"e": 4388,
"s": 4345,
"text": "Test whether two bitsets are equal or not."
},
{
"code": null,
"e": 4431,
"s": 4388,
"text": "Test whether two bitsets are equal or not."
},
{
"code": null,
"e": 4473,
"s": 4431,
"text": "Performs bitwise AND operation on bitset."
},
{
"code": null,
"e": 4514,
"s": 4473,
"text": "Performs bitwise OR operation on bitset."
},
{
"code": null,
"e": 4556,
"s": 4514,
"text": "Performs bitwise XOR operation on bitset."
},
{
"code": null,
"e": 4619,
"s": 4556,
"text": "Extracts upto N bits from is and stores into another bitset x."
},
{
"code": null,
"e": 4664,
"s": 4619,
"text": "Inserts bitset x to the character stream os."
},
{
"code": null,
"e": 4715,
"s": 4664,
"text": "Tests whether all bits from bitset are set or not."
},
{
"code": null,
"e": 4773,
"s": 4715,
"text": "Tests whether at least one bit from bitset is set or not."
},
{
"code": null,
"e": 4811,
"s": 4773,
"text": "Count number of set bits from bitset."
},
{
"code": null,
"e": 4841,
"s": 4811,
"text": "Toggles all bits from bitset."
},
{
"code": null,
"e": 4873,
"s": 4841,
"text": "Toggles single bit from bitset."
},
{
"code": null,
"e": 4914,
"s": 4873,
"text": "Tests whether all bits are unset or not."
},
{
"code": null,
"e": 4956,
"s": 4914,
"text": "Returns the value of bit at position pos."
},
{
"code": null,
"e": 5002,
"s": 4956,
"text": "Returns the reference of bit at position pos."
},
{
"code": null,
"e": 5036,
"s": 5002,
"text": "Reset all bits of bitset to zero."
},
{
"code": null,
"e": 5072,
"s": 5036,
"text": "Reset single bit of bitset to zero."
},
{
"code": null,
"e": 5105,
"s": 5072,
"text": "Set all bits from bitset to one."
},
{
"code": null,
"e": 5155,
"s": 5105,
"text": "Set single bit from bitset to either one or zero."
},
{
"code": null,
"e": 5187,
"s": 5155,
"text": "Reports the size of the bitset."
},
{
"code": null,
"e": 5224,
"s": 5187,
"text": "Tests whether Nth bit is set or not."
},
{
"code": null,
"e": 5265,
"s": 5224,
"text": "Converts bitset object to string object."
},
{
"code": null,
"e": 5303,
"s": 5265,
"text": "Convert bitset to unsigned long long."
},
{
"code": null,
"e": 5336,
"s": 5303,
"text": "Convert bitset to unsigned long."
},
{
"code": null,
"e": 5385,
"s": 5336,
"text": "Returns hash value based on the provided bitset."
},
{
"code": null,
"e": 5392,
"s": 5385,
"text": " Print"
},
{
"code": null,
"e": 5403,
"s": 5392,
"text": " Add Notes"
}
] |
How to find exponential value in Python? | Exponential value of a x is xth power of e, Euler's constant which is an irrational number called Euler's number and is equal to 2.718281.
There are two ways to calculate it.
Using ** operator
>>> import math
>>> math.e**2 #math.e is defined constant in math module
7.3890560989306495
Using exp() function
>>>import math
>>> math.exp(2)
7.38905609893065 | [
{
"code": null,
"e": 1201,
"s": 1062,
"text": "Exponential value of a x is xth power of e, Euler's constant which is an irrational number called Euler's number and is equal to 2.718281."
},
{
"code": null,
"e": 1237,
"s": 1201,
"text": "There are two ways to calculate it."
},
{
"code": null,
"e": 1255,
"s": 1237,
"text": "Using ** operator"
},
{
"code": null,
"e": 1347,
"s": 1255,
"text": ">>> import math\n>>> math.e**2 #math.e is defined constant in math module\n7.3890560989306495"
},
{
"code": null,
"e": 1368,
"s": 1347,
"text": "Using exp() function"
},
{
"code": null,
"e": 1416,
"s": 1368,
"text": ">>>import math\n>>> math.exp(2)\n7.38905609893065"
}
] |
MongoDB Aggregate JSON array field for the matching field of other collection? | For this, create two collections and add some document. After that, use $lookup for match. Let us create a collection with documents −
> db.demo101.insertOne(
... { "_id" : "1", "Details" : [ { "PId" : "200" }, { "PId" : "201" }, { "PId" : "201" } ] }
... )
{ "acknowledged" : true, "insertedId" : "1" }
Display all documents from a collection with the help of find() method −
> db.demo101.find();
This will produce the following output −
{ "_id" : "1", "Details" : [ { "PId" : "200" }, { "PId" : "201" }, { "PId" : "201" } ] }
Following is the query to create second collection with some documents −
> db.demo102.insertOne(
... { "_id" : "201", "CustEmailId" : "[email protected]" }
... );
{ "acknowledged" : true, "insertedId" : "201" }
Display all documents from a collection with the help of find() method −
> db.demo102.find();
This will produce the following output −
{ "_id" : "200", "CustEmailId" : "[email protected]" }
{ "_id" : "201", "CustEmailId" : "[email protected]" }
Following is the query to aggregate JSON array field for the matching field of other collection −
> db.demo101.aggregate(
... [
... {$unwind:"$Details"},
... {$lookup : {from : "demo102", "localField":"Details.PId", "foreignField":"_id", as :"out"}},
... {$project : {"_id":1, "Details.PId":{$arrayElemAt:["$out.CustEmailId",0]}}},
... {$group:{_id:"$_id", Details : {$push : "$Details"}}}
... ]
... ).pretty()
This will produce the following output −
{
"_id" : "1",
"Details" : [
{
"PId" : "[email protected]"
},
{
"PId" : "[email protected]"
},
{
"PId" : "[email protected]"
}
]
} | [
{
"code": null,
"e": 1197,
"s": 1062,
"text": "For this, create two collections and add some document. After that, use $lookup for match. Let us create a collection with documents −"
},
{
"code": null,
"e": 1366,
"s": 1197,
"text": "> db.demo101.insertOne(\n... { \"_id\" : \"1\", \"Details\" : [ { \"PId\" : \"200\" }, { \"PId\" : \"201\" }, { \"PId\" : \"201\" } ] }\n... )\n{ \"acknowledged\" : true, \"insertedId\" : \"1\" }"
},
{
"code": null,
"e": 1439,
"s": 1366,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1460,
"s": 1439,
"text": "> db.demo101.find();"
},
{
"code": null,
"e": 1501,
"s": 1460,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1590,
"s": 1501,
"text": "{ \"_id\" : \"1\", \"Details\" : [ { \"PId\" : \"200\" }, { \"PId\" : \"201\" }, { \"PId\" : \"201\" } ] }"
},
{
"code": null,
"e": 1663,
"s": 1590,
"text": "Following is the query to create second collection with some documents −"
},
{
"code": null,
"e": 1799,
"s": 1663,
"text": "> db.demo102.insertOne(\n... { \"_id\" : \"201\", \"CustEmailId\" : \"[email protected]\" }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : \"201\" }"
},
{
"code": null,
"e": 1872,
"s": 1799,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1893,
"s": 1872,
"text": "> db.demo102.find();"
},
{
"code": null,
"e": 1934,
"s": 1893,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2039,
"s": 1934,
"text": "{ \"_id\" : \"200\", \"CustEmailId\" : \"[email protected]\" }\n{ \"_id\" : \"201\", \"CustEmailId\" : \"[email protected]\" }"
},
{
"code": null,
"e": 2137,
"s": 2039,
"text": "Following is the query to aggregate JSON array field for the matching field of other collection −"
},
{
"code": null,
"e": 2462,
"s": 2137,
"text": "> db.demo101.aggregate(\n... [\n... {$unwind:\"$Details\"},\n... {$lookup : {from : \"demo102\", \"localField\":\"Details.PId\", \"foreignField\":\"_id\", as :\"out\"}},\n... {$project : {\"_id\":1, \"Details.PId\":{$arrayElemAt:[\"$out.CustEmailId\",0]}}},\n... {$group:{_id:\"$_id\", Details : {$push : \"$Details\"}}}\n... ]\n... ).pretty()"
},
{
"code": null,
"e": 2503,
"s": 2462,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2699,
"s": 2503,
"text": "{\n \"_id\" : \"1\",\n \"Details\" : [\n {\n \"PId\" : \"[email protected]\"\n },\n {\n \"PId\" : \"[email protected]\"\n },\n {\n \"PId\" : \"[email protected]\"\n }\n ]\n}"
}
] |
An easy tutorial about Sentiment Analysis with Deep Learning and Keras | by Sergio Virahonda | Towards Data Science | Get comfortable, it’s going to take you several minutes to read but hopefully, you’ll stick with me along the whole article. I’m gonna walk you through a foundational task that you as data scientist/machine learning engineer must know how to perform because at some point of your career you’ll be required to do so. In the context of this article, I’ll assume you have a basic understanding of what I’m going to talk in the next lines. I’ll be stacking layers of concepts as I move forward, keeping a very low-level language — don’t worry if you fell a little lost between lines, later I will probably clarify your doubts. The main idea is for you to understand what I’ll be explaining. That being said, let’s get hands-on (Btw, don’t miss any detail and download the whole project from my repo.)
I’ll start by defining the first unusual term in the title: Sentiment Analysis is a very frequent term within text classification and is essentially to use natural language processing (quite often referred simply as NLP)+ machine learning to interpret and classify emotions in text information. Imagine the task of determining whether a product’s review is positive or negative; you could do it yourself just by reading it, right? But what happens when the company you work for sells 2k products every single day? Are you pretending to read all the reviews and manually classify them? Let’s be honest, your job would be the worst ever. There’s where Sentiment Analysis comes in and makes your life and job easier.
There are several ways to implement Sentiment Analysis and each data scientist has his/her own preferred method, I’ll guide you through a very simple one so you can understand what it involves, but also suggest you some others that way you can research about them. Let’s place first things first: If you are not familiar with Machine Learning, you must know all algorithms are only able to understand and process numeric data (particularly floating point data), thus you cannot feed them with text and wait for them to solve your problems; instead, you’ll have to make several transformations to your data until it reaches a representative numeric shape. The common and most basic steps are:
Remove URLs and email addresses from every single sample — because they won’t add meaningful value.
Remove punctuation signs — otherwise your model won’t understand that “good!” and “good” are actually meaning the same thing.
Lowercase all text — because you want to make the input text as generic as possible and avoid that, for example, a “Good” which is at the beginning of a phrase to be understood differently than the “good” in another sample.
Remove stop-words — because they only add noise and won’t make the data more meaningful. Btw, stop-words refer to the most common words in a language, such as “I”, “have”, “are” and so on. I hope you get the point because there’s not an official stop-words list out there.
Stemming/Lemmatizing: This step is optional, but for most of data scientist considered as crucial. I’ll show you that it’s not THAT relevant to achieve good results. Stemming and lemmatizing are very similar tasks, both look forward to extract the root words from every word of a sentence of the corpus data. Lemmatizing generally returns valid words (that exist) while stemming techniques return (most of the times) shorten words, that’s why lemmatizing is used more in real world implementations. This is how lemmatizers vs. stemmers work: suppose you want to find the root word of ‘caring’: ‘Caring’ -> Lemmatization -> ‘Care’. In the other hand: ‘Caring’ -> Stemming -> ‘Car’; did you get the point? You can research about both and obviously implement any if the business requires it.
Transform dataset (text) into numeric tensors — Usually referred as vectorization. If you recall some lines above, I explained that like all other neural networks, deep-learning models don’t take as input raw text: they only work with numeric tensors, that’s why this step is not negotiable. There are multiple ways to do so; for example, if you’re going to use a classic ML model (not DL) then you definitely should go with CountVectorizer, TFIDF Vectorizer or just the basic but not so good approach: Bag-Of-Words. It’s up to you. However, if you’re going to implement Deep Learning you might know that the best way is to turn your text data (that can be understood as sequences of word or sequences of characters) into low-dimensional floating-point vectors — don’t worry, I’ll explain this in a bit.
This is how a very basic text cleaning Python function would look like (this is a very simple way, you can implement the one that best works for your purpose — out there are very complete libraries such as Gensim or NLTK):
def depure_data(data): #Removing URLs with a regular expression url_pattern = re.compile(r'https?://\S+|www\.\S+') data = url_pattern.sub(r'', data) # Remove Emails data = re.sub('\S*@\S*\s?', '', data) # Remove new line characters data = re.sub('\s+', ' ', data) # Remove distracting single quotes data = re.sub("\'", "", data) return data
Now a very simple way to remove repeating words from your dataset, following the idea that the shortest and longest ones are usually useless:
def sent_to_words(sentences): for sentence in sentences: yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))
Finally, a function to detokenize all sentences (this because I’ll use word embeddings and not this old-fashioned tokenizing method):
def detokenize(text): return TreebankWordDetokenizer().detokenize(text)
To run everything in the right order, you just need to run this:
temp = []#Splitting pd.Series to listdata_to_list = train['selected_text'].values.tolist()for i in range(len(data_to_list)): temp.append(depure_data(data_to_list[i]))data_words = list(sent_to_words(temp))data = []for i in range(len(data_words)): data.append(detokenize(data_words[i]))print(data[:5])
At this point, you will have transformed your noisy text dataset into a very flat and simple one. In this particular case, you’ll have gone from this:
['I`d have responded, if I were going', 'Sooo SAD', 'bullying me', 'leave me alone', 'Sons of ****,']
To this:
['have responded if were going', 'sooo sad', 'bullying me', 'leave me alone', 'sons of']
If you want to go even beyond, then take the stemming or lemmatizing paths, you’ll get much better results. In this particular how-to, will keep it this way just you to get that it’s totally possible to achieve great results skipping that step (if you’re building your model in a business context then you’ll be 100% in obligation to do so, don’t skip it!)
Alright, it’s time to understand an extremely important step you’ll have to deal with when working with text data. Once you have your text data completely clean of noise, it’s time to transform it into floating-point tensors. In order to perform this task, we’ll use word-embeddings.
Word embeddings (or sometimes called word vectors) are learned from data and essentially are low-dimensional floating-point vectors (dense vectors, as opposed to sparse vectors obtained from processes such as one-hot-encoding) that pack information in few dimensions. Why would you use this method and not any other different and more simple? Because deep learning models converge easier with dense vectors than with sparse ones. Again, it always depends on the dataset nature and the business need.
There are two ways to obtain word embeddings:
Use a pretrained word embedding stack on top of your model, just as you would use a pretrained NN layer (or group of layers) — a very infrequent approach.
Learn word embeddings from scratch. To achieve this, you’d start with random word vectors and progressively learn meaningful ones just as a NN would learn its weights. This is the option that we’ll use and actually is reasonable to learn a new embedding space with every single new task. Fortunately, this step is very straightforward with TensorFlow or Keras, and you’d implement word embedding just like one more layer in your NN stack.
Before moving forward, we need to take a previous step. We need to transform our array of text into 2D numeric arrays:
from keras.preprocessing.text import Tokenizerfrom keras.preprocessing.sequence import pad_sequencesfrom keras import regularizersmax_words = 5000max_len = 200tokenizer = Tokenizer(num_words=max_words)tokenizer.fit_on_texts(data)sequences = tokenizer.texts_to_sequences(data)tweets = pad_sequences(sequences, maxlen=max_len)print(tweets)
The output you’ll get would look like this:
[[ 0 0 0 ... 68 146 41] [ 0 0 0 ... 0 397 65] [ 0 0 0 ... 0 0 11] ... [ 0 0 0 ... 372 10 3] [ 0 0 0 ... 24 542 4] [ 0 0 0 ... 2424 199 657]]
What does the previous step mean? Let’s take the definition from the official Keras documentation, you’ll get better the point:
This function transforms a list (of length num_samples) of sequences (lists of integers) into a 2D Numpy array of shape (num_samples, num_timesteps). num_timesteps is either the maxlen argument if provided, or the length of the longest sequence in the list.
Sequences that are shorter than num_timesteps are padded with value until they are num_timesteps long.
Sequences longer than num_timesteps are truncated so that they fit the desired length
It’s extremely important you to keep in mind that no matter if you use TensorFlow or any other Astraction API such as Keras, you should get the same result at the end of your training. In this opportunity we’ll use Keras for obvious reasons: It’s extremely easy to implement. This is how you create an embedding layer:
from keras.layers import Embeddingembedding_layer = Embedding(1000, 64)
The above layer takes 2D integer tensors of shape (samples, sequence_length) and at least two arguments: the number of possible tokens and the dimensionality of the embeddings (here 1000 and 64, respectively). To be more figurative, just imagine the embedding layer is a dictionary that links integer indices to dense vectors. Finally, it returns a 3D floating-point tensor of shape (samples, sequence_length, embedding_dimensionality) that can now be processed by our neural network. Let’s talk about that topic, particularly about Recurrent Neural Networks that are the best when processing text-related sequences is required.
Usually other types of neural networks out there such as densely connected networks or convolutional networks have no memory, this means that every single input is processed independently with no relation with the other ones. This is the opposite of what you normally would do when reading a paragraph: when you’re reading you keep in memory what you’ve read in the previous lines , right? You have a sense of the whole meaning and this is exactly the same principle that RNNs adopt. They process sequences by iterating along the sequence elements and keeping information relative to what it has processed so far. The math that is under a RNN’s hood is, to be honest, a topic that you should cover by yourself in order to understand its logic. I suggest you to give a read to “Learning TensorFlow” by Tom Hope (available here) which explains all the process in a very easy manner.
In this article, I’ll implement three RNN types: a single LSTM (long short-term memory) model, a Bidirectional LSTM and a very infrequent used Conv1D model. As a bonus, I show how to implement a SimpleRNN model but to be honest, it’s not deployed in production anywhere because it’s extremely simple.
Coming back to our example, this is how the code would look like when implementing a single LSTM layer model with its respective embedding layer:
from keras.models import Sequentialfrom keras import layersfrom keras import regularizersfrom keras import backend as Kfrom keras.callbacks import ModelCheckpointmodel1 = Sequential()model1.add(layers.Embedding(max_words, 20)) #The embedding layermodel1.add(layers.LSTM(15,dropout=0.5)) #Our LSTM layermodel1.add(layers.Dense(3,activation='softmax'))model1.compile(optimizer='rmsprop',loss='categorical_crossentropy', metrics=['accuracy'])checkpoint1 = ModelCheckpoint("best_model1.hdf5", monitor='val_accuracy', verbose=1,save_best_only=True, mode='auto', period=1,save_weights_only=False)history = model1.fit(X_train, y_train, epochs=70,validation_data=(X_test, y_test),callbacks=[checkpoint1])
There are a few things to highlight in the code above: when implementing a Keras Sequential model, it’s all about stacking layers. LSTM layers (as well as all other RNN layers) can take several arguments but the ones that I defined are 15 which is the number of hidden units within the layer (must be a positive integer and represents the dimensionality of the output space) and the dropout rate of the layer. Dropout is one of the most effective and most commonly used regularization techniques for NNs and consists of randomly turning off hidden units during training, that way the network does not rely 100% on all its neurons and instead, forces itself to find more meaningful patterns in the data in order to increase the metric you’re trying to optimize. There are several other arguments to pass, you can find the complete documentation here, but for this particular example, these settings will achieve good results.
FYI, sometimes it’s useful to stack several recurrent layers one after the other in order to increase the representational power of a network. If you want to do so then you’ll have to return full sequences of outputs. This is an example:
model0 = Sequential()model0.add(layers.Embedding(max_words, 15))model0.add(layers.SimpleRNN(15,return_sequences=True))model0.add(layers.SimpleRNN(15))model0.add(layers.Dense(3,activation='softmax'))
In our LSTM example I’m stacking a Dense layer with three output units that would be the 3 possible classes of our dataset. In order to make probabilistic outputs, it’s always good to use ‘softmax’ as activation function in the final layer. Use the next table when building a neural network and you feel confused:
When compiling the model, I’m using RMSprop optimizer with its default learning rate but actually this is up to every developer. Some people love Adam, some others Adadelta, and so on. To be honest, RMSprop or Adam should be enough in most of the cases. If you don’t know what an optimizer is, it’s simply the mechanism that constantly computes the gradient of the loss and defines how to move against the loss function in order to find its global minima and therefore, find the best network’s parameters (the model kernel and its bias’ weights). As loss function, I use categorical_crossentropy (Check the table) that is typically used when you’re dealing with multiclass classification tasks. In the other hand, you would use binary_crossentropy when binary classification is required.
Finally, I’m using checkpoints to save the best model achieved in the training process. This is very useful when you need to get the model that best satisfies the metric you’re trying to optimize. Then the classic model.fit step and wait for it to complete the training iterations.
This is the validation score achieved by this NN architecture at its last epoch:
Epoch 70/70645/645 [==============================] - ETA: 0s - loss: 0.3090 - accuracy: 0.8881Epoch 00070: val_accuracy did not improve from 0.84558
Let’s compare this with a more complex network.
This is how our example’s BidRNN implementation looks like:
model2 = Sequential()model2.add(layers.Embedding(max_words, 40, input_length=max_len))model2.add(layers.Bidirectional(layers.LSTM(20,dropout=0.6)))model2.add(layers.Dense(3,activation='softmax'))model2.compile(optimizer='rmsprop',loss='categorical_crossentropy', metrics=['accuracy'])checkpoint2 = ModelCheckpoint("best_model2.hdf5", monitor='val_accuracy', verbose=1,save_best_only=True, mode='auto', period=1,save_weights_only=False)history = model2.fit(X_train, y_train, epochs=70,validation_data=(X_test, y_test),callbacks=[checkpoint2])
Let’s understand better how a bidirectional layer works. It maximizes the order sensitivity of the RNNs: essentially it consists of two RNNs (LSTMs or GRUs) that process the input sequence in one different direction to finally merge representations. By doing this, they’re able to catch more complex patterns than a single RNN layer would catch. In other words, one of the layers interprets the sequences in chronological order and the second one do so in anti-chronological order, that’s why Bidirectional RNNs are widely used, because they offer greater performance than regular RNNs.
The way they are implemented is not complex, it is just one layer inside the other. If you read carefully, I’m using almost the same parameters but achieved about .3% more of validation accuracy on its overall training:
Epoch 70/70644/645 [============================>.] - ETA: 0s - loss: 0.2876 - accuracy: 0.8965Epoch 00070: val_accuracy did not improve from 0.84849
It’s a very good number even when it’s a very simple model and I wasn’t focused on hyperparameter tuning. I’m sure that if you dedicate yourself to adjust them then will get a very good result. Unfortunately, there’s no magical formula to do so, it’s all about adjusting its architecture and forcing it to learn every time more complex patterns and control its overfitting tendency with more regularization. One important thing to highlight is that if you see your model accuracy/loss stuck around certain value, it’s likely because the learning rate is too small and therefore making your optimizer to get stuck around a local minima of the loss function; make the LR bigger or simply try another optimizer.
It’s time to try another type of architecture which even it’s not the best for text classification, it’s well known by achieving fantastic results when processing text datasets. Let’s get into it.
I hope you’re still with me, because this is one of the fastest models out there when talking about convergence — it demands a cheaper computational cost. I know by prior experience that it tends to overfit extremely quick on small datasets. In this sense, just will implement it to show you how to do so in case it’s of your interest and also give you an overview about how it works.
It uses the same principles as classic 2D ConvNets used for image classification. Convolutional layers extract patches from 1D/2D tensors (depending on the type of task and layer) and apply the same convolutional transformations to every one of them (getting as output several subsequences). I won’t get deep in such explanation because that’s out of the scope of this article, but if you want to fully understand how these layers work I would suggest to you check the book previously recommended. The most important fact of these layers is that they can recognize patters in a sequence — A pattern learned at a certain position in a sentence can later be identified in a different position or even in another sentence.
This is how 1D ConvNets are implemented:
model3.add(layers.Embedding(max_words, 40, input_length=max_len))model3.add(layers.Conv1D(20, 6, activation='relu',kernel_regularizer=regularizers.l1_l2(l1=2e-3, l2=2e-3),bias_regularizer=regularizers.l2(2e-3)))model3.add(layers.MaxPooling1D(5))model3.add(layers.Conv1D(20, 6, activation='relu',kernel_regularizer=regularizers.l1_l2(l1=2e-3, l2=2e-3),bias_regularizer=regularizers.l2(2e-3)))model3.add(layers.GlobalMaxPooling1D())model3.add(layers.Dense(3,activation='softmax'))model3.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['acc'])history = model3.fit(X_train, y_train, epochs=70,validation_data=(X_test, y_test))
Where Conv1D layers are in charge of computing the convolution operations while MaxPooling1D layers’ main task is to reduce the dimensionality of every convolutional output. Once the convolution operation is performed, the MaxPooling window extracts the highest value within it and outputs patches of maximum values. It’s important to highlight the importance of regularizers in this type of configuration, otherwise your network will learn meaningless patterns and overfit extremely fast — just FYI.
To contrast how the previous model performs, this is the metric achieved at the last epoch:
Epoch 70/70645/645 [==============================] - 5s 7ms/step - loss: 0.3096 - acc: 0.9173 - val_loss: 0.5819 - val_acc: 0.8195
And its best validation accuracy obtained was around 82%. It overfits very fast even when I’ve implemented very drastic regularization.
At this point, the best model so far has been the Bidirectional RNN. Please keep in mind that these metrics were obtained with little-to-zero hyperparameter tuning. To understand in a better way how well its predictions are, let’s look at its confusion matrix:
From the above’s image, we can deduce: 81% of positive ratings were classified as positive, 80% of negative ratings were classified as negative and 91% of neutral ratings were classified as neutral. These are not the best predictions, but are a good baseline to work on even better models. In a business scenario you would need to be close to 95% in the most easy cases.
If you want to test how it works on an input made by yourself, just compute the next lines:
sentiment = ['Neutral','Negative','Positive']sequence = tokenizer.texts_to_sequences(['this data science article is the best ever'])test = pad_sequences(sequence, maxlen=max_len)sentiment[np.around(best_model.predict(test), decimals=0).argmax(axis=1)[0]]
And the output will be:
'Positive'
Alright, we’ve reached the end of this post. I encourage you to implement all models by yourself and focus on hyperparameter tuning which is one of the tasks that takes longer. Once you’ve reached a good number, I’ll see you back here to guide you through that model’s deployment 😊.
There are several ways to do such a task. You can use the Google Cloud Platform, take the Azure path, even the cheaper way of Heroku, but let’s be honest: most of the biggest companies are adopting AWS as their main public cloud provider and these guys have a fantastic platform to build, train and deploy ML models: AWS SageMaker; which has tons of documentation out there. I’ll be posting another step-by-step well-explained tutorial about how to easily deploy models on it. I hope to see you there! | [
{
"code": null,
"e": 968,
"s": 171,
"text": "Get comfortable, it’s going to take you several minutes to read but hopefully, you’ll stick with me along the whole article. I’m gonna walk you through a foundational task that you as data scientist/machine learning engineer must know how to perform because at some point of your career you’ll be required to do so. In the context of this article, I’ll assume you have a basic understanding of what I’m going to talk in the next lines. I’ll be stacking layers of concepts as I move forward, keeping a very low-level language — don’t worry if you fell a little lost between lines, later I will probably clarify your doubts. The main idea is for you to understand what I’ll be explaining. That being said, let’s get hands-on (Btw, don’t miss any detail and download the whole project from my repo.)"
},
{
"code": null,
"e": 1682,
"s": 968,
"text": "I’ll start by defining the first unusual term in the title: Sentiment Analysis is a very frequent term within text classification and is essentially to use natural language processing (quite often referred simply as NLP)+ machine learning to interpret and classify emotions in text information. Imagine the task of determining whether a product’s review is positive or negative; you could do it yourself just by reading it, right? But what happens when the company you work for sells 2k products every single day? Are you pretending to read all the reviews and manually classify them? Let’s be honest, your job would be the worst ever. There’s where Sentiment Analysis comes in and makes your life and job easier."
},
{
"code": null,
"e": 2374,
"s": 1682,
"text": "There are several ways to implement Sentiment Analysis and each data scientist has his/her own preferred method, I’ll guide you through a very simple one so you can understand what it involves, but also suggest you some others that way you can research about them. Let’s place first things first: If you are not familiar with Machine Learning, you must know all algorithms are only able to understand and process numeric data (particularly floating point data), thus you cannot feed them with text and wait for them to solve your problems; instead, you’ll have to make several transformations to your data until it reaches a representative numeric shape. The common and most basic steps are:"
},
{
"code": null,
"e": 2474,
"s": 2374,
"text": "Remove URLs and email addresses from every single sample — because they won’t add meaningful value."
},
{
"code": null,
"e": 2600,
"s": 2474,
"text": "Remove punctuation signs — otherwise your model won’t understand that “good!” and “good” are actually meaning the same thing."
},
{
"code": null,
"e": 2824,
"s": 2600,
"text": "Lowercase all text — because you want to make the input text as generic as possible and avoid that, for example, a “Good” which is at the beginning of a phrase to be understood differently than the “good” in another sample."
},
{
"code": null,
"e": 3097,
"s": 2824,
"text": "Remove stop-words — because they only add noise and won’t make the data more meaningful. Btw, stop-words refer to the most common words in a language, such as “I”, “have”, “are” and so on. I hope you get the point because there’s not an official stop-words list out there."
},
{
"code": null,
"e": 3886,
"s": 3097,
"text": "Stemming/Lemmatizing: This step is optional, but for most of data scientist considered as crucial. I’ll show you that it’s not THAT relevant to achieve good results. Stemming and lemmatizing are very similar tasks, both look forward to extract the root words from every word of a sentence of the corpus data. Lemmatizing generally returns valid words (that exist) while stemming techniques return (most of the times) shorten words, that’s why lemmatizing is used more in real world implementations. This is how lemmatizers vs. stemmers work: suppose you want to find the root word of ‘caring’: ‘Caring’ -> Lemmatization -> ‘Care’. In the other hand: ‘Caring’ -> Stemming -> ‘Car’; did you get the point? You can research about both and obviously implement any if the business requires it."
},
{
"code": null,
"e": 4690,
"s": 3886,
"text": "Transform dataset (text) into numeric tensors — Usually referred as vectorization. If you recall some lines above, I explained that like all other neural networks, deep-learning models don’t take as input raw text: they only work with numeric tensors, that’s why this step is not negotiable. There are multiple ways to do so; for example, if you’re going to use a classic ML model (not DL) then you definitely should go with CountVectorizer, TFIDF Vectorizer or just the basic but not so good approach: Bag-Of-Words. It’s up to you. However, if you’re going to implement Deep Learning you might know that the best way is to turn your text data (that can be understood as sequences of word or sequences of characters) into low-dimensional floating-point vectors — don’t worry, I’ll explain this in a bit."
},
{
"code": null,
"e": 4913,
"s": 4690,
"text": "This is how a very basic text cleaning Python function would look like (this is a very simple way, you can implement the one that best works for your purpose — out there are very complete libraries such as Gensim or NLTK):"
},
{
"code": null,
"e": 5296,
"s": 4913,
"text": "def depure_data(data): #Removing URLs with a regular expression url_pattern = re.compile(r'https?://\\S+|www\\.\\S+') data = url_pattern.sub(r'', data) # Remove Emails data = re.sub('\\S*@\\S*\\s?', '', data) # Remove new line characters data = re.sub('\\s+', ' ', data) # Remove distracting single quotes data = re.sub(\"\\'\", \"\", data) return data"
},
{
"code": null,
"e": 5438,
"s": 5296,
"text": "Now a very simple way to remove repeating words from your dataset, following the idea that the shortest and longest ones are usually useless:"
},
{
"code": null,
"e": 5574,
"s": 5438,
"text": "def sent_to_words(sentences): for sentence in sentences: yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))"
},
{
"code": null,
"e": 5708,
"s": 5574,
"text": "Finally, a function to detokenize all sentences (this because I’ll use word embeddings and not this old-fashioned tokenizing method):"
},
{
"code": null,
"e": 5783,
"s": 5708,
"text": "def detokenize(text): return TreebankWordDetokenizer().detokenize(text)"
},
{
"code": null,
"e": 5848,
"s": 5783,
"text": "To run everything in the right order, you just need to run this:"
},
{
"code": null,
"e": 6154,
"s": 5848,
"text": "temp = []#Splitting pd.Series to listdata_to_list = train['selected_text'].values.tolist()for i in range(len(data_to_list)): temp.append(depure_data(data_to_list[i]))data_words = list(sent_to_words(temp))data = []for i in range(len(data_words)): data.append(detokenize(data_words[i]))print(data[:5])"
},
{
"code": null,
"e": 6305,
"s": 6154,
"text": "At this point, you will have transformed your noisy text dataset into a very flat and simple one. In this particular case, you’ll have gone from this:"
},
{
"code": null,
"e": 6407,
"s": 6305,
"text": "['I`d have responded, if I were going', 'Sooo SAD', 'bullying me', 'leave me alone', 'Sons of ****,']"
},
{
"code": null,
"e": 6416,
"s": 6407,
"text": "To this:"
},
{
"code": null,
"e": 6505,
"s": 6416,
"text": "['have responded if were going', 'sooo sad', 'bullying me', 'leave me alone', 'sons of']"
},
{
"code": null,
"e": 6862,
"s": 6505,
"text": "If you want to go even beyond, then take the stemming or lemmatizing paths, you’ll get much better results. In this particular how-to, will keep it this way just you to get that it’s totally possible to achieve great results skipping that step (if you’re building your model in a business context then you’ll be 100% in obligation to do so, don’t skip it!)"
},
{
"code": null,
"e": 7146,
"s": 6862,
"text": "Alright, it’s time to understand an extremely important step you’ll have to deal with when working with text data. Once you have your text data completely clean of noise, it’s time to transform it into floating-point tensors. In order to perform this task, we’ll use word-embeddings."
},
{
"code": null,
"e": 7646,
"s": 7146,
"text": "Word embeddings (or sometimes called word vectors) are learned from data and essentially are low-dimensional floating-point vectors (dense vectors, as opposed to sparse vectors obtained from processes such as one-hot-encoding) that pack information in few dimensions. Why would you use this method and not any other different and more simple? Because deep learning models converge easier with dense vectors than with sparse ones. Again, it always depends on the dataset nature and the business need."
},
{
"code": null,
"e": 7692,
"s": 7646,
"text": "There are two ways to obtain word embeddings:"
},
{
"code": null,
"e": 7847,
"s": 7692,
"text": "Use a pretrained word embedding stack on top of your model, just as you would use a pretrained NN layer (or group of layers) — a very infrequent approach."
},
{
"code": null,
"e": 8286,
"s": 7847,
"text": "Learn word embeddings from scratch. To achieve this, you’d start with random word vectors and progressively learn meaningful ones just as a NN would learn its weights. This is the option that we’ll use and actually is reasonable to learn a new embedding space with every single new task. Fortunately, this step is very straightforward with TensorFlow or Keras, and you’d implement word embedding just like one more layer in your NN stack."
},
{
"code": null,
"e": 8405,
"s": 8286,
"text": "Before moving forward, we need to take a previous step. We need to transform our array of text into 2D numeric arrays:"
},
{
"code": null,
"e": 8743,
"s": 8405,
"text": "from keras.preprocessing.text import Tokenizerfrom keras.preprocessing.sequence import pad_sequencesfrom keras import regularizersmax_words = 5000max_len = 200tokenizer = Tokenizer(num_words=max_words)tokenizer.fit_on_texts(data)sequences = tokenizer.texts_to_sequences(data)tweets = pad_sequences(sequences, maxlen=max_len)print(tweets)"
},
{
"code": null,
"e": 8787,
"s": 8743,
"text": "The output you’ll get would look like this:"
},
{
"code": null,
"e": 9009,
"s": 8787,
"text": "[[ 0 0 0 ... 68 146 41] [ 0 0 0 ... 0 397 65] [ 0 0 0 ... 0 0 11] ... [ 0 0 0 ... 372 10 3] [ 0 0 0 ... 24 542 4] [ 0 0 0 ... 2424 199 657]]"
},
{
"code": null,
"e": 9137,
"s": 9009,
"text": "What does the previous step mean? Let’s take the definition from the official Keras documentation, you’ll get better the point:"
},
{
"code": null,
"e": 9395,
"s": 9137,
"text": "This function transforms a list (of length num_samples) of sequences (lists of integers) into a 2D Numpy array of shape (num_samples, num_timesteps). num_timesteps is either the maxlen argument if provided, or the length of the longest sequence in the list."
},
{
"code": null,
"e": 9498,
"s": 9395,
"text": "Sequences that are shorter than num_timesteps are padded with value until they are num_timesteps long."
},
{
"code": null,
"e": 9584,
"s": 9498,
"text": "Sequences longer than num_timesteps are truncated so that they fit the desired length"
},
{
"code": null,
"e": 9903,
"s": 9584,
"text": "It’s extremely important you to keep in mind that no matter if you use TensorFlow or any other Astraction API such as Keras, you should get the same result at the end of your training. In this opportunity we’ll use Keras for obvious reasons: It’s extremely easy to implement. This is how you create an embedding layer:"
},
{
"code": null,
"e": 9975,
"s": 9903,
"text": "from keras.layers import Embeddingembedding_layer = Embedding(1000, 64)"
},
{
"code": null,
"e": 10604,
"s": 9975,
"text": "The above layer takes 2D integer tensors of shape (samples, sequence_length) and at least two arguments: the number of possible tokens and the dimensionality of the embeddings (here 1000 and 64, respectively). To be more figurative, just imagine the embedding layer is a dictionary that links integer indices to dense vectors. Finally, it returns a 3D floating-point tensor of shape (samples, sequence_length, embedding_dimensionality) that can now be processed by our neural network. Let’s talk about that topic, particularly about Recurrent Neural Networks that are the best when processing text-related sequences is required."
},
{
"code": null,
"e": 11485,
"s": 10604,
"text": "Usually other types of neural networks out there such as densely connected networks or convolutional networks have no memory, this means that every single input is processed independently with no relation with the other ones. This is the opposite of what you normally would do when reading a paragraph: when you’re reading you keep in memory what you’ve read in the previous lines , right? You have a sense of the whole meaning and this is exactly the same principle that RNNs adopt. They process sequences by iterating along the sequence elements and keeping information relative to what it has processed so far. The math that is under a RNN’s hood is, to be honest, a topic that you should cover by yourself in order to understand its logic. I suggest you to give a read to “Learning TensorFlow” by Tom Hope (available here) which explains all the process in a very easy manner."
},
{
"code": null,
"e": 11786,
"s": 11485,
"text": "In this article, I’ll implement three RNN types: a single LSTM (long short-term memory) model, a Bidirectional LSTM and a very infrequent used Conv1D model. As a bonus, I show how to implement a SimpleRNN model but to be honest, it’s not deployed in production anywhere because it’s extremely simple."
},
{
"code": null,
"e": 11932,
"s": 11786,
"text": "Coming back to our example, this is how the code would look like when implementing a single LSTM layer model with its respective embedding layer:"
},
{
"code": null,
"e": 12629,
"s": 11932,
"text": "from keras.models import Sequentialfrom keras import layersfrom keras import regularizersfrom keras import backend as Kfrom keras.callbacks import ModelCheckpointmodel1 = Sequential()model1.add(layers.Embedding(max_words, 20)) #The embedding layermodel1.add(layers.LSTM(15,dropout=0.5)) #Our LSTM layermodel1.add(layers.Dense(3,activation='softmax'))model1.compile(optimizer='rmsprop',loss='categorical_crossentropy', metrics=['accuracy'])checkpoint1 = ModelCheckpoint(\"best_model1.hdf5\", monitor='val_accuracy', verbose=1,save_best_only=True, mode='auto', period=1,save_weights_only=False)history = model1.fit(X_train, y_train, epochs=70,validation_data=(X_test, y_test),callbacks=[checkpoint1])"
},
{
"code": null,
"e": 13554,
"s": 12629,
"text": "There are a few things to highlight in the code above: when implementing a Keras Sequential model, it’s all about stacking layers. LSTM layers (as well as all other RNN layers) can take several arguments but the ones that I defined are 15 which is the number of hidden units within the layer (must be a positive integer and represents the dimensionality of the output space) and the dropout rate of the layer. Dropout is one of the most effective and most commonly used regularization techniques for NNs and consists of randomly turning off hidden units during training, that way the network does not rely 100% on all its neurons and instead, forces itself to find more meaningful patterns in the data in order to increase the metric you’re trying to optimize. There are several other arguments to pass, you can find the complete documentation here, but for this particular example, these settings will achieve good results."
},
{
"code": null,
"e": 13792,
"s": 13554,
"text": "FYI, sometimes it’s useful to stack several recurrent layers one after the other in order to increase the representational power of a network. If you want to do so then you’ll have to return full sequences of outputs. This is an example:"
},
{
"code": null,
"e": 13991,
"s": 13792,
"text": "model0 = Sequential()model0.add(layers.Embedding(max_words, 15))model0.add(layers.SimpleRNN(15,return_sequences=True))model0.add(layers.SimpleRNN(15))model0.add(layers.Dense(3,activation='softmax'))"
},
{
"code": null,
"e": 14305,
"s": 13991,
"text": "In our LSTM example I’m stacking a Dense layer with three output units that would be the 3 possible classes of our dataset. In order to make probabilistic outputs, it’s always good to use ‘softmax’ as activation function in the final layer. Use the next table when building a neural network and you feel confused:"
},
{
"code": null,
"e": 15093,
"s": 14305,
"text": "When compiling the model, I’m using RMSprop optimizer with its default learning rate but actually this is up to every developer. Some people love Adam, some others Adadelta, and so on. To be honest, RMSprop or Adam should be enough in most of the cases. If you don’t know what an optimizer is, it’s simply the mechanism that constantly computes the gradient of the loss and defines how to move against the loss function in order to find its global minima and therefore, find the best network’s parameters (the model kernel and its bias’ weights). As loss function, I use categorical_crossentropy (Check the table) that is typically used when you’re dealing with multiclass classification tasks. In the other hand, you would use binary_crossentropy when binary classification is required."
},
{
"code": null,
"e": 15375,
"s": 15093,
"text": "Finally, I’m using checkpoints to save the best model achieved in the training process. This is very useful when you need to get the model that best satisfies the metric you’re trying to optimize. Then the classic model.fit step and wait for it to complete the training iterations."
},
{
"code": null,
"e": 15456,
"s": 15375,
"text": "This is the validation score achieved by this NN architecture at its last epoch:"
},
{
"code": null,
"e": 15606,
"s": 15456,
"text": "Epoch 70/70645/645 [==============================] - ETA: 0s - loss: 0.3090 - accuracy: 0.8881Epoch 00070: val_accuracy did not improve from 0.84558"
},
{
"code": null,
"e": 15654,
"s": 15606,
"text": "Let’s compare this with a more complex network."
},
{
"code": null,
"e": 15714,
"s": 15654,
"text": "This is how our example’s BidRNN implementation looks like:"
},
{
"code": null,
"e": 16256,
"s": 15714,
"text": "model2 = Sequential()model2.add(layers.Embedding(max_words, 40, input_length=max_len))model2.add(layers.Bidirectional(layers.LSTM(20,dropout=0.6)))model2.add(layers.Dense(3,activation='softmax'))model2.compile(optimizer='rmsprop',loss='categorical_crossentropy', metrics=['accuracy'])checkpoint2 = ModelCheckpoint(\"best_model2.hdf5\", monitor='val_accuracy', verbose=1,save_best_only=True, mode='auto', period=1,save_weights_only=False)history = model2.fit(X_train, y_train, epochs=70,validation_data=(X_test, y_test),callbacks=[checkpoint2])"
},
{
"code": null,
"e": 16843,
"s": 16256,
"text": "Let’s understand better how a bidirectional layer works. It maximizes the order sensitivity of the RNNs: essentially it consists of two RNNs (LSTMs or GRUs) that process the input sequence in one different direction to finally merge representations. By doing this, they’re able to catch more complex patterns than a single RNN layer would catch. In other words, one of the layers interprets the sequences in chronological order and the second one do so in anti-chronological order, that’s why Bidirectional RNNs are widely used, because they offer greater performance than regular RNNs."
},
{
"code": null,
"e": 17063,
"s": 16843,
"text": "The way they are implemented is not complex, it is just one layer inside the other. If you read carefully, I’m using almost the same parameters but achieved about .3% more of validation accuracy on its overall training:"
},
{
"code": null,
"e": 17213,
"s": 17063,
"text": "Epoch 70/70644/645 [============================>.] - ETA: 0s - loss: 0.2876 - accuracy: 0.8965Epoch 00070: val_accuracy did not improve from 0.84849"
},
{
"code": null,
"e": 17922,
"s": 17213,
"text": "It’s a very good number even when it’s a very simple model and I wasn’t focused on hyperparameter tuning. I’m sure that if you dedicate yourself to adjust them then will get a very good result. Unfortunately, there’s no magical formula to do so, it’s all about adjusting its architecture and forcing it to learn every time more complex patterns and control its overfitting tendency with more regularization. One important thing to highlight is that if you see your model accuracy/loss stuck around certain value, it’s likely because the learning rate is too small and therefore making your optimizer to get stuck around a local minima of the loss function; make the LR bigger or simply try another optimizer."
},
{
"code": null,
"e": 18119,
"s": 17922,
"text": "It’s time to try another type of architecture which even it’s not the best for text classification, it’s well known by achieving fantastic results when processing text datasets. Let’s get into it."
},
{
"code": null,
"e": 18504,
"s": 18119,
"text": "I hope you’re still with me, because this is one of the fastest models out there when talking about convergence — it demands a cheaper computational cost. I know by prior experience that it tends to overfit extremely quick on small datasets. In this sense, just will implement it to show you how to do so in case it’s of your interest and also give you an overview about how it works."
},
{
"code": null,
"e": 19224,
"s": 18504,
"text": "It uses the same principles as classic 2D ConvNets used for image classification. Convolutional layers extract patches from 1D/2D tensors (depending on the type of task and layer) and apply the same convolutional transformations to every one of them (getting as output several subsequences). I won’t get deep in such explanation because that’s out of the scope of this article, but if you want to fully understand how these layers work I would suggest to you check the book previously recommended. The most important fact of these layers is that they can recognize patters in a sequence — A pattern learned at a certain position in a sentence can later be identified in a different position or even in another sentence."
},
{
"code": null,
"e": 19265,
"s": 19224,
"text": "This is how 1D ConvNets are implemented:"
},
{
"code": null,
"e": 19909,
"s": 19265,
"text": "model3.add(layers.Embedding(max_words, 40, input_length=max_len))model3.add(layers.Conv1D(20, 6, activation='relu',kernel_regularizer=regularizers.l1_l2(l1=2e-3, l2=2e-3),bias_regularizer=regularizers.l2(2e-3)))model3.add(layers.MaxPooling1D(5))model3.add(layers.Conv1D(20, 6, activation='relu',kernel_regularizer=regularizers.l1_l2(l1=2e-3, l2=2e-3),bias_regularizer=regularizers.l2(2e-3)))model3.add(layers.GlobalMaxPooling1D())model3.add(layers.Dense(3,activation='softmax'))model3.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['acc'])history = model3.fit(X_train, y_train, epochs=70,validation_data=(X_test, y_test))"
},
{
"code": null,
"e": 20410,
"s": 19909,
"text": "Where Conv1D layers are in charge of computing the convolution operations while MaxPooling1D layers’ main task is to reduce the dimensionality of every convolutional output. Once the convolution operation is performed, the MaxPooling window extracts the highest value within it and outputs patches of maximum values. It’s important to highlight the importance of regularizers in this type of configuration, otherwise your network will learn meaningless patterns and overfit extremely fast — just FYI."
},
{
"code": null,
"e": 20502,
"s": 20410,
"text": "To contrast how the previous model performs, this is the metric achieved at the last epoch:"
},
{
"code": null,
"e": 20634,
"s": 20502,
"text": "Epoch 70/70645/645 [==============================] - 5s 7ms/step - loss: 0.3096 - acc: 0.9173 - val_loss: 0.5819 - val_acc: 0.8195"
},
{
"code": null,
"e": 20770,
"s": 20634,
"text": "And its best validation accuracy obtained was around 82%. It overfits very fast even when I’ve implemented very drastic regularization."
},
{
"code": null,
"e": 21031,
"s": 20770,
"text": "At this point, the best model so far has been the Bidirectional RNN. Please keep in mind that these metrics were obtained with little-to-zero hyperparameter tuning. To understand in a better way how well its predictions are, let’s look at its confusion matrix:"
},
{
"code": null,
"e": 21402,
"s": 21031,
"text": "From the above’s image, we can deduce: 81% of positive ratings were classified as positive, 80% of negative ratings were classified as negative and 91% of neutral ratings were classified as neutral. These are not the best predictions, but are a good baseline to work on even better models. In a business scenario you would need to be close to 95% in the most easy cases."
},
{
"code": null,
"e": 21494,
"s": 21402,
"text": "If you want to test how it works on an input made by yourself, just compute the next lines:"
},
{
"code": null,
"e": 21749,
"s": 21494,
"text": "sentiment = ['Neutral','Negative','Positive']sequence = tokenizer.texts_to_sequences(['this data science article is the best ever'])test = pad_sequences(sequence, maxlen=max_len)sentiment[np.around(best_model.predict(test), decimals=0).argmax(axis=1)[0]]"
},
{
"code": null,
"e": 21773,
"s": 21749,
"text": "And the output will be:"
},
{
"code": null,
"e": 21784,
"s": 21773,
"text": "'Positive'"
},
{
"code": null,
"e": 22067,
"s": 21784,
"text": "Alright, we’ve reached the end of this post. I encourage you to implement all models by yourself and focus on hyperparameter tuning which is one of the tasks that takes longer. Once you’ve reached a good number, I’ll see you back here to guide you through that model’s deployment 😊."
}
] |
PyQt5 - QStackedWidget | Functioning of QStackedWidget is similar to QTabWidget. It also helps in the efficient use of window’s client area.
QStackedWidget provides a stack of widgets, only one of which can be viewed at a time. It is a useful layout built on top of QStackedLayout.
A parent QStackedWidget object is populated with more than one child widget.
self.Stack = QStackedWidget (self)
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack3 = QWidget()
self.Stack.addWidget (self.stack1)
self.Stack.addWidget (self.stack2)
self.Stack.addWidget (self.stack3)
Each child widget can have its own layout of form elements. QStackedWidget on its own cannot switch between the pages. It is linked with the currently selected index of QListWidget.
self.leftlist = QListWidget ()
self.leftlist.insertItem (0, 'Contact' )
self.leftlist.insertItem (1, 'Personal' )
self.leftlist.insertItem (2, 'Educational' )
self.leftlist.currentRowChanged.connect(self.display)
Here, the currentRowChanged() signal of QListWidget is connected to display() function, which changes the view of stacked widget.
def display(self,i):
self.Stack.setCurrentIndex(i)
The complete code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class stackedExample(QWidget):
def __init__(self):
super(stackedExample, self).__init__()
self.leftlist = QListWidget ()
self.leftlist.insertItem (0, 'Contact' )
self.leftlist.insertItem (1, 'Personal' )
self.leftlist.insertItem (2, 'Educational' )
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack3 = QWidget()
self.stack1UI()
self.stack2UI()
self.stack3UI()
self.Stack = QStackedWidget (self)
self.Stack.addWidget (self.stack1)
self.Stack.addWidget (self.stack2)
self.Stack.addWidget (self.stack3)
hbox = QHBoxLayout(self)
hbox.addWidget(self.leftlist)
hbox.addWidget(self.Stack)
self.setLayout(hbox)
self.leftlist.currentRowChanged.connect(self.display)
self.setGeometry(300, 50, 10,10)
self.setWindowTitle('StackedWidget demo')
self.show()
def stack1UI(self):
layout = QFormLayout()
layout.addRow("Name",QLineEdit())
layout.addRow("Address",QLineEdit())
#self.setTabText(0,"Contact Details")
self.stack1.setLayout(layout)
def stack2UI(self):
layout = QFormLayout()
sex = QHBoxLayout()
sex.addWidget(QRadioButton("Male"))
sex.addWidget(QRadioButton("Female"))
layout.addRow(QLabel("Sex"),sex)
layout.addRow("Date of Birth",QLineEdit())
self.stack2.setLayout(layout)
def stack3UI(self):
layout = QHBoxLayout()
layout.addWidget(QLabel("subjects"))
layout.addWidget(QCheckBox("Physics"))
layout.addWidget(QCheckBox("Maths"))
self.stack3.setLayout(layout)
def display(self,i):
self.Stack.setCurrentIndex(i)
def main():
app = QApplication(sys.argv)
ex = stackedExample()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The above code produces the following output −
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2079,
"s": 1963,
"text": "Functioning of QStackedWidget is similar to QTabWidget. It also helps in the efficient use of window’s client area."
},
{
"code": null,
"e": 2220,
"s": 2079,
"text": "QStackedWidget provides a stack of widgets, only one of which can be viewed at a time. It is a useful layout built on top of QStackedLayout."
},
{
"code": null,
"e": 2297,
"s": 2220,
"text": "A parent QStackedWidget object is populated with more than one child widget."
},
{
"code": null,
"e": 2510,
"s": 2297,
"text": "self.Stack = QStackedWidget (self)\nself.stack1 = QWidget()\nself.stack2 = QWidget()\nself.stack3 = QWidget()\n\nself.Stack.addWidget (self.stack1)\nself.Stack.addWidget (self.stack2)\nself.Stack.addWidget (self.stack3)"
},
{
"code": null,
"e": 2692,
"s": 2510,
"text": "Each child widget can have its own layout of form elements. QStackedWidget on its own cannot switch between the pages. It is linked with the currently selected index of QListWidget."
},
{
"code": null,
"e": 2905,
"s": 2692,
"text": "self.leftlist = QListWidget ()\nself.leftlist.insertItem (0, 'Contact' )\nself.leftlist.insertItem (1, 'Personal' )\nself.leftlist.insertItem (2, 'Educational' )\nself.leftlist.currentRowChanged.connect(self.display)"
},
{
"code": null,
"e": 3035,
"s": 2905,
"text": "Here, the currentRowChanged() signal of QListWidget is connected to display() function, which changes the view of stacked widget."
},
{
"code": null,
"e": 3089,
"s": 3035,
"text": "def display(self,i):\n self.Stack.setCurrentIndex(i)"
},
{
"code": null,
"e": 3123,
"s": 3089,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 5054,
"s": 3123,
"text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass stackedExample(QWidget):\n def __init__(self):\n super(stackedExample, self).__init__()\n\t\tself.leftlist = QListWidget ()\n self.leftlist.insertItem (0, 'Contact' )\n self.leftlist.insertItem (1, 'Personal' )\n self.leftlist.insertItem (2, 'Educational' )\n\t\t\n self.stack1 = QWidget()\n self.stack2 = QWidget()\n self.stack3 = QWidget()\n\t\t\n self.stack1UI()\n self.stack2UI()\n self.stack3UI()\n\t\t\n self.Stack = QStackedWidget (self)\n self.Stack.addWidget (self.stack1)\n self.Stack.addWidget (self.stack2)\n self.Stack.addWidget (self.stack3)\n\t\t\n hbox = QHBoxLayout(self)\n hbox.addWidget(self.leftlist)\n hbox.addWidget(self.Stack)\n\n self.setLayout(hbox)\n self.leftlist.currentRowChanged.connect(self.display)\n self.setGeometry(300, 50, 10,10)\n self.setWindowTitle('StackedWidget demo')\n self.show()\n\t\t\n def stack1UI(self):\n layout = QFormLayout()\n layout.addRow(\"Name\",QLineEdit())\n layout.addRow(\"Address\",QLineEdit())\n #self.setTabText(0,\"Contact Details\")\n self.stack1.setLayout(layout)\n\t\t\n def stack2UI(self):\n layout = QFormLayout()\n sex = QHBoxLayout()\n sex.addWidget(QRadioButton(\"Male\"))\n sex.addWidget(QRadioButton(\"Female\"))\n layout.addRow(QLabel(\"Sex\"),sex)\n layout.addRow(\"Date of Birth\",QLineEdit())\n\t\t\n self.stack2.setLayout(layout)\n\t\t\n def stack3UI(self):\n layout = QHBoxLayout()\n layout.addWidget(QLabel(\"subjects\"))\n layout.addWidget(QCheckBox(\"Physics\"))\n layout.addWidget(QCheckBox(\"Maths\"))\n self.stack3.setLayout(layout)\n\t\t\n def display(self,i):\n self.Stack.setCurrentIndex(i)\n\t\t\ndef main():\n app = QApplication(sys.argv)\n ex = stackedExample()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 5101,
"s": 5054,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 5138,
"s": 5101,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 5148,
"s": 5138,
"text": " ALAA EID"
},
{
"code": null,
"e": 5155,
"s": 5148,
"text": " Print"
},
{
"code": null,
"e": 5166,
"s": 5155,
"text": " Add Notes"
}
] |
Unix / Linux - Using Shell Arrays | In this chapter, we will discuss how to use shell arrays in Unix. A shell variable is capable enough to hold a single value. These variables are called scalar variables.
Shell supports a different type of variable called an array variable. This can hold multiple values at the same time. Arrays provide a method of grouping a set of variables. Instead of creating a new name for each variable that is required, you can use a single array variable that stores all the other variables.
All the naming rules discussed for Shell Variables would be applicable while naming arrays.
The difference between an array variable and a scalar variable can be explained as follows.
Suppose you are trying to represent the names of various students as a set of variables. Each of the individual variables is a scalar variable as follows −
NAME01="Zara"
NAME02="Qadir"
NAME03="Mahnaz"
NAME04="Ayan"
NAME05="Daisy"
We can use a single array to store all the above mentioned names. Following is the simplest method of creating an array variable. This helps assign a value to one of its indices.
array_name[index]=value
Here array_name is the name of the array, index is the index of the item in the array that you want to set, and value is the value you want to set for that item.
As an example, the following commands −
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
If you are using the ksh shell, here is the syntax of array initialization −
set -A array_name value1 value2 ... valuen
If you are using the bash shell, here is the syntax of array initialization −
array_name=(value1 ... valuen)
After you have set any array variable, you access it as follows −
${array_name[index]}
Here array_name is the name of the array, and index is the index of the value to be accessed. Following is an example to understand the concept −
#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
The above example will generate the following result −
$./test.sh
First Index: Zara
Second Index: Qadir
You can access all the items in an array in one of the following ways −
${array_name[*]}
${array_name[@]}
Here array_name is the name of the array you are interested in. Following example will help you understand the concept −
#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"
The above example will generate the following result −
$./test.sh
First Method: Zara Qadir Mahnaz Ayan Daisy
Second Method: Zara Qadir Mahnaz Ayan Daisy
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": 2917,
"s": 2747,
"text": "In this chapter, we will discuss how to use shell arrays in Unix. A shell variable is capable enough to hold a single value. These variables are called scalar variables."
},
{
"code": null,
"e": 3231,
"s": 2917,
"text": "Shell supports a different type of variable called an array variable. This can hold multiple values at the same time. Arrays provide a method of grouping a set of variables. Instead of creating a new name for each variable that is required, you can use a single array variable that stores all the other variables."
},
{
"code": null,
"e": 3323,
"s": 3231,
"text": "All the naming rules discussed for Shell Variables would be applicable while naming arrays."
},
{
"code": null,
"e": 3415,
"s": 3323,
"text": "The difference between an array variable and a scalar variable can be explained as follows."
},
{
"code": null,
"e": 3571,
"s": 3415,
"text": "Suppose you are trying to represent the names of various students as a set of variables. Each of the individual variables is a scalar variable as follows −"
},
{
"code": null,
"e": 3645,
"s": 3571,
"text": "NAME01=\"Zara\"\nNAME02=\"Qadir\"\nNAME03=\"Mahnaz\"\nNAME04=\"Ayan\"\nNAME05=\"Daisy\""
},
{
"code": null,
"e": 3824,
"s": 3645,
"text": "We can use a single array to store all the above mentioned names. Following is the simplest method of creating an array variable. This helps assign a value to one of its indices."
},
{
"code": null,
"e": 3849,
"s": 3824,
"text": "array_name[index]=value\n"
},
{
"code": null,
"e": 4011,
"s": 3849,
"text": "Here array_name is the name of the array, index is the index of the item in the array that you want to set, and value is the value you want to set for that item."
},
{
"code": null,
"e": 4051,
"s": 4011,
"text": "As an example, the following commands −"
},
{
"code": null,
"e": 4130,
"s": 4051,
"text": "NAME[0]=\"Zara\"\nNAME[1]=\"Qadir\"\nNAME[2]=\"Mahnaz\"\nNAME[3]=\"Ayan\"\nNAME[4]=\"Daisy\""
},
{
"code": null,
"e": 4207,
"s": 4130,
"text": "If you are using the ksh shell, here is the syntax of array initialization −"
},
{
"code": null,
"e": 4251,
"s": 4207,
"text": "set -A array_name value1 value2 ... valuen\n"
},
{
"code": null,
"e": 4329,
"s": 4251,
"text": "If you are using the bash shell, here is the syntax of array initialization −"
},
{
"code": null,
"e": 4361,
"s": 4329,
"text": "array_name=(value1 ... valuen)\n"
},
{
"code": null,
"e": 4427,
"s": 4361,
"text": "After you have set any array variable, you access it as follows −"
},
{
"code": null,
"e": 4449,
"s": 4427,
"text": "${array_name[index]}\n"
},
{
"code": null,
"e": 4595,
"s": 4449,
"text": "Here array_name is the name of the array, and index is the index of the value to be accessed. Following is an example to understand the concept −"
},
{
"code": null,
"e": 4748,
"s": 4595,
"text": "#!/bin/sh\n\nNAME[0]=\"Zara\"\nNAME[1]=\"Qadir\"\nNAME[2]=\"Mahnaz\"\nNAME[3]=\"Ayan\"\nNAME[4]=\"Daisy\"\necho \"First Index: ${NAME[0]}\"\necho \"Second Index: ${NAME[1]}\""
},
{
"code": null,
"e": 4803,
"s": 4748,
"text": "The above example will generate the following result −"
},
{
"code": null,
"e": 4853,
"s": 4803,
"text": "$./test.sh\nFirst Index: Zara\nSecond Index: Qadir\n"
},
{
"code": null,
"e": 4925,
"s": 4853,
"text": "You can access all the items in an array in one of the following ways −"
},
{
"code": null,
"e": 4960,
"s": 4925,
"text": "${array_name[*]}\n${array_name[@]}\n"
},
{
"code": null,
"e": 5081,
"s": 4960,
"text": "Here array_name is the name of the array you are interested in. Following example will help you understand the concept −"
},
{
"code": null,
"e": 5236,
"s": 5081,
"text": "#!/bin/sh\n\nNAME[0]=\"Zara\"\nNAME[1]=\"Qadir\"\nNAME[2]=\"Mahnaz\"\nNAME[3]=\"Ayan\"\nNAME[4]=\"Daisy\"\necho \"First Method: ${NAME[*]}\"\necho \"Second Method: ${NAME[@]}\""
},
{
"code": null,
"e": 5291,
"s": 5236,
"text": "The above example will generate the following result −"
},
{
"code": null,
"e": 5390,
"s": 5291,
"text": "$./test.sh\nFirst Method: Zara Qadir Mahnaz Ayan Daisy\nSecond Method: Zara Qadir Mahnaz Ayan Daisy\n"
},
{
"code": null,
"e": 5425,
"s": 5390,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 5453,
"s": 5425,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5487,
"s": 5453,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5504,
"s": 5487,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5537,
"s": 5504,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5548,
"s": 5537,
"text": " Pradeep D"
},
{
"code": null,
"e": 5583,
"s": 5548,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5599,
"s": 5583,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 5632,
"s": 5599,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5644,
"s": 5632,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 5676,
"s": 5644,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5684,
"s": 5676,
"text": " Uplatz"
},
{
"code": null,
"e": 5691,
"s": 5684,
"text": " Print"
},
{
"code": null,
"e": 5702,
"s": 5691,
"text": " Add Notes"
}
] |
Use Python to Stylize the Excel Formatting | by Yeung WONG | Towards Data Science | Do you have to regularly update the reports day after day? Have you ever thought of a way to automate these tedious, boring, and robotic works? You may say ‘Yes, but I can’t since there are lots of formatting stuff I need to manually add to Excel’. Today, I am going to show you how Python can work on Excel spreadsheet formatting and automatically generate the report.
I am a cryptocurrency enthusiast and I would check the price for different coins day by day. However, it is extremely time-consuming to check all the coins one by one and that’s why I would like to use a program to automatically generate the summary report for me every morning. If you are interested to know more financial data analysis, feel free to check my publication.
medium.com
All codes and data are uploaded to my GitHub. You can check and folk this repo to further study. =)
First of all, we need to collect the data to display in the table. For example, you may query the data from the company database. You may obtain the data from your business partner. Or just like my case, I scrape the data from the Internet instantly. The data source I used here is CoinDesk API. For more details about how this API works and the parameter settings are, you can check my article below.
medium.com
import jsonfrom urllib import requesturl = "https://production.api.coindesk.com/v2/tb/price/ticker?assets=all"response = request.urlopen(url)data = json.loads(response.read().decode())
By the above code, we can easily obtain the latest cryptocurrency pricing for different coins. I have shown below how the data should look like.
{'statusCode': 200, 'message': 'OK', 'data': {'BTC': {'iso': 'BTC', 'name': 'Bitcoin', 'slug': 'bitcoin', 'change': {'percent': 0.6642429710971107, 'value': 298.538427}, 'ohlc': {'o': 44944.160494, 'h': 46843.67, 'l': 43480.540171, 'c': 45242.698921}, 'circulatingSupply': 18814943.79249204, 'marketCap': 851238837219.2552, 'ts': 1631590859000, 'src': 'tb'}, 'ETH': {...}}}
However, the data is in JSON format which is not easy to read. Therefore, we have to preprocess the data into the table format.
def flatten_json(coin_dict): flatten_dict = {} def flatten(x, name=''): if type(x) is dict: for key in x: flatten(x[key], name + key + '_') else: flatten_dict[name[:-1]] = x flatten(coin_dict) return flatten_dictimport pandas as pdmaster_df = pd.DataFrame()for coin in data['data'].keys(): temp_df = pd.json_normalize(flatten_json(data['data'][coin])) master_df = master_df.append(temp_df)master_df = master_df[['iso', 'name', 'ohlc_o', 'ohlc_h', 'ohlc_l', 'ohlc_c', 'change_percent']].reset_index(drop=True)master_df.columns = ['Symbol', 'Name', 'Open', 'High', 'Low', 'Close', 'Pct_Change']master_df.iloc[:, 2:] = master_df.iloc[:, 2:].apply(lambda x: round(x, 2))master_df['Pct_Change'] = master_df['Pct_Change'] / 100master_df = master_df.sort_values('Pct_Change', ascending=False).reset_index(drop=True)master_df.to_csv('master_df.csv', index=False)master_df.head()
In order to transform the JSON into the table, you can follow these steps.
Flatten the dictionary in the JSON for every coin dataAppend all the coin data frames into one master data frameSelect the columns that we are interested inRename the columns for easy referenceRounding the figures to simplify the tableSort by the Percentage Change
Flatten the dictionary in the JSON for every coin data
Append all the coin data frames into one master data frame
Select the columns that we are interested in
Rename the columns for easy reference
Rounding the figures to simplify the table
Sort by the Percentage Change
Finally, it comes to the main dish. Just remember one thing, before writing the code, you should have a design in mind first. For example, below is my draft template. The reason to have the draft is because it helps you better define the column or index to put the elements (title, table, remark, etc).
1. Add the table to the excel
file_name = "Cryptocurrency.xlsx"sheet_name = "Summary"writer = pd.ExcelWriter(file_name, engine='xlsxwriter')master_df.to_excel(writer, sheet_name=sheet_name, startrow = 2, index = False)
Just one point to note, you may see that there is a parameter startrow set to 2. It is because we would like to leave the first two rows for the title and the spacing and we will start writing the table in row 3 (Python count value starting from 0 so basically setting as 2 means the 3rd row)
2. Add the title to the excel
from datetime import datetimeworkbook = writer.bookworksheet = writer.sheets[sheet_name]worksheet.write(0, 0, 'Cryptocurrency Pricing Summary on '+datetime.now().strftime('%d %b %Y'), workbook.add_format({'bold': True, 'color': '#E26B0A', 'size': 14}))
To define which cell to write the text, you can count from top to bottom then from left to right. For example, if you are writing A1, then it is (0, 0). If you are writing C4, then it should be (3, 2).
3. Add the remark to the excel
worksheet.write(len(master_df)+4, 0, 'Remark:', workbook.add_format({'bold': True}))worksheet.write(len(master_df)+5, 0, 'The last update time is ' + datetime.now().strftime('%H:%M') + '.')
Here is one trick to bear in mind. Since the data frame may have a different number of rows in every update, you should better consider its records when writing the remark string. For example, here I set the row index as len(master_df)+4 which is the number of rows in the table plus the title and spacings.
4. Add the color to the table header
header_format = workbook.add_format({'bold': True, 'text_wrap': True, 'fg_color': '#FDE9D9', 'border': 1})for col_num, value in enumerate(master_df.columns.values): worksheet.write(2, col_num, value, header_format)
For the table headers, two parameters are introduced. The first one is text_wrap. It is set to True so that the text for the header will be wrapped to the next line if the space is not enough to display. The second one is fg_color. It is used to set the foreground color of the cell.
5. Add the border to the table
row_idx, col_idx = master_df.shapefor r in range(row_idx): for c in range(col_idx): if c == 6: worksheet.write(r + 3, c, master_df.values[r, c], workbook.add_format({'border': 1, 'num_format': '0.00%'})) else: worksheet.write(r + 3, c, master_df.values[r, c], workbook.add_format({'border': 1, 'num_format': '0.00'}))
The trick is similar to previous cases. Just remember to set the row index to be r+3 because there are three rows ahead of the first value in the table.
6. Set the Column Width
worksheet.set_column(0, 6, 12)worksheet.set_column(1, 1, 20)
For your reference, the function parameter is as follow: (start column index, end column index, column width)
I hope this article can help those who have to regularly update the Excel spreadsheet. If you would like to know more office tricks with programming, you can subscribe to my medium and I will update and share more skills with you all. =)
If you find my article useful, please endorse my skills on my linkedIn page to encourage me to write more articles.
Originally published on cydalytics.blogspot.com | [
{
"code": null,
"e": 542,
"s": 172,
"text": "Do you have to regularly update the reports day after day? Have you ever thought of a way to automate these tedious, boring, and robotic works? You may say ‘Yes, but I can’t since there are lots of formatting stuff I need to manually add to Excel’. Today, I am going to show you how Python can work on Excel spreadsheet formatting and automatically generate the report."
},
{
"code": null,
"e": 916,
"s": 542,
"text": "I am a cryptocurrency enthusiast and I would check the price for different coins day by day. However, it is extremely time-consuming to check all the coins one by one and that’s why I would like to use a program to automatically generate the summary report for me every morning. If you are interested to know more financial data analysis, feel free to check my publication."
},
{
"code": null,
"e": 927,
"s": 916,
"text": "medium.com"
},
{
"code": null,
"e": 1027,
"s": 927,
"text": "All codes and data are uploaded to my GitHub. You can check and folk this repo to further study. =)"
},
{
"code": null,
"e": 1429,
"s": 1027,
"text": "First of all, we need to collect the data to display in the table. For example, you may query the data from the company database. You may obtain the data from your business partner. Or just like my case, I scrape the data from the Internet instantly. The data source I used here is CoinDesk API. For more details about how this API works and the parameter settings are, you can check my article below."
},
{
"code": null,
"e": 1440,
"s": 1429,
"text": "medium.com"
},
{
"code": null,
"e": 1625,
"s": 1440,
"text": "import jsonfrom urllib import requesturl = \"https://production.api.coindesk.com/v2/tb/price/ticker?assets=all\"response = request.urlopen(url)data = json.loads(response.read().decode())"
},
{
"code": null,
"e": 1770,
"s": 1625,
"text": "By the above code, we can easily obtain the latest cryptocurrency pricing for different coins. I have shown below how the data should look like."
},
{
"code": null,
"e": 2170,
"s": 1770,
"text": "{'statusCode': 200, 'message': 'OK', 'data': {'BTC': {'iso': 'BTC', 'name': 'Bitcoin', 'slug': 'bitcoin', 'change': {'percent': 0.6642429710971107, 'value': 298.538427}, 'ohlc': {'o': 44944.160494, 'h': 46843.67, 'l': 43480.540171, 'c': 45242.698921}, 'circulatingSupply': 18814943.79249204, 'marketCap': 851238837219.2552, 'ts': 1631590859000, 'src': 'tb'}, 'ETH': {...}}}"
},
{
"code": null,
"e": 2298,
"s": 2170,
"text": "However, the data is in JSON format which is not easy to read. Therefore, we have to preprocess the data into the table format."
},
{
"code": null,
"e": 3238,
"s": 2298,
"text": "def flatten_json(coin_dict): flatten_dict = {} def flatten(x, name=''): if type(x) is dict: for key in x: flatten(x[key], name + key + '_') else: flatten_dict[name[:-1]] = x flatten(coin_dict) return flatten_dictimport pandas as pdmaster_df = pd.DataFrame()for coin in data['data'].keys(): temp_df = pd.json_normalize(flatten_json(data['data'][coin])) master_df = master_df.append(temp_df)master_df = master_df[['iso', 'name', 'ohlc_o', 'ohlc_h', 'ohlc_l', 'ohlc_c', 'change_percent']].reset_index(drop=True)master_df.columns = ['Symbol', 'Name', 'Open', 'High', 'Low', 'Close', 'Pct_Change']master_df.iloc[:, 2:] = master_df.iloc[:, 2:].apply(lambda x: round(x, 2))master_df['Pct_Change'] = master_df['Pct_Change'] / 100master_df = master_df.sort_values('Pct_Change', ascending=False).reset_index(drop=True)master_df.to_csv('master_df.csv', index=False)master_df.head()"
},
{
"code": null,
"e": 3313,
"s": 3238,
"text": "In order to transform the JSON into the table, you can follow these steps."
},
{
"code": null,
"e": 3578,
"s": 3313,
"text": "Flatten the dictionary in the JSON for every coin dataAppend all the coin data frames into one master data frameSelect the columns that we are interested inRename the columns for easy referenceRounding the figures to simplify the tableSort by the Percentage Change"
},
{
"code": null,
"e": 3633,
"s": 3578,
"text": "Flatten the dictionary in the JSON for every coin data"
},
{
"code": null,
"e": 3692,
"s": 3633,
"text": "Append all the coin data frames into one master data frame"
},
{
"code": null,
"e": 3737,
"s": 3692,
"text": "Select the columns that we are interested in"
},
{
"code": null,
"e": 3775,
"s": 3737,
"text": "Rename the columns for easy reference"
},
{
"code": null,
"e": 3818,
"s": 3775,
"text": "Rounding the figures to simplify the table"
},
{
"code": null,
"e": 3848,
"s": 3818,
"text": "Sort by the Percentage Change"
},
{
"code": null,
"e": 4151,
"s": 3848,
"text": "Finally, it comes to the main dish. Just remember one thing, before writing the code, you should have a design in mind first. For example, below is my draft template. The reason to have the draft is because it helps you better define the column or index to put the elements (title, table, remark, etc)."
},
{
"code": null,
"e": 4181,
"s": 4151,
"text": "1. Add the table to the excel"
},
{
"code": null,
"e": 4370,
"s": 4181,
"text": "file_name = \"Cryptocurrency.xlsx\"sheet_name = \"Summary\"writer = pd.ExcelWriter(file_name, engine='xlsxwriter')master_df.to_excel(writer, sheet_name=sheet_name, startrow = 2, index = False)"
},
{
"code": null,
"e": 4663,
"s": 4370,
"text": "Just one point to note, you may see that there is a parameter startrow set to 2. It is because we would like to leave the first two rows for the title and the spacing and we will start writing the table in row 3 (Python count value starting from 0 so basically setting as 2 means the 3rd row)"
},
{
"code": null,
"e": 4693,
"s": 4663,
"text": "2. Add the title to the excel"
},
{
"code": null,
"e": 4947,
"s": 4693,
"text": "from datetime import datetimeworkbook = writer.bookworksheet = writer.sheets[sheet_name]worksheet.write(0, 0, 'Cryptocurrency Pricing Summary on '+datetime.now().strftime('%d %b %Y'), workbook.add_format({'bold': True, 'color': '#E26B0A', 'size': 14}))"
},
{
"code": null,
"e": 5149,
"s": 4947,
"text": "To define which cell to write the text, you can count from top to bottom then from left to right. For example, if you are writing A1, then it is (0, 0). If you are writing C4, then it should be (3, 2)."
},
{
"code": null,
"e": 5180,
"s": 5149,
"text": "3. Add the remark to the excel"
},
{
"code": null,
"e": 5370,
"s": 5180,
"text": "worksheet.write(len(master_df)+4, 0, 'Remark:', workbook.add_format({'bold': True}))worksheet.write(len(master_df)+5, 0, 'The last update time is ' + datetime.now().strftime('%H:%M') + '.')"
},
{
"code": null,
"e": 5678,
"s": 5370,
"text": "Here is one trick to bear in mind. Since the data frame may have a different number of rows in every update, you should better consider its records when writing the remark string. For example, here I set the row index as len(master_df)+4 which is the number of rows in the table plus the title and spacings."
},
{
"code": null,
"e": 5715,
"s": 5678,
"text": "4. Add the color to the table header"
},
{
"code": null,
"e": 5933,
"s": 5715,
"text": "header_format = workbook.add_format({'bold': True, 'text_wrap': True, 'fg_color': '#FDE9D9', 'border': 1})for col_num, value in enumerate(master_df.columns.values): worksheet.write(2, col_num, value, header_format)"
},
{
"code": null,
"e": 6217,
"s": 5933,
"text": "For the table headers, two parameters are introduced. The first one is text_wrap. It is set to True so that the text for the header will be wrapped to the next line if the space is not enough to display. The second one is fg_color. It is used to set the foreground color of the cell."
},
{
"code": null,
"e": 6248,
"s": 6217,
"text": "5. Add the border to the table"
},
{
"code": null,
"e": 6605,
"s": 6248,
"text": "row_idx, col_idx = master_df.shapefor r in range(row_idx): for c in range(col_idx): if c == 6: worksheet.write(r + 3, c, master_df.values[r, c], workbook.add_format({'border': 1, 'num_format': '0.00%'})) else: worksheet.write(r + 3, c, master_df.values[r, c], workbook.add_format({'border': 1, 'num_format': '0.00'}))"
},
{
"code": null,
"e": 6758,
"s": 6605,
"text": "The trick is similar to previous cases. Just remember to set the row index to be r+3 because there are three rows ahead of the first value in the table."
},
{
"code": null,
"e": 6782,
"s": 6758,
"text": "6. Set the Column Width"
},
{
"code": null,
"e": 6843,
"s": 6782,
"text": "worksheet.set_column(0, 6, 12)worksheet.set_column(1, 1, 20)"
},
{
"code": null,
"e": 6953,
"s": 6843,
"text": "For your reference, the function parameter is as follow: (start column index, end column index, column width)"
},
{
"code": null,
"e": 7191,
"s": 6953,
"text": "I hope this article can help those who have to regularly update the Excel spreadsheet. If you would like to know more office tricks with programming, you can subscribe to my medium and I will update and share more skills with you all. =)"
},
{
"code": null,
"e": 7307,
"s": 7191,
"text": "If you find my article useful, please endorse my skills on my linkedIn page to encourage me to write more articles."
}
] |
TensorFlow - Installation | To install TensorFlow, it is important to have “Python” installed in your system. Python version 3.4+ is considered the best to start with TensorFlow installation.
Consider the following steps to install TensorFlow in Windows operating system.
Step 1 − Verify the python version being installed.
Step 2 − A user can pick up any mechanism to install TensorFlow in the system. We recommend “pip” and “Anaconda”. Pip is a command used for executing and installing modules in Python.
Before we install TensorFlow, we need to install Anaconda framework in our system.
After successful installation, check in command prompt through “conda” command. The execution of command is displayed below −
Step 3 − Execute the following command to initialize the installation of TensorFlow −
conda create --name tensorflow python = 3.5
It downloads the necessary packages needed for TensorFlow setup.
Step 4 − After successful environmental setup, it is important to activate TensorFlow module.
activate tensorflow
Step 5 − Use pip to install “Tensorflow” in the system. The command used for installation is mentioned as below −
pip install tensorflow
And,
pip install tensorflow-gpu
After successful installation, it is important to know the sample program execution of TensorFlow.
Following example helps us understand the basic program creation “Hello World” in TensorFlow.
The code for first program implementation is mentioned below −
>> activate tensorflow
>> python (activating python shell)
>> import tensorflow as tf
>> hello = tf.constant(‘Hello, Tensorflow!’)
>> sess = tf.Session()
>> print(sess.run(hello))
61 Lectures
9 hours
Abhishek And Pukhraj
57 Lectures
7 hours
Abhishek And Pukhraj
52 Lectures
7 hours
Abhishek And Pukhraj
52 Lectures
6 hours
Abhishek And Pukhraj
29 Lectures
3.5 hours
Mohammad Nauman
82 Lectures
4 hours
Anis Koubaa
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2479,
"s": 2315,
"text": "To install TensorFlow, it is important to have “Python” installed in your system. Python version 3.4+ is considered the best to start with TensorFlow installation."
},
{
"code": null,
"e": 2559,
"s": 2479,
"text": "Consider the following steps to install TensorFlow in Windows operating system."
},
{
"code": null,
"e": 2611,
"s": 2559,
"text": "Step 1 − Verify the python version being installed."
},
{
"code": null,
"e": 2795,
"s": 2611,
"text": "Step 2 − A user can pick up any mechanism to install TensorFlow in the system. We recommend “pip” and “Anaconda”. Pip is a command used for executing and installing modules in Python."
},
{
"code": null,
"e": 2878,
"s": 2795,
"text": "Before we install TensorFlow, we need to install Anaconda framework in our system."
},
{
"code": null,
"e": 3004,
"s": 2878,
"text": "After successful installation, check in command prompt through “conda” command. The execution of command is displayed below −"
},
{
"code": null,
"e": 3090,
"s": 3004,
"text": "Step 3 − Execute the following command to initialize the installation of TensorFlow −"
},
{
"code": null,
"e": 3135,
"s": 3090,
"text": "conda create --name tensorflow python = 3.5\n"
},
{
"code": null,
"e": 3200,
"s": 3135,
"text": "It downloads the necessary packages needed for TensorFlow setup."
},
{
"code": null,
"e": 3294,
"s": 3200,
"text": "Step 4 − After successful environmental setup, it is important to activate TensorFlow module."
},
{
"code": null,
"e": 3315,
"s": 3294,
"text": "activate tensorflow\n"
},
{
"code": null,
"e": 3429,
"s": 3315,
"text": "Step 5 − Use pip to install “Tensorflow” in the system. The command used for installation is mentioned as below −"
},
{
"code": null,
"e": 3453,
"s": 3429,
"text": "pip install tensorflow\n"
},
{
"code": null,
"e": 3458,
"s": 3453,
"text": "And,"
},
{
"code": null,
"e": 3486,
"s": 3458,
"text": "pip install tensorflow-gpu\n"
},
{
"code": null,
"e": 3585,
"s": 3486,
"text": "After successful installation, it is important to know the sample program execution of TensorFlow."
},
{
"code": null,
"e": 3679,
"s": 3585,
"text": "Following example helps us understand the basic program creation “Hello World” in TensorFlow."
},
{
"code": null,
"e": 3742,
"s": 3679,
"text": "The code for first program implementation is mentioned below −"
},
{
"code": null,
"e": 3923,
"s": 3742,
"text": ">> activate tensorflow\n>> python (activating python shell)\n>> import tensorflow as tf\n>> hello = tf.constant(‘Hello, Tensorflow!’)\n>> sess = tf.Session()\n>> print(sess.run(hello))\n"
},
{
"code": null,
"e": 3956,
"s": 3923,
"text": "\n 61 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3978,
"s": 3956,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4011,
"s": 3978,
"text": "\n 57 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4033,
"s": 4011,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4066,
"s": 4033,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4088,
"s": 4066,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4121,
"s": 4088,
"text": "\n 52 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4143,
"s": 4121,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4178,
"s": 4143,
"text": "\n 29 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4195,
"s": 4178,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 4228,
"s": 4195,
"text": "\n 82 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4241,
"s": 4228,
"text": " Anis Koubaa"
},
{
"code": null,
"e": 4248,
"s": 4241,
"text": " Print"
},
{
"code": null,
"e": 4259,
"s": 4248,
"text": " Add Notes"
}
] |
Java.io.OutputStream class in Java - GeeksforGeeks | 24 Jan, 2017
This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output.
Constructor and Description
OutputStream() : Single Constructor
Methods:
void close() : Closes this output stream and releases any system resources associated with this stream.Syntax :public void close()
throws IOException
Throws:
IOException
Syntax :public void close()
throws IOException
Throws:
IOException
void flush() : Flushes this output stream and forces any buffered output bytes to be written out.Syntax :public void flush()
throws IOException
Throws:
IOException
Syntax :public void flush()
throws IOException
Throws:
IOException
void write(byte[] b) : Writes b.length bytes from the specified byte array to this output stream.Syntax :public void write(byte[] b)
throws IOException
Parameters:
b - the data.
Throws:
IOException
Syntax :public void write(byte[] b)
throws IOException
Parameters:
b - the data.
Throws:
IOException
void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this output stream.Syntax :public void write(byte[] b,
int off,
int len)
throws IOException
Parameters:
b - the data.
off - the start offset in the data.
len - the number of bytes to write.
Throws:
IOException
Syntax :public void write(byte[] b,
int off,
int len)
throws IOException
Parameters:
b - the data.
off - the start offset in the data.
len - the number of bytes to write.
Throws:
IOException
abstract void write(int b) : Writes the specified byte to this output stream.Syntax :public abstract void write(int b)
throws IOException
Parameters:
b - the byte.
Throws:
IOException
Syntax :public abstract void write(int b)
throws IOException
Parameters:
b - the byte.
Throws:
IOException
import java.io.*;//Java program to demonstrate OutputStreamclass OutputStreamDemo{ public static void main(String args[])throws Exception { OutputStream os = new FileOutputStream("file.txt"); byte b[] = {65, 66, 67, 68, 69, 70}; //illustrating write(byte[] b) method os.write(b); //illustrating flush() method os.flush(); //illustrating write(int b) method for (int i = 71; i <75 ; i++) { os.write(i); } os.flush(); //close the stream os.close(); }}
Output :
ABCDEFGHIJ
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-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Stream In Java
Singleton Class in Java
Initializing a List in Java
Different ways of Reading a text file in Java | [
{
"code": null,
"e": 27878,
"s": 27850,
"text": "\n24 Jan, 2017"
},
{
"code": null,
"e": 28167,
"s": 27878,
"text": "This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output."
},
{
"code": null,
"e": 28195,
"s": 28167,
"text": "Constructor and Description"
},
{
"code": null,
"e": 28231,
"s": 28195,
"text": "OutputStream() : Single Constructor"
},
{
"code": null,
"e": 28240,
"s": 28231,
"text": "Methods:"
},
{
"code": null,
"e": 28421,
"s": 28240,
"text": "void close() : Closes this output stream and releases any system resources associated with this stream.Syntax :public void close()\n throws IOException\nThrows:\nIOException"
},
{
"code": null,
"e": 28499,
"s": 28421,
"text": "Syntax :public void close()\n throws IOException\nThrows:\nIOException"
},
{
"code": null,
"e": 28674,
"s": 28499,
"text": "void flush() : Flushes this output stream and forces any buffered output bytes to be written out.Syntax :public void flush()\n throws IOException\nThrows:\nIOException"
},
{
"code": null,
"e": 28752,
"s": 28674,
"text": "Syntax :public void flush()\n throws IOException\nThrows:\nIOException"
},
{
"code": null,
"e": 28962,
"s": 28752,
"text": "void write(byte[] b) : Writes b.length bytes from the specified byte array to this output stream.Syntax :public void write(byte[] b)\n throws IOException\nParameters:\nb - the data.\nThrows:\nIOException "
},
{
"code": null,
"e": 29075,
"s": 28962,
"text": "Syntax :public void write(byte[] b)\n throws IOException\nParameters:\nb - the data.\nThrows:\nIOException "
},
{
"code": null,
"e": 29429,
"s": 29075,
"text": "void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this output stream.Syntax :public void write(byte[] b,\n int off,\n int len)\n throws IOException\nParameters:\nb - the data.\noff - the start offset in the data.\nlen - the number of bytes to write.\nThrows:\nIOException "
},
{
"code": null,
"e": 29650,
"s": 29429,
"text": "Syntax :public void write(byte[] b,\n int off,\n int len)\n throws IOException\nParameters:\nb - the data.\noff - the start offset in the data.\nlen - the number of bytes to write.\nThrows:\nIOException "
},
{
"code": null,
"e": 29854,
"s": 29650,
"text": "abstract void write(int b) : Writes the specified byte to this output stream.Syntax :public abstract void write(int b)\n throws IOException\nParameters:\nb - the byte.\nThrows:\nIOException"
},
{
"code": null,
"e": 29981,
"s": 29854,
"text": "Syntax :public abstract void write(int b)\n throws IOException\nParameters:\nb - the byte.\nThrows:\nIOException"
},
{
"code": "import java.io.*;//Java program to demonstrate OutputStreamclass OutputStreamDemo{ public static void main(String args[])throws Exception { OutputStream os = new FileOutputStream(\"file.txt\"); byte b[] = {65, 66, 67, 68, 69, 70}; //illustrating write(byte[] b) method os.write(b); //illustrating flush() method os.flush(); //illustrating write(int b) method for (int i = 71; i <75 ; i++) { os.write(i); } os.flush(); //close the stream os.close(); }}",
"e": 30585,
"s": 29981,
"text": null
},
{
"code": null,
"e": 30594,
"s": 30585,
"text": "Output :"
},
{
"code": null,
"e": 30605,
"s": 30594,
"text": "ABCDEFGHIJ"
},
{
"code": null,
"e": 30907,
"s": 30605,
"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": 31032,
"s": 30907,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31041,
"s": 31032,
"text": "Java-I/O"
},
{
"code": null,
"e": 31046,
"s": 31041,
"text": "Java"
},
{
"code": null,
"e": 31051,
"s": 31046,
"text": "Java"
},
{
"code": null,
"e": 31149,
"s": 31051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31193,
"s": 31149,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31229,
"s": 31193,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 31254,
"s": 31229,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31286,
"s": 31254,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31337,
"s": 31286,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31368,
"s": 31337,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 31383,
"s": 31368,
"text": "Stream In Java"
},
{
"code": null,
"e": 31407,
"s": 31383,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 31435,
"s": 31407,
"text": "Initializing a List in Java"
}
] |
Bootstrap 4 | Jumbotron - GeeksforGeeks | 28 Apr, 2022
A jumbotron is a big grey box used to indicate some text which requires extra attention. Any text that seems to be important can be written inside a jumbotron to make it appear big and noticeable.
Steps to add jumbotron:
Use a jumbotron class inside a div element.
Write any text inside the div tag.
Close the div element.
Syntax:
<div class="jumbtron"> Contents... <div>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Jumbotron</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body style="text-align:center;"> <div class="container"> <div class="jumbotron"> <h1 style="color:green;"> GeeksforGeeks </h1> <p>A computer science portal for geeks</p> </div> </div></body></html>
Output:
Full-width Jumbotron: The .jumbotron-fluid and .container or .container-fluid classes is used to create a full-width jumbotron without rounded borders.
Syntax:
<div class="jumbotron jumbotron-fluid">
<div class="container"> Contents... <div>
<div>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Jumbotron</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body style="text-align:center;"> <div class="container"> <div class="jumbotron"> <h1 style="color:green;"> GeeksforGeeks </h1> <p>A computer science portal for geeks</p> </div> </div></body></html>
Output:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
sahilintern
Bootstrap-4
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to change navigation bar color in Bootstrap ?
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to set Bootstrap Timepicker using datetimepicker library ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 29795,
"s": 29767,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 29992,
"s": 29795,
"text": "A jumbotron is a big grey box used to indicate some text which requires extra attention. Any text that seems to be important can be written inside a jumbotron to make it appear big and noticeable."
},
{
"code": null,
"e": 30016,
"s": 29992,
"text": "Steps to add jumbotron:"
},
{
"code": null,
"e": 30060,
"s": 30016,
"text": "Use a jumbotron class inside a div element."
},
{
"code": null,
"e": 30095,
"s": 30060,
"text": "Write any text inside the div tag."
},
{
"code": null,
"e": 30118,
"s": 30095,
"text": "Close the div element."
},
{
"code": null,
"e": 30126,
"s": 30118,
"text": "Syntax:"
},
{
"code": null,
"e": 30167,
"s": 30126,
"text": "<div class=\"jumbtron\"> Contents... <div>"
},
{
"code": null,
"e": 30176,
"s": 30167,
"text": "Example:"
},
{
"code": null,
"e": 30181,
"s": 30176,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Jumbotron</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body style=\"text-align:center;\"> <div class=\"container\"> <div class=\"jumbotron\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p>A computer science portal for geeks</p> </div> </div></body></html>",
"e": 31041,
"s": 30181,
"text": null
},
{
"code": null,
"e": 31049,
"s": 31041,
"text": "Output:"
},
{
"code": null,
"e": 31201,
"s": 31049,
"text": "Full-width Jumbotron: The .jumbotron-fluid and .container or .container-fluid classes is used to create a full-width jumbotron without rounded borders."
},
{
"code": null,
"e": 31209,
"s": 31201,
"text": "Syntax:"
},
{
"code": null,
"e": 31301,
"s": 31209,
"text": "<div class=\"jumbotron jumbotron-fluid\">\n <div class=\"container\"> Contents... <div>\n<div>"
},
{
"code": null,
"e": 31310,
"s": 31301,
"text": "Example:"
},
{
"code": null,
"e": 31315,
"s": 31310,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Jumbotron</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body style=\"text-align:center;\"> <div class=\"container\"> <div class=\"jumbotron\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p>A computer science portal for geeks</p> </div> </div></body></html>",
"e": 32175,
"s": 31315,
"text": null
},
{
"code": null,
"e": 32183,
"s": 32175,
"text": "Output:"
},
{
"code": null,
"e": 32202,
"s": 32183,
"text": "Supported Browser:"
},
{
"code": null,
"e": 32216,
"s": 32202,
"text": "Google Chrome"
},
{
"code": null,
"e": 32234,
"s": 32216,
"text": "Internet Explorer"
},
{
"code": null,
"e": 32242,
"s": 32234,
"text": "Firefox"
},
{
"code": null,
"e": 32248,
"s": 32242,
"text": "Opera"
},
{
"code": null,
"e": 32255,
"s": 32248,
"text": "Safari"
},
{
"code": null,
"e": 32267,
"s": 32255,
"text": "ysachin2314"
},
{
"code": null,
"e": 32279,
"s": 32267,
"text": "sahilintern"
},
{
"code": null,
"e": 32291,
"s": 32279,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 32301,
"s": 32291,
"text": "Bootstrap"
},
{
"code": null,
"e": 32318,
"s": 32301,
"text": "Web Technologies"
},
{
"code": null,
"e": 32416,
"s": 32318,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32445,
"s": 32416,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32495,
"s": 32445,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 32536,
"s": 32495,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 32592,
"s": 32536,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 32655,
"s": 32592,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 32695,
"s": 32655,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32728,
"s": 32695,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32773,
"s": 32728,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32816,
"s": 32773,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to remove time from date using JavaScript ? - GeeksforGeeks | 22 Feb, 2022
Given a Date Object and the task is to remove the time portion of the object using JavaScript.
split() method: This method is used to split a string into an array of substrings, and returns the new array.
Syntax:
string.split( separator, limit )
Parameters:
separator: This parameter is optional. It specifies the character, or the regular expression to use for splitting the string. If not used, the whole string will be returned (an array with only one item).
limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.
Return value: It returns a new array, having the splitted items.
Example 1: This example splits the date by using (‘ ‘) and then take the value at index = 0 of the array returned after split using split() method.
<!DOCTYPE HTML> <html> <head> <title> Remove time from date </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var d = '12/05/2019 12:00:00 AM'; up.innerHTML = d; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { down.innerHTML = d.split(' ')[0]; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example is quite similar to the previous one. This example first splits the date by using (‘ ‘) and then take the value at index = 0 of the array returned after split using split() method. It works with Date objects.
<!DOCTYPE HTML> <html> <head> <title> Remove time from date </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var d = new Date(); up.innerHTML = d; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { down.innerHTML = d.toISOString().split('T')[0]; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
jayjbm94
javascript-date
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24935,
"s": 24907,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 25030,
"s": 24935,
"text": "Given a Date Object and the task is to remove the time portion of the object using JavaScript."
},
{
"code": null,
"e": 25140,
"s": 25030,
"text": "split() method: This method is used to split a string into an array of substrings, and returns the new array."
},
{
"code": null,
"e": 25148,
"s": 25140,
"text": "Syntax:"
},
{
"code": null,
"e": 25181,
"s": 25148,
"text": "string.split( separator, limit )"
},
{
"code": null,
"e": 25193,
"s": 25181,
"text": "Parameters:"
},
{
"code": null,
"e": 25397,
"s": 25193,
"text": "separator: This parameter is optional. It specifies the character, or the regular expression to use for splitting the string. If not used, the whole string will be returned (an array with only one item)."
},
{
"code": null,
"e": 25556,
"s": 25397,
"text": "limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array."
},
{
"code": null,
"e": 25621,
"s": 25556,
"text": "Return value: It returns a new array, having the splitted items."
},
{
"code": null,
"e": 25769,
"s": 25621,
"text": "Example 1: This example splits the date by using (‘ ‘) and then take the value at index = 0 of the array returned after split using split() method."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Remove time from date </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var d = '12/05/2019 12:00:00 AM'; up.innerHTML = d; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { down.innerHTML = d.split(' ')[0]; } </script> </body> </html> ",
"e": 26709,
"s": 25769,
"text": null
},
{
"code": null,
"e": 26717,
"s": 26709,
"text": "Output:"
},
{
"code": null,
"e": 26748,
"s": 26717,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 26778,
"s": 26748,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 27011,
"s": 26778,
"text": "Example 2: This example is quite similar to the previous one. This example first splits the date by using (‘ ‘) and then take the value at index = 0 of the array returned after split using split() method. It works with Date objects."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Remove time from date </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var d = new Date(); up.innerHTML = d; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { down.innerHTML = d.toISOString().split('T')[0]; } </script> </body> </html> ",
"e": 27952,
"s": 27011,
"text": null
},
{
"code": null,
"e": 27960,
"s": 27952,
"text": "Output:"
},
{
"code": null,
"e": 27991,
"s": 27960,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28021,
"s": 27991,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28030,
"s": 28021,
"text": "jayjbm94"
},
{
"code": null,
"e": 28046,
"s": 28030,
"text": "javascript-date"
},
{
"code": null,
"e": 28057,
"s": 28046,
"text": "JavaScript"
},
{
"code": null,
"e": 28074,
"s": 28057,
"text": "Web Technologies"
},
{
"code": null,
"e": 28101,
"s": 28074,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28199,
"s": 28101,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28208,
"s": 28199,
"text": "Comments"
},
{
"code": null,
"e": 28221,
"s": 28208,
"text": "Old Comments"
},
{
"code": null,
"e": 28282,
"s": 28221,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28323,
"s": 28282,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28377,
"s": 28323,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28417,
"s": 28377,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28479,
"s": 28417,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 28535,
"s": 28479,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28568,
"s": 28535,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28630,
"s": 28568,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28673,
"s": 28630,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Difference between Iterator and Enumeration in Java with Examples - GeeksforGeeks | 28 Jan, 2021
Iterator: It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is an improved version of Enumeration with the additional functionality of remove-ability of an element.
Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface. Iterator is the only cursor available for entire collection framework.
Syntax:
// Here "c" is any Collection object. itr is of
// type Iterator interface and refers to "c"
Iterator itr = c.iterator();
Enumeration: Enumeration (or enum) is a user-defined data type. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. In Java (from 1.5), enums are represented using the enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods and constructors to it. The main objective of the enum is to define our own data types(Enumerated Data Types).
Syntax:
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color
{
RED, GREEN, BLUE;
}
Difference between Iterator and Enumeration:
The functionality of Enumeration and the Iterator are same. Using Enumeration you can only traverse and fetch the objects, where as using Iterator we can also add and remove the objects. So Iterator can be useful if you want to manipulate the list and Enumeration is for read-only access.
gautambalachandran
Picked
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Stack vs Heap Memory Allocation
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 24768,
"s": 24740,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 25026,
"s": 24768,
"text": "Iterator: It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is an improved version of Enumeration with the additional functionality of remove-ability of an element. "
},
{
"code": null,
"e": 25293,
"s": 25026,
"text": "Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface. Iterator is the only cursor available for entire collection framework. "
},
{
"code": null,
"e": 25303,
"s": 25293,
"text": "Syntax: "
},
{
"code": null,
"e": 25425,
"s": 25303,
"text": "// Here \"c\" is any Collection object. itr is of\n// type Iterator interface and refers to \"c\"\nIterator itr = c.iterator();"
},
{
"code": null,
"e": 25869,
"s": 25425,
"text": "Enumeration: Enumeration (or enum) is a user-defined data type. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. In Java (from 1.5), enums are represented using the enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods and constructors to it. The main objective of the enum is to define our own data types(Enumerated Data Types). "
},
{
"code": null,
"e": 25879,
"s": 25869,
"text": "Syntax: "
},
{
"code": null,
"e": 26039,
"s": 25879,
"text": "// A simple enum example where enum is declared \n// outside any class (Note enum keyword instead of \n// class keyword) \nenum Color \n{ \n RED, GREEN, BLUE; \n}"
},
{
"code": null,
"e": 26085,
"s": 26039,
"text": "Difference between Iterator and Enumeration: "
},
{
"code": null,
"e": 26376,
"s": 26085,
"text": "The functionality of Enumeration and the Iterator are same. Using Enumeration you can only traverse and fetch the objects, where as using Iterator we can also add and remove the objects. So Iterator can be useful if you want to manipulate the list and Enumeration is for read-only access. "
},
{
"code": null,
"e": 26397,
"s": 26378,
"text": "gautambalachandran"
},
{
"code": null,
"e": 26404,
"s": 26397,
"text": "Picked"
},
{
"code": null,
"e": 26423,
"s": 26404,
"text": "Difference Between"
},
{
"code": null,
"e": 26428,
"s": 26423,
"text": "Java"
},
{
"code": null,
"e": 26433,
"s": 26428,
"text": "Java"
},
{
"code": null,
"e": 26531,
"s": 26433,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26592,
"s": 26531,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26630,
"s": 26592,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 26662,
"s": 26630,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 26730,
"s": 26662,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 26767,
"s": 26730,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 26782,
"s": 26767,
"text": "Arrays in Java"
},
{
"code": null,
"e": 26826,
"s": 26782,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 26848,
"s": 26826,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 26884,
"s": 26848,
"text": "Arrays.sort() in Java with examples"
}
] |
Insertion in a B+ tree - GeeksforGeeks | 24 Nov, 2021
Prerequisite: Introduction of B+ treesIn this article, we will discuss that how to insert a node in B+ Tree. During insertion following properties of B+ Tree must be followed:
Each node except root can have a maximum of M children and at least ceil(M/2) children.
Each node can contain a maximum of M – 1 keys and a minimum of ceil(M/2) – 1 keys.
The root has at least two children and atleast one search key.
While insertion overflow of the node occurs when it contains more than M – 1 search key values.
Here M is the order of B+ tree.
Every element is inserted into a leaf node. So, go to the appropriate leaf node.Insert the key into the leaf node in increasing order only if there is no overflow. If there is an overflow go ahead with the following steps mentioned below to deal with overflow while maintaining the B+ Tree properties.
Every element is inserted into a leaf node. So, go to the appropriate leaf node.
Insert the key into the leaf node in increasing order only if there is no overflow. If there is an overflow go ahead with the following steps mentioned below to deal with overflow while maintaining the B+ Tree properties.
Case 1: Overflow in leaf node
Split the leaf node into two nodes.First node contains ceil((m-1)/2) values.Second node contains the remaining values.Copy the smallest search key value from second node to the parent node.(Right biased)
Split the leaf node into two nodes.
First node contains ceil((m-1)/2) values.
Second node contains the remaining values.
Copy the smallest search key value from second node to the parent node.(Right biased)
Below is the illustration of inserting 8 into B+ Tree of order of 5:
Case 2: Overflow in non-leaf node
Split the non leaf node into two nodes.First node contains ceil(m/2)-1 values.Move the smallest among remaining to the parent.Second node contains the remaining keys.
Split the non leaf node into two nodes.
First node contains ceil(m/2)-1 values.
Move the smallest among remaining to the parent.
Second node contains the remaining keys.
Below is the illustration of inserting 15 into B+ Tree of order of 5:
Problem: Insert the following key values 6, 16, 26, 36, 46 on a B+ tree with order = 3. Solution: Step 1: The order is 3 so at maximum in a node so there can be only 2 search key values. As insertion happens on a leaf node only in a B+ tree so insert search key value 6 and 16 in increasing order in the node. Below is the illustration of the same:
Step 2: We cannot insert 26 in the same node as it causes an overflow in the leaf node, We have to split the leaf node according to the rules. First part contains ceil((3-1)/2) values i.e., only 6. The second node contains the remaining values i.e., 16 and 26. Then also copy the smallest search key value from the second node to the parent node i.e., 16 to the parent node. Below is the illustration of the same:
Step 3: Now the next value is 36 that is to be inserted after 26 but in that node, it causes an overflow again in that leaf node. Again follow the above steps to split the node. First part contains ceil((3-1)/2) values i.e., only 16. The second node contains the remaining values i.e., 26 and 36. Then also copy the smallest search key value from the second node to the parent node i.e., 26 to the parent node. Below is the illustration of the same: The illustration is shown in the diagram below.
Step 4: Now we have to insert 46 which is to be inserted after 36 but it causes an overflow in the leaf node. So we split the node according to the rules. The first part contains 26 and the second part contains 36 and 46 but now we also have to copy 36 to the parent node but it causes overflow as only two search key values can be accommodated in a node. Now follow the steps to deal with overflow in the non-leaf node. First node contains ceil(3/2)-1 values i.e. ’16’. Move the smallest among remaining to the parent i.e ’26’ will be the new parent node. The second node contains the remaining keys i.e ’36’ and the rest of the leaf nodes remain the same. Below is the illustration of the same:
Below is the implementation of insertion in the B+ tree:
C++
Python3
// C++ program for implementing B+ Tree#include <climits>#include <fstream>#include <iostream>#include <sstream>using namespace std;int MAX = 3; // BP nodeclass Node { bool IS_LEAF; int *key, size; Node** ptr; friend class BPTree; public: Node();}; // BP treeclass BPTree { Node* root; void insertInternal(int, Node*, Node*); Node* findParent(Node*, Node*); public: BPTree(); void search(int); void insert(int); void display(Node*); Node* getRoot();}; // Constructor of NodeNode::Node(){ key = new int[MAX]; ptr = new Node*[MAX + 1];} // Initialise the BPTree NodeBPTree::BPTree(){ root = NULL;} // Function to find any element// in B+ Treevoid BPTree::search(int x){ // If tree is empty if (root == NULL) { cout << "Tree is empty\n"; } // Traverse to find the value else { Node* cursor = root; // Till we reach leaf node while (cursor->IS_LEAF == false) { for (int i = 0; i < cursor->size; i++) { // If the element to be // found is not present if (x < cursor->key[i]) { cursor = cursor->ptr[i]; break; } // If reaches end of the // cursor node if (i == cursor->size - 1) { cursor = cursor->ptr[i + 1]; break; } } } // Traverse the cursor and find // the node with value x for (int i = 0; i < cursor->size; i++) { // If found then return if (cursor->key[i] == x) { cout << "Found\n"; return; } } // Else element is not present cout << "Not found\n"; }} // Function to implement the Insert// Operation in B+ Treevoid BPTree::insert(int x){ // If root is null then return // newly created node if (root == NULL) { root = new Node; root->key[0] = x; root->IS_LEAF = true; root->size = 1; } // Traverse the B+ Tree else { Node* cursor = root; Node* parent; // Till cursor reaches the // leaf node while (cursor->IS_LEAF == false) { parent = cursor; for (int i = 0; i < cursor->size; i++) { // If found the position // where we have to insert // node if (x < cursor->key[i]) { cursor = cursor->ptr[i]; break; } // If reaches the end if (i == cursor->size - 1) { cursor = cursor->ptr[i + 1]; break; } } } if (cursor->size < MAX) { int i = 0; while (x > cursor->key[i] && i < cursor->size) { i++; } for (int j = cursor->size; j > i; j--) { cursor->key[j] = cursor->key[j - 1]; } cursor->key[i] = x; cursor->size++; cursor->ptr[cursor->size] = cursor->ptr[cursor->size - 1]; cursor->ptr[cursor->size - 1] = NULL; } else { // Create a newLeaf node Node* newLeaf = new Node; int virtualNode[MAX + 1]; // Update cursor to virtual // node created for (int i = 0; i < MAX; i++) { virtualNode[i] = cursor->key[i]; } int i = 0, j; // Traverse to find where the new // node is to be inserted while (x > virtualNode[i] && i < MAX) { i++; } // Update the current virtual // Node to its previous for (int j = MAX + 1; j > i; j--) { virtualNode[j] = virtualNode[j - 1]; } virtualNode[i] = x; newLeaf->IS_LEAF = true; cursor->size = (MAX + 1) / 2; newLeaf->size = MAX + 1 - (MAX + 1) / 2; cursor->ptr[cursor->size] = newLeaf; newLeaf->ptr[newLeaf->size] = cursor->ptr[MAX]; cursor->ptr[MAX] = NULL; // Update the current virtual // Node's key to its previous for (i = 0; i < cursor->size; i++) { cursor->key[i] = virtualNode[i]; } // Update the newLeaf key to // virtual Node for (i = 0, j = cursor->size; i < newLeaf->size; i++, j++) { newLeaf->key[i] = virtualNode[j]; } // If cursor is the root node if (cursor == root) { // Create a new Node Node* newRoot = new Node; // Update rest field of // B+ Tree Node newRoot->key[0] = newLeaf->key[0]; newRoot->ptr[0] = cursor; newRoot->ptr[1] = newLeaf; newRoot->IS_LEAF = false; newRoot->size = 1; root = newRoot; } else { // Recursive Call for // insert in internal insertInternal(newLeaf->key[0], parent, newLeaf); } } }} // Function to implement the Insert// Internal Operation in B+ Treevoid BPTree::insertInternal(int x, Node* cursor, Node* child){ // If we doesn't have overflow if (cursor->size < MAX) { int i = 0; // Traverse the child node // for current cursor node while (x > cursor->key[i] && i < cursor->size) { i++; } // Traverse the cursor node // and update the current key // to its previous node key for (int j = cursor->size; j > i; j--) { cursor->key[j] = cursor->key[j - 1]; } // Traverse the cursor node // and update the current ptr // to its previous node ptr for (int j = cursor->size + 1; j > i + 1; j--) { cursor->ptr[j] = cursor->ptr[j - 1]; } cursor->key[i] = x; cursor->size++; cursor->ptr[i + 1] = child; } // For overflow, break the node else { // For new Interval Node* newInternal = new Node; int virtualKey[MAX + 1]; Node* virtualPtr[MAX + 2]; // Insert the current list key // of cursor node to virtualKey for (int i = 0; i < MAX; i++) { virtualKey[i] = cursor->key[i]; } // Insert the current list ptr // of cursor node to virtualPtr for (int i = 0; i < MAX + 1; i++) { virtualPtr[i] = cursor->ptr[i]; } int i = 0, j; // Traverse to find where the new // node is to be inserted while (x > virtualKey[i] && i < MAX) { i++; } // Traverse the virtualKey node // and update the current key // to its previous node key for (int j = MAX + 1; j > i; j--) { virtualKey[j] = virtualKey[j - 1]; } virtualKey[i] = x; // Traverse the virtualKey node // and update the current ptr // to its previous node ptr for (int j = MAX + 2; j > i + 1; j--) { virtualPtr[j] = virtualPtr[j - 1]; } virtualPtr[i + 1] = child; newInternal->IS_LEAF = false; cursor->size = (MAX + 1) / 2; newInternal->size = MAX - (MAX + 1) / 2; // Insert new node as an // internal node for (i = 0, j = cursor->size + 1; i < newInternal->size; i++, j++) { newInternal->key[i] = virtualKey[j]; } for (i = 0, j = cursor->size + 1; i < newInternal->size + 1; i++, j++) { newInternal->ptr[i] = virtualPtr[j]; } // If cursor is the root node if (cursor == root) { // Create a new root node Node* newRoot = new Node; // Update key value newRoot->key[0] = cursor->key[cursor->size]; // Update rest field of // B+ Tree Node newRoot->ptr[0] = cursor; newRoot->ptr[1] = newInternal; newRoot->IS_LEAF = false; newRoot->size = 1; root = newRoot; } else { // Recursive Call to insert // the data insertInternal(cursor->key[cursor->size], findParent(root, cursor), newInternal); } }} // Function to find the parent nodeNode* BPTree::findParent(Node* cursor, Node* child){ Node* parent; // If cursor reaches the end of Tree if (cursor->IS_LEAF || (cursor->ptr[0])->IS_LEAF) { return NULL; } // Traverse the current node with // all its child for (int i = 0; i < cursor->size + 1; i++) { // Update the parent for the // child Node if (cursor->ptr[i] == child) { parent = cursor; return parent; } // Else recursively traverse to // find child node else { parent = findParent(cursor->ptr[i], child); // If parent is found, then // return that parent node if (parent != NULL) return parent; } } // Return parent node return parent;} // Function to get the root NodeNode* BPTree::getRoot(){ return root;} // Driver Codeint main(){ BPTree node; // Create B+ Tree node.insert(6); node.insert(16); node.insert(26); node.insert(36); node.insert(46); // Function Call to search node // with value 16 node.search(16); return 0;}
# Python3 program for implementing B+ Tree MAX = 3 # BP nodeclass Node : def __init__(self): self.IS_LEAF=False self.key, self.size=[None]*MAX,0 self.ptr=[None]*(MAX+1) # BP treeclass BPTree : # Initialise the BPTree Node def __init__(self): self.root = None # Function to find any element# in B+ Tree def search(self,x): # If tree is empty if (self.root == None) : cout << "Tree is empty\n" # Traverse to find the value else : cursor = self.root # Till we reach leaf node while (not cursor.IS_LEAF) : for i in range(cursor.size) : # If the element to be # found is not present if (x < cursor.key[i]) : cursor = cursor.ptr[i] break # If reaches end of the # cursor node if (i == cursor.size - 1) : cursor = cursor.ptr[i + 1] break # Traverse the cursor and find # the node with value x for i in range(cursor.size): # If found then return if (cursor.key[i] == x) : print("Found") return # Else element is not present print("Not found") # Function to implement the Insert # Operation in B+ Tree def insert(self, x): # If root is None then return # newly created node if (self.root == None) : self.root = Node() self.root.key[0] = x self.root.IS_LEAF = True self.root.size = 1 # Traverse the B+ Tree else : cursor = self.root parent=None # Till cursor reaches the # leaf node while (not cursor.IS_LEAF) : parent = cursor for i in range(cursor.size) : # If found the position # where we have to insert # node if (x < cursor.key[i]) : cursor = cursor.ptr[i] break # If reaches the end if (i == cursor.size - 1) : cursor = cursor.ptr[i + 1] break if (cursor.size < MAX) : i = 0 while (i < cursor.size and x > cursor.key[i]): i+=1 for j in range(cursor.size,i,-1): cursor.key[j] = cursor.key[j - 1] cursor.key[i] = x cursor.size+=1 cursor.ptr[cursor.size] = cursor.ptr[cursor.size - 1] cursor.ptr[cursor.size - 1] = None else : # Create a newLeaf node newLeaf = Node() virtualNode=[None]*(MAX + 1) # Update cursor to virtual # node created for i in range(MAX): virtualNode[i] = cursor.key[i] i = 0 # Traverse to find where the new # node is to be inserted while (i < MAX and x > virtualNode[i]) : i+=1 # Update the current virtual # Node to its previous for j in range(MAX,i,-1) : virtualNode[j] = virtualNode[j - 1] virtualNode[i] = x newLeaf.IS_LEAF = True cursor.size = int((MAX + 1) / 2) newLeaf.size = int(MAX + 1 - (MAX + 1) / 2) cursor.ptr[cursor.size] = newLeaf newLeaf.ptr[newLeaf.size] = cursor.ptr[MAX] cursor.ptr[MAX] = None # Update the current virtual # Node's key to its previous for i in range(cursor.size): cursor.key[i] = virtualNode[i] # Update the newLeaf key to # virtual Node j=cursor.size for i in range(newLeaf.size): newLeaf.key[i] = virtualNode[j] j+=1 # If cursor is the root node if (cursor == self.root) : # Create a new Node newRoot = Node() # Update rest field of # B+ Tree Node newRoot.key[0] = newLeaf.key[0] newRoot.ptr[0] = cursor newRoot.ptr[1] = newLeaf newRoot.IS_LEAF = False newRoot.size = 1 root = newRoot else : # Recursive Call for # insert in internal insertInternal(newLeaf.key[0], parent, newLeaf) # Function to implement the Insert# Internal Operation in B+ Treedef insertInternal(x, cursor, child): # If we doesn't have overflow if (cursor.size < MAX) : i = 0 # Traverse the child node # for current cursor node while (x > cursor.key[i] and i < cursor.size) : i+=1 # Traverse the cursor node # and update the current key # to its previous node key for j in range(cursor.size,i,-1) : cursor.key[j] = cursor.key[j - 1] # Traverse the cursor node # and update the current ptr # to its previous node ptr for j in range(cursor.size + 1, i + 1,-1): cursor.ptr[j] = cursor.ptr[j - 1] cursor.key[i] = x cursor.size+=1 cursor.ptr[i + 1] = child # For overflow, break the node else : # For new Interval newInternal = Node() virtualKey=[None]*(MAX + 1) virtualPtr=[None]*(MAX + 2) # Insert the current list key # of cursor node to virtualKey for i in range(MAX) : virtualKey[i] = cursor.key[i] # Insert the current list ptr # of cursor node to virtualPtr for i in range(MAX + 1): virtualPtr[i] = cursor.ptr[i] i = 0 # Traverse to find where the new # node is to be inserted while (x > virtualKey[i] and i < MAX) : i+=1 # Traverse the virtualKey node # and update the current key # to its previous node key for j in range(MAX + 1,i,-1): virtualKey[j] = virtualKey[j - 1] virtualKey[i] = x # Traverse the virtualKey node # and update the current ptr # to its previous node ptr for j in range(MAX + 2, i + 1,-1) : virtualPtr[j] = virtualPtr[j - 1] virtualPtr[i + 1] = child newInternal.IS_LEAF = false cursor.size = (MAX + 1) / 2 newInternal.size = MAX - (MAX + 1) / 2 # Insert new node as an # internal node j = cursor.size + 1 for i in range(newInternal.size): newInternal.key[i] = virtualKey[j] j+=1 j = cursor.size + 1 for i in range(newInternal.size): newInternal.ptr[i] = virtualKey[j] j+=1 # If cursor is the root node if (cursor == self.root) : # Create a new root node newRoot = self.root # Update key value newRoot.key[0] = cursor.key[cursor.size] # Update rest field of # B+ Tree Node newRoot.ptr[0] = cursor newRoot.ptr[1] = newInternal newRoot.IS_LEAF = false newRoot.size = 1 root = newRoot else : # Recursive Call to insert # the data insertInternal(cursor.key[cursor.size], findParent(root, cursor), newInternal) # Function to find the parent node def findParent(self, cursor, child): # If cursor reaches the end of Tree if (cursor.IS_LEAF or (cursor.ptr[0]).IS_LEAF) : return None # Traverse the current node with # all its child for i in range(cursor.size + 1) : # Update the parent for the # child Node if (cursor.ptr[i] == child) : parent = cursor return parent # Else recursively traverse to # find child node else : parent = findParent(cursor.ptr[i], child) # If parent is found, then # return that parent node if (parent != None): return parent # Return parent node return parent # Function to get the root Node def getRoot(self): return self.root # Driver Codeif __name__=='__main__': node=BPTree() # Create B+ Tree node.insert(6) node.insert(16) node.insert(26) node.insert(36) node.insert(46) # Function Call to search node # with value 16 node.search(16)
Found
amartyaghoshgfg
B and B+ Trees
Data Structures-B and B+ Trees
Algorithms
Data Structures
Tree
Data Structures
Tree
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Program for SSTF disk scheduling algorithm
Quadratic Probing in Hashing
Rail Fence Cipher - Encryption and Decryption
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Implementing a Linked List in Java using Class
Insertion and Deletion in Heaps
Abstract Data Types | [
{
"code": null,
"e": 24700,
"s": 24672,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 24878,
"s": 24700,
"text": "Prerequisite: Introduction of B+ treesIn this article, we will discuss that how to insert a node in B+ Tree. During insertion following properties of B+ Tree must be followed: "
},
{
"code": null,
"e": 24966,
"s": 24878,
"text": "Each node except root can have a maximum of M children and at least ceil(M/2) children."
},
{
"code": null,
"e": 25049,
"s": 24966,
"text": "Each node can contain a maximum of M – 1 keys and a minimum of ceil(M/2) – 1 keys."
},
{
"code": null,
"e": 25112,
"s": 25049,
"text": "The root has at least two children and atleast one search key."
},
{
"code": null,
"e": 25208,
"s": 25112,
"text": "While insertion overflow of the node occurs when it contains more than M – 1 search key values."
},
{
"code": null,
"e": 25241,
"s": 25208,
"text": "Here M is the order of B+ tree. "
},
{
"code": null,
"e": 25545,
"s": 25243,
"text": "Every element is inserted into a leaf node. So, go to the appropriate leaf node.Insert the key into the leaf node in increasing order only if there is no overflow. If there is an overflow go ahead with the following steps mentioned below to deal with overflow while maintaining the B+ Tree properties."
},
{
"code": null,
"e": 25626,
"s": 25545,
"text": "Every element is inserted into a leaf node. So, go to the appropriate leaf node."
},
{
"code": null,
"e": 25848,
"s": 25626,
"text": "Insert the key into the leaf node in increasing order only if there is no overflow. If there is an overflow go ahead with the following steps mentioned below to deal with overflow while maintaining the B+ Tree properties."
},
{
"code": null,
"e": 25882,
"s": 25850,
"text": "Case 1: Overflow in leaf node "
},
{
"code": null,
"e": 26086,
"s": 25882,
"text": "Split the leaf node into two nodes.First node contains ceil((m-1)/2) values.Second node contains the remaining values.Copy the smallest search key value from second node to the parent node.(Right biased)"
},
{
"code": null,
"e": 26122,
"s": 26086,
"text": "Split the leaf node into two nodes."
},
{
"code": null,
"e": 26164,
"s": 26122,
"text": "First node contains ceil((m-1)/2) values."
},
{
"code": null,
"e": 26207,
"s": 26164,
"text": "Second node contains the remaining values."
},
{
"code": null,
"e": 26293,
"s": 26207,
"text": "Copy the smallest search key value from second node to the parent node.(Right biased)"
},
{
"code": null,
"e": 26364,
"s": 26293,
"text": "Below is the illustration of inserting 8 into B+ Tree of order of 5: "
},
{
"code": null,
"e": 26400,
"s": 26364,
"text": "Case 2: Overflow in non-leaf node "
},
{
"code": null,
"e": 26567,
"s": 26400,
"text": "Split the non leaf node into two nodes.First node contains ceil(m/2)-1 values.Move the smallest among remaining to the parent.Second node contains the remaining keys."
},
{
"code": null,
"e": 26607,
"s": 26567,
"text": "Split the non leaf node into two nodes."
},
{
"code": null,
"e": 26647,
"s": 26607,
"text": "First node contains ceil(m/2)-1 values."
},
{
"code": null,
"e": 26696,
"s": 26647,
"text": "Move the smallest among remaining to the parent."
},
{
"code": null,
"e": 26737,
"s": 26696,
"text": "Second node contains the remaining keys."
},
{
"code": null,
"e": 26809,
"s": 26737,
"text": "Below is the illustration of inserting 15 into B+ Tree of order of 5: "
},
{
"code": null,
"e": 27162,
"s": 26811,
"text": "Problem: Insert the following key values 6, 16, 26, 36, 46 on a B+ tree with order = 3. Solution: Step 1: The order is 3 so at maximum in a node so there can be only 2 search key values. As insertion happens on a leaf node only in a B+ tree so insert search key value 6 and 16 in increasing order in the node. Below is the illustration of the same: "
},
{
"code": null,
"e": 27578,
"s": 27162,
"text": "Step 2: We cannot insert 26 in the same node as it causes an overflow in the leaf node, We have to split the leaf node according to the rules. First part contains ceil((3-1)/2) values i.e., only 6. The second node contains the remaining values i.e., 16 and 26. Then also copy the smallest search key value from the second node to the parent node i.e., 16 to the parent node. Below is the illustration of the same: "
},
{
"code": null,
"e": 28078,
"s": 27578,
"text": "Step 3: Now the next value is 36 that is to be inserted after 26 but in that node, it causes an overflow again in that leaf node. Again follow the above steps to split the node. First part contains ceil((3-1)/2) values i.e., only 16. The second node contains the remaining values i.e., 26 and 36. Then also copy the smallest search key value from the second node to the parent node i.e., 26 to the parent node. Below is the illustration of the same: The illustration is shown in the diagram below. "
},
{
"code": null,
"e": 28777,
"s": 28078,
"text": "Step 4: Now we have to insert 46 which is to be inserted after 36 but it causes an overflow in the leaf node. So we split the node according to the rules. The first part contains 26 and the second part contains 36 and 46 but now we also have to copy 36 to the parent node but it causes overflow as only two search key values can be accommodated in a node. Now follow the steps to deal with overflow in the non-leaf node. First node contains ceil(3/2)-1 values i.e. ’16’. Move the smallest among remaining to the parent i.e ’26’ will be the new parent node. The second node contains the remaining keys i.e ’36’ and the rest of the leaf nodes remain the same. Below is the illustration of the same: "
},
{
"code": null,
"e": 28835,
"s": 28777,
"text": "Below is the implementation of insertion in the B+ tree: "
},
{
"code": null,
"e": 28839,
"s": 28835,
"text": "C++"
},
{
"code": null,
"e": 28847,
"s": 28839,
"text": "Python3"
},
{
"code": "// C++ program for implementing B+ Tree#include <climits>#include <fstream>#include <iostream>#include <sstream>using namespace std;int MAX = 3; // BP nodeclass Node { bool IS_LEAF; int *key, size; Node** ptr; friend class BPTree; public: Node();}; // BP treeclass BPTree { Node* root; void insertInternal(int, Node*, Node*); Node* findParent(Node*, Node*); public: BPTree(); void search(int); void insert(int); void display(Node*); Node* getRoot();}; // Constructor of NodeNode::Node(){ key = new int[MAX]; ptr = new Node*[MAX + 1];} // Initialise the BPTree NodeBPTree::BPTree(){ root = NULL;} // Function to find any element// in B+ Treevoid BPTree::search(int x){ // If tree is empty if (root == NULL) { cout << \"Tree is empty\\n\"; } // Traverse to find the value else { Node* cursor = root; // Till we reach leaf node while (cursor->IS_LEAF == false) { for (int i = 0; i < cursor->size; i++) { // If the element to be // found is not present if (x < cursor->key[i]) { cursor = cursor->ptr[i]; break; } // If reaches end of the // cursor node if (i == cursor->size - 1) { cursor = cursor->ptr[i + 1]; break; } } } // Traverse the cursor and find // the node with value x for (int i = 0; i < cursor->size; i++) { // If found then return if (cursor->key[i] == x) { cout << \"Found\\n\"; return; } } // Else element is not present cout << \"Not found\\n\"; }} // Function to implement the Insert// Operation in B+ Treevoid BPTree::insert(int x){ // If root is null then return // newly created node if (root == NULL) { root = new Node; root->key[0] = x; root->IS_LEAF = true; root->size = 1; } // Traverse the B+ Tree else { Node* cursor = root; Node* parent; // Till cursor reaches the // leaf node while (cursor->IS_LEAF == false) { parent = cursor; for (int i = 0; i < cursor->size; i++) { // If found the position // where we have to insert // node if (x < cursor->key[i]) { cursor = cursor->ptr[i]; break; } // If reaches the end if (i == cursor->size - 1) { cursor = cursor->ptr[i + 1]; break; } } } if (cursor->size < MAX) { int i = 0; while (x > cursor->key[i] && i < cursor->size) { i++; } for (int j = cursor->size; j > i; j--) { cursor->key[j] = cursor->key[j - 1]; } cursor->key[i] = x; cursor->size++; cursor->ptr[cursor->size] = cursor->ptr[cursor->size - 1]; cursor->ptr[cursor->size - 1] = NULL; } else { // Create a newLeaf node Node* newLeaf = new Node; int virtualNode[MAX + 1]; // Update cursor to virtual // node created for (int i = 0; i < MAX; i++) { virtualNode[i] = cursor->key[i]; } int i = 0, j; // Traverse to find where the new // node is to be inserted while (x > virtualNode[i] && i < MAX) { i++; } // Update the current virtual // Node to its previous for (int j = MAX + 1; j > i; j--) { virtualNode[j] = virtualNode[j - 1]; } virtualNode[i] = x; newLeaf->IS_LEAF = true; cursor->size = (MAX + 1) / 2; newLeaf->size = MAX + 1 - (MAX + 1) / 2; cursor->ptr[cursor->size] = newLeaf; newLeaf->ptr[newLeaf->size] = cursor->ptr[MAX]; cursor->ptr[MAX] = NULL; // Update the current virtual // Node's key to its previous for (i = 0; i < cursor->size; i++) { cursor->key[i] = virtualNode[i]; } // Update the newLeaf key to // virtual Node for (i = 0, j = cursor->size; i < newLeaf->size; i++, j++) { newLeaf->key[i] = virtualNode[j]; } // If cursor is the root node if (cursor == root) { // Create a new Node Node* newRoot = new Node; // Update rest field of // B+ Tree Node newRoot->key[0] = newLeaf->key[0]; newRoot->ptr[0] = cursor; newRoot->ptr[1] = newLeaf; newRoot->IS_LEAF = false; newRoot->size = 1; root = newRoot; } else { // Recursive Call for // insert in internal insertInternal(newLeaf->key[0], parent, newLeaf); } } }} // Function to implement the Insert// Internal Operation in B+ Treevoid BPTree::insertInternal(int x, Node* cursor, Node* child){ // If we doesn't have overflow if (cursor->size < MAX) { int i = 0; // Traverse the child node // for current cursor node while (x > cursor->key[i] && i < cursor->size) { i++; } // Traverse the cursor node // and update the current key // to its previous node key for (int j = cursor->size; j > i; j--) { cursor->key[j] = cursor->key[j - 1]; } // Traverse the cursor node // and update the current ptr // to its previous node ptr for (int j = cursor->size + 1; j > i + 1; j--) { cursor->ptr[j] = cursor->ptr[j - 1]; } cursor->key[i] = x; cursor->size++; cursor->ptr[i + 1] = child; } // For overflow, break the node else { // For new Interval Node* newInternal = new Node; int virtualKey[MAX + 1]; Node* virtualPtr[MAX + 2]; // Insert the current list key // of cursor node to virtualKey for (int i = 0; i < MAX; i++) { virtualKey[i] = cursor->key[i]; } // Insert the current list ptr // of cursor node to virtualPtr for (int i = 0; i < MAX + 1; i++) { virtualPtr[i] = cursor->ptr[i]; } int i = 0, j; // Traverse to find where the new // node is to be inserted while (x > virtualKey[i] && i < MAX) { i++; } // Traverse the virtualKey node // and update the current key // to its previous node key for (int j = MAX + 1; j > i; j--) { virtualKey[j] = virtualKey[j - 1]; } virtualKey[i] = x; // Traverse the virtualKey node // and update the current ptr // to its previous node ptr for (int j = MAX + 2; j > i + 1; j--) { virtualPtr[j] = virtualPtr[j - 1]; } virtualPtr[i + 1] = child; newInternal->IS_LEAF = false; cursor->size = (MAX + 1) / 2; newInternal->size = MAX - (MAX + 1) / 2; // Insert new node as an // internal node for (i = 0, j = cursor->size + 1; i < newInternal->size; i++, j++) { newInternal->key[i] = virtualKey[j]; } for (i = 0, j = cursor->size + 1; i < newInternal->size + 1; i++, j++) { newInternal->ptr[i] = virtualPtr[j]; } // If cursor is the root node if (cursor == root) { // Create a new root node Node* newRoot = new Node; // Update key value newRoot->key[0] = cursor->key[cursor->size]; // Update rest field of // B+ Tree Node newRoot->ptr[0] = cursor; newRoot->ptr[1] = newInternal; newRoot->IS_LEAF = false; newRoot->size = 1; root = newRoot; } else { // Recursive Call to insert // the data insertInternal(cursor->key[cursor->size], findParent(root, cursor), newInternal); } }} // Function to find the parent nodeNode* BPTree::findParent(Node* cursor, Node* child){ Node* parent; // If cursor reaches the end of Tree if (cursor->IS_LEAF || (cursor->ptr[0])->IS_LEAF) { return NULL; } // Traverse the current node with // all its child for (int i = 0; i < cursor->size + 1; i++) { // Update the parent for the // child Node if (cursor->ptr[i] == child) { parent = cursor; return parent; } // Else recursively traverse to // find child node else { parent = findParent(cursor->ptr[i], child); // If parent is found, then // return that parent node if (parent != NULL) return parent; } } // Return parent node return parent;} // Function to get the root NodeNode* BPTree::getRoot(){ return root;} // Driver Codeint main(){ BPTree node; // Create B+ Tree node.insert(6); node.insert(16); node.insert(26); node.insert(36); node.insert(46); // Function Call to search node // with value 16 node.search(16); return 0;}",
"e": 39405,
"s": 28847,
"text": null
},
{
"code": "# Python3 program for implementing B+ Tree MAX = 3 # BP nodeclass Node : def __init__(self): self.IS_LEAF=False self.key, self.size=[None]*MAX,0 self.ptr=[None]*(MAX+1) # BP treeclass BPTree : # Initialise the BPTree Node def __init__(self): self.root = None # Function to find any element# in B+ Tree def search(self,x): # If tree is empty if (self.root == None) : cout << \"Tree is empty\\n\" # Traverse to find the value else : cursor = self.root # Till we reach leaf node while (not cursor.IS_LEAF) : for i in range(cursor.size) : # If the element to be # found is not present if (x < cursor.key[i]) : cursor = cursor.ptr[i] break # If reaches end of the # cursor node if (i == cursor.size - 1) : cursor = cursor.ptr[i + 1] break # Traverse the cursor and find # the node with value x for i in range(cursor.size): # If found then return if (cursor.key[i] == x) : print(\"Found\") return # Else element is not present print(\"Not found\") # Function to implement the Insert # Operation in B+ Tree def insert(self, x): # If root is None then return # newly created node if (self.root == None) : self.root = Node() self.root.key[0] = x self.root.IS_LEAF = True self.root.size = 1 # Traverse the B+ Tree else : cursor = self.root parent=None # Till cursor reaches the # leaf node while (not cursor.IS_LEAF) : parent = cursor for i in range(cursor.size) : # If found the position # where we have to insert # node if (x < cursor.key[i]) : cursor = cursor.ptr[i] break # If reaches the end if (i == cursor.size - 1) : cursor = cursor.ptr[i + 1] break if (cursor.size < MAX) : i = 0 while (i < cursor.size and x > cursor.key[i]): i+=1 for j in range(cursor.size,i,-1): cursor.key[j] = cursor.key[j - 1] cursor.key[i] = x cursor.size+=1 cursor.ptr[cursor.size] = cursor.ptr[cursor.size - 1] cursor.ptr[cursor.size - 1] = None else : # Create a newLeaf node newLeaf = Node() virtualNode=[None]*(MAX + 1) # Update cursor to virtual # node created for i in range(MAX): virtualNode[i] = cursor.key[i] i = 0 # Traverse to find where the new # node is to be inserted while (i < MAX and x > virtualNode[i]) : i+=1 # Update the current virtual # Node to its previous for j in range(MAX,i,-1) : virtualNode[j] = virtualNode[j - 1] virtualNode[i] = x newLeaf.IS_LEAF = True cursor.size = int((MAX + 1) / 2) newLeaf.size = int(MAX + 1 - (MAX + 1) / 2) cursor.ptr[cursor.size] = newLeaf newLeaf.ptr[newLeaf.size] = cursor.ptr[MAX] cursor.ptr[MAX] = None # Update the current virtual # Node's key to its previous for i in range(cursor.size): cursor.key[i] = virtualNode[i] # Update the newLeaf key to # virtual Node j=cursor.size for i in range(newLeaf.size): newLeaf.key[i] = virtualNode[j] j+=1 # If cursor is the root node if (cursor == self.root) : # Create a new Node newRoot = Node() # Update rest field of # B+ Tree Node newRoot.key[0] = newLeaf.key[0] newRoot.ptr[0] = cursor newRoot.ptr[1] = newLeaf newRoot.IS_LEAF = False newRoot.size = 1 root = newRoot else : # Recursive Call for # insert in internal insertInternal(newLeaf.key[0], parent, newLeaf) # Function to implement the Insert# Internal Operation in B+ Treedef insertInternal(x, cursor, child): # If we doesn't have overflow if (cursor.size < MAX) : i = 0 # Traverse the child node # for current cursor node while (x > cursor.key[i] and i < cursor.size) : i+=1 # Traverse the cursor node # and update the current key # to its previous node key for j in range(cursor.size,i,-1) : cursor.key[j] = cursor.key[j - 1] # Traverse the cursor node # and update the current ptr # to its previous node ptr for j in range(cursor.size + 1, i + 1,-1): cursor.ptr[j] = cursor.ptr[j - 1] cursor.key[i] = x cursor.size+=1 cursor.ptr[i + 1] = child # For overflow, break the node else : # For new Interval newInternal = Node() virtualKey=[None]*(MAX + 1) virtualPtr=[None]*(MAX + 2) # Insert the current list key # of cursor node to virtualKey for i in range(MAX) : virtualKey[i] = cursor.key[i] # Insert the current list ptr # of cursor node to virtualPtr for i in range(MAX + 1): virtualPtr[i] = cursor.ptr[i] i = 0 # Traverse to find where the new # node is to be inserted while (x > virtualKey[i] and i < MAX) : i+=1 # Traverse the virtualKey node # and update the current key # to its previous node key for j in range(MAX + 1,i,-1): virtualKey[j] = virtualKey[j - 1] virtualKey[i] = x # Traverse the virtualKey node # and update the current ptr # to its previous node ptr for j in range(MAX + 2, i + 1,-1) : virtualPtr[j] = virtualPtr[j - 1] virtualPtr[i + 1] = child newInternal.IS_LEAF = false cursor.size = (MAX + 1) / 2 newInternal.size = MAX - (MAX + 1) / 2 # Insert new node as an # internal node j = cursor.size + 1 for i in range(newInternal.size): newInternal.key[i] = virtualKey[j] j+=1 j = cursor.size + 1 for i in range(newInternal.size): newInternal.ptr[i] = virtualKey[j] j+=1 # If cursor is the root node if (cursor == self.root) : # Create a new root node newRoot = self.root # Update key value newRoot.key[0] = cursor.key[cursor.size] # Update rest field of # B+ Tree Node newRoot.ptr[0] = cursor newRoot.ptr[1] = newInternal newRoot.IS_LEAF = false newRoot.size = 1 root = newRoot else : # Recursive Call to insert # the data insertInternal(cursor.key[cursor.size], findParent(root, cursor), newInternal) # Function to find the parent node def findParent(self, cursor, child): # If cursor reaches the end of Tree if (cursor.IS_LEAF or (cursor.ptr[0]).IS_LEAF) : return None # Traverse the current node with # all its child for i in range(cursor.size + 1) : # Update the parent for the # child Node if (cursor.ptr[i] == child) : parent = cursor return parent # Else recursively traverse to # find child node else : parent = findParent(cursor.ptr[i], child) # If parent is found, then # return that parent node if (parent != None): return parent # Return parent node return parent # Function to get the root Node def getRoot(self): return self.root # Driver Codeif __name__=='__main__': node=BPTree() # Create B+ Tree node.insert(6) node.insert(16) node.insert(26) node.insert(36) node.insert(46) # Function Call to search node # with value 16 node.search(16)",
"e": 49013,
"s": 39405,
"text": null
},
{
"code": null,
"e": 49019,
"s": 49013,
"text": "Found"
},
{
"code": null,
"e": 49037,
"s": 49021,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 49052,
"s": 49037,
"text": "B and B+ Trees"
},
{
"code": null,
"e": 49083,
"s": 49052,
"text": "Data Structures-B and B+ Trees"
},
{
"code": null,
"e": 49094,
"s": 49083,
"text": "Algorithms"
},
{
"code": null,
"e": 49110,
"s": 49094,
"text": "Data Structures"
},
{
"code": null,
"e": 49115,
"s": 49110,
"text": "Tree"
},
{
"code": null,
"e": 49131,
"s": 49115,
"text": "Data Structures"
},
{
"code": null,
"e": 49136,
"s": 49131,
"text": "Tree"
},
{
"code": null,
"e": 49147,
"s": 49136,
"text": "Algorithms"
},
{
"code": null,
"e": 49245,
"s": 49147,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49270,
"s": 49245,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 49313,
"s": 49270,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 49356,
"s": 49313,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 49385,
"s": 49356,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 49431,
"s": 49385,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 49456,
"s": 49431,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 49512,
"s": 49456,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 49559,
"s": 49512,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 49591,
"s": 49559,
"text": "Insertion and Deletion in Heaps"
}
] |
Why is Delta Lake becoming increasingly popular? | by Lingeshwaran Kanniappan | Towards Data Science | It can be confusing to understand the difference between a Delta lake and the Data lake for a beginner. Working with the former storage layer for more than a year now, I am sharing the particular advantages which a delta lake serves and how it overcomes the challenges of a traditional data lake architecture with some examples.
The examples are to make it more intuitive and non-technical. I believe this will serve as a good curation from different sources for what delta lake can bring to the table.
By definition, delta lake is NOT a separate storage container, rather an open-source storage layer that will run on top of the existing data lake and object stores. Let us think of it as an additional functionality on top of the present data lakes, as shown below.
It is powered by a delta engine which in turn is powered by a native execution engine known as Photon. This is a vectorized query engine written in C++ from scratch. It is in public preview as of the time of writing this article.
It is a container to store raw data. Consider it to be a dumping ground of pure raw data which is yet to be processed.
Some important features of Data Lake include - its flat architecture, the schema is enforced only when you do a read operation (schema-on-read). Hence it can store unstructured data easily with low latency.
However, with raw data came raw challenges 🧱
Data lakes cannot handle corrupted data well. There will be a need for complete reprocessing when we identify a failure during a data load.
The solution that delta lake provides in this scenario is by bringing in Atomicity. This means that there is either a full write/commit (or) no write (aka Atomic visibility).
It is binary while doing the commit operation. So, we will know when there is an issue in the data before the job is completed.
There is a single source of truth that is employed to serve this purpose. It is known as the transaction log (delta log files), and it keeps track of all the atomic transactions that are being written into the delta table. Spark then updates the table at the user’s side after every transaction.
The delta log files are JSON files (00000000000000000000.json, 00000000000000000001.json etc.) placed inside the _delta_log subdirectory together with occasional checkpoint files.
Inside a delta log file, there are also commitInfo, partitionValues and stats information which are different metadata attributes to keep track of the data changes that can benefit in improving the query efficiency.
Consider the following simple credit transaction, once the data is written it should get updated with the correct value of 110 £ after the service is up and running (or) remain as 100 £ with the transaction log capturing no commit information. This is what an atomic commit must look like.
Only one client can achieve the creation of the object via one atomic commit.
Partial execution can result in a non-atomic commit which happens in a data lake during server failure (or) other issues.
Two scenarios pose an issue when it comes to missing data:
Batch and stream processing data has necessitated the use of lambda architecture style that writes data into two different containers. The unification of both these workload types is not possible in a data lake.
During an overwrite operation (basically delete and write), there is a point in time when there is no data in the table and if any failure occurs during this instant, we will not see any data when we query it.
This data inconsistency is handled in Delta lake using the concept called optimistic concurrency control through which the data being written either by multiple users at the same time (or) by different types (batch/stream) is done in a serialized fashion. We can use the source as a batch table and the streaming table as a sink.
There are special scenarios where the concurrent operations cannot be performed optimistically, during which the delta engine throws an error.
When there is a loss of connection (or) some form of failure (or) multiple writes, the data to be committed should not be lost rather it is captured in the transaction log and it will perform the commit in a serialized fashion.
As described in the Consistency section, the operations happening in parallel needs to be serially isolated to avoid conflicts. This allows the unification of the data models (batch and stream) which was not possible in the case of a data lake.
This is how the isolation mechanism is addressing the challenge: The commits that are not yet completed are isolated by the rule of mutual exclusion. Only when the commit is successful it allows for a write /merge/ delete operation into the delta lake.
This also brings in the facility to use the standard (DELETE, UPDATE, MERGE INTO) commands on the delta lake data which helps in bringing CCPA/GDPR compliance to your data.
There are special scenarios where two operations can lead to conflicts in the delta table, which is captured here for further reference. In short, those conflicts can be avoided using partitioning on the column that is used in the filter command.
Here the transactions T1 and T2 are isolated and executed sequentially using the transaction log information. Hence, they both don’t contradict the data at any given instant.
Consider the scenario where there is a failure and the server-side during an operation. This can again, result in loss of data (or) a population of corrupted records. This cannot be avoided in a typical data lake.
However, due to transaction logging and on-disk storage persistence, the data will persist even when there is a system (or) server-side failure. Hence the non-volatile memory plays a crucial role in delta lake.
Here, the update operation can fail and/or a read can fail when the server is down. Since the transactions are stored on the disk, the latest value can be read from the delta table until the last commit.
In terms of authenticity, when we try to change the type of data being written into the data lake, it leads to corruption and missing records. Hence, there needs to be a check on the validity of the schema.
In delta lake, there is schema validation being performed before any commit. A different schema by default is prevented from performing an overwrite. In this way, the schema format in which the data is written should always match with the schema that was initially defined (aka schema-on-write).
If an overwrite is required, schema evolution is there for the rescue. This can be done by setting configuration options while performing the write operation.
Here, for the simple insert operation: When mergeSchema is set to true there is typecasting of the Float type to Long type. There is another option called overwriteSchema setting this to true will completely ignore the old data and creates a new table in its place.
Modern big data systems are consistent in making frequent and volumetric data changes. There needs to be an auditing system (or) rollback mechanism to monitor the changes that are happening. The support for which is not present in data lakes.
However, in a delta table, the current state of the data is the collective sum of all the commits recorded in the transaction log (_delta_log/) subdirectory within the table.
It serves as a recipe to build the data from scratch to its current form. This ability to create the data by traversing through the transaction log is called Time-travel (or) data versioning.
The previous versions of the data in the delta table can be accessed via the timestamp (or) the version number. The data in delta tables are ultimately stored as versioned parquet files.
This allows users to perform easier rollback operations to get back to the instant when the data was proper and undo the wrong commit.
Every table comes with a version number (or) timestamp which can be fetched from a DESCRIBE HISTORY <table_name>command. Either using the clause VERSION AS OF (or) TIMESTAMP AS OF we can get the snapshot of the table at that instant.
Metadata is the data of the data for the data. It consists of the schema, column name, type and transactional information of the table.
Metadata is continuously generated as the atomic commits are logged in the delta log. This can be used to keep track of all the changes that are happening due to all the sources.
This metadata management is scalable in Spark and its processing is distributed across the nodes just like the data. This captures the schema, time of the creation of the atomic commit, GUID (globally unique identifier), the format of the file and other configuration options.
The read/list operation is expensive in native object stores, whereas in the case of a delta lake the metadata read is parallelized from the log over the cluster.
This can be done using DESCRIBE HISTORY , DESCRIBE DETAIL SQL commands. This runs on the parallel processing engine and gives the underlying metadata information. For further reference, you can see the documentation here.
-- get the full historyDESCRIBE HISTORY '/data/balanceTable/' DESCRIBE HISTORY delta.'/data/balanceTable/'-- get the metadata of delta tableDESCRIBE DETAIL '/data/balanceTable/'DESCRIBE DETAIL delta.'/data/balanceTable/'
To conclude, all these challenges posed by a data lake were handled using a delta lake. It greatly reduces the complexity of raw data handling by keeping the data flow consistent and durable.
The key takeaway will be to use Delta lake when there is going to be a large amount of raw data with a focus on improving the query performance, data consistency and durability.
Please provide your constructive thoughts, comments (or) suggestions if any.
Also, feel free to connect with me on LinkedIn. Until next time! | [
{
"code": null,
"e": 500,
"s": 171,
"text": "It can be confusing to understand the difference between a Delta lake and the Data lake for a beginner. Working with the former storage layer for more than a year now, I am sharing the particular advantages which a delta lake serves and how it overcomes the challenges of a traditional data lake architecture with some examples."
},
{
"code": null,
"e": 674,
"s": 500,
"text": "The examples are to make it more intuitive and non-technical. I believe this will serve as a good curation from different sources for what delta lake can bring to the table."
},
{
"code": null,
"e": 939,
"s": 674,
"text": "By definition, delta lake is NOT a separate storage container, rather an open-source storage layer that will run on top of the existing data lake and object stores. Let us think of it as an additional functionality on top of the present data lakes, as shown below."
},
{
"code": null,
"e": 1169,
"s": 939,
"text": "It is powered by a delta engine which in turn is powered by a native execution engine known as Photon. This is a vectorized query engine written in C++ from scratch. It is in public preview as of the time of writing this article."
},
{
"code": null,
"e": 1288,
"s": 1169,
"text": "It is a container to store raw data. Consider it to be a dumping ground of pure raw data which is yet to be processed."
},
{
"code": null,
"e": 1495,
"s": 1288,
"text": "Some important features of Data Lake include - its flat architecture, the schema is enforced only when you do a read operation (schema-on-read). Hence it can store unstructured data easily with low latency."
},
{
"code": null,
"e": 1540,
"s": 1495,
"text": "However, with raw data came raw challenges 🧱"
},
{
"code": null,
"e": 1680,
"s": 1540,
"text": "Data lakes cannot handle corrupted data well. There will be a need for complete reprocessing when we identify a failure during a data load."
},
{
"code": null,
"e": 1855,
"s": 1680,
"text": "The solution that delta lake provides in this scenario is by bringing in Atomicity. This means that there is either a full write/commit (or) no write (aka Atomic visibility)."
},
{
"code": null,
"e": 1983,
"s": 1855,
"text": "It is binary while doing the commit operation. So, we will know when there is an issue in the data before the job is completed."
},
{
"code": null,
"e": 2279,
"s": 1983,
"text": "There is a single source of truth that is employed to serve this purpose. It is known as the transaction log (delta log files), and it keeps track of all the atomic transactions that are being written into the delta table. Spark then updates the table at the user’s side after every transaction."
},
{
"code": null,
"e": 2459,
"s": 2279,
"text": "The delta log files are JSON files (00000000000000000000.json, 00000000000000000001.json etc.) placed inside the _delta_log subdirectory together with occasional checkpoint files."
},
{
"code": null,
"e": 2675,
"s": 2459,
"text": "Inside a delta log file, there are also commitInfo, partitionValues and stats information which are different metadata attributes to keep track of the data changes that can benefit in improving the query efficiency."
},
{
"code": null,
"e": 2965,
"s": 2675,
"text": "Consider the following simple credit transaction, once the data is written it should get updated with the correct value of 110 £ after the service is up and running (or) remain as 100 £ with the transaction log capturing no commit information. This is what an atomic commit must look like."
},
{
"code": null,
"e": 3043,
"s": 2965,
"text": "Only one client can achieve the creation of the object via one atomic commit."
},
{
"code": null,
"e": 3165,
"s": 3043,
"text": "Partial execution can result in a non-atomic commit which happens in a data lake during server failure (or) other issues."
},
{
"code": null,
"e": 3224,
"s": 3165,
"text": "Two scenarios pose an issue when it comes to missing data:"
},
{
"code": null,
"e": 3436,
"s": 3224,
"text": "Batch and stream processing data has necessitated the use of lambda architecture style that writes data into two different containers. The unification of both these workload types is not possible in a data lake."
},
{
"code": null,
"e": 3646,
"s": 3436,
"text": "During an overwrite operation (basically delete and write), there is a point in time when there is no data in the table and if any failure occurs during this instant, we will not see any data when we query it."
},
{
"code": null,
"e": 3976,
"s": 3646,
"text": "This data inconsistency is handled in Delta lake using the concept called optimistic concurrency control through which the data being written either by multiple users at the same time (or) by different types (batch/stream) is done in a serialized fashion. We can use the source as a batch table and the streaming table as a sink."
},
{
"code": null,
"e": 4119,
"s": 3976,
"text": "There are special scenarios where the concurrent operations cannot be performed optimistically, during which the delta engine throws an error."
},
{
"code": null,
"e": 4347,
"s": 4119,
"text": "When there is a loss of connection (or) some form of failure (or) multiple writes, the data to be committed should not be lost rather it is captured in the transaction log and it will perform the commit in a serialized fashion."
},
{
"code": null,
"e": 4592,
"s": 4347,
"text": "As described in the Consistency section, the operations happening in parallel needs to be serially isolated to avoid conflicts. This allows the unification of the data models (batch and stream) which was not possible in the case of a data lake."
},
{
"code": null,
"e": 4845,
"s": 4592,
"text": "This is how the isolation mechanism is addressing the challenge: The commits that are not yet completed are isolated by the rule of mutual exclusion. Only when the commit is successful it allows for a write /merge/ delete operation into the delta lake."
},
{
"code": null,
"e": 5018,
"s": 4845,
"text": "This also brings in the facility to use the standard (DELETE, UPDATE, MERGE INTO) commands on the delta lake data which helps in bringing CCPA/GDPR compliance to your data."
},
{
"code": null,
"e": 5265,
"s": 5018,
"text": "There are special scenarios where two operations can lead to conflicts in the delta table, which is captured here for further reference. In short, those conflicts can be avoided using partitioning on the column that is used in the filter command."
},
{
"code": null,
"e": 5440,
"s": 5265,
"text": "Here the transactions T1 and T2 are isolated and executed sequentially using the transaction log information. Hence, they both don’t contradict the data at any given instant."
},
{
"code": null,
"e": 5654,
"s": 5440,
"text": "Consider the scenario where there is a failure and the server-side during an operation. This can again, result in loss of data (or) a population of corrupted records. This cannot be avoided in a typical data lake."
},
{
"code": null,
"e": 5865,
"s": 5654,
"text": "However, due to transaction logging and on-disk storage persistence, the data will persist even when there is a system (or) server-side failure. Hence the non-volatile memory plays a crucial role in delta lake."
},
{
"code": null,
"e": 6069,
"s": 5865,
"text": "Here, the update operation can fail and/or a read can fail when the server is down. Since the transactions are stored on the disk, the latest value can be read from the delta table until the last commit."
},
{
"code": null,
"e": 6276,
"s": 6069,
"text": "In terms of authenticity, when we try to change the type of data being written into the data lake, it leads to corruption and missing records. Hence, there needs to be a check on the validity of the schema."
},
{
"code": null,
"e": 6572,
"s": 6276,
"text": "In delta lake, there is schema validation being performed before any commit. A different schema by default is prevented from performing an overwrite. In this way, the schema format in which the data is written should always match with the schema that was initially defined (aka schema-on-write)."
},
{
"code": null,
"e": 6731,
"s": 6572,
"text": "If an overwrite is required, schema evolution is there for the rescue. This can be done by setting configuration options while performing the write operation."
},
{
"code": null,
"e": 6997,
"s": 6731,
"text": "Here, for the simple insert operation: When mergeSchema is set to true there is typecasting of the Float type to Long type. There is another option called overwriteSchema setting this to true will completely ignore the old data and creates a new table in its place."
},
{
"code": null,
"e": 7240,
"s": 6997,
"text": "Modern big data systems are consistent in making frequent and volumetric data changes. There needs to be an auditing system (or) rollback mechanism to monitor the changes that are happening. The support for which is not present in data lakes."
},
{
"code": null,
"e": 7415,
"s": 7240,
"text": "However, in a delta table, the current state of the data is the collective sum of all the commits recorded in the transaction log (_delta_log/) subdirectory within the table."
},
{
"code": null,
"e": 7607,
"s": 7415,
"text": "It serves as a recipe to build the data from scratch to its current form. This ability to create the data by traversing through the transaction log is called Time-travel (or) data versioning."
},
{
"code": null,
"e": 7794,
"s": 7607,
"text": "The previous versions of the data in the delta table can be accessed via the timestamp (or) the version number. The data in delta tables are ultimately stored as versioned parquet files."
},
{
"code": null,
"e": 7929,
"s": 7794,
"text": "This allows users to perform easier rollback operations to get back to the instant when the data was proper and undo the wrong commit."
},
{
"code": null,
"e": 8163,
"s": 7929,
"text": "Every table comes with a version number (or) timestamp which can be fetched from a DESCRIBE HISTORY <table_name>command. Either using the clause VERSION AS OF (or) TIMESTAMP AS OF we can get the snapshot of the table at that instant."
},
{
"code": null,
"e": 8299,
"s": 8163,
"text": "Metadata is the data of the data for the data. It consists of the schema, column name, type and transactional information of the table."
},
{
"code": null,
"e": 8478,
"s": 8299,
"text": "Metadata is continuously generated as the atomic commits are logged in the delta log. This can be used to keep track of all the changes that are happening due to all the sources."
},
{
"code": null,
"e": 8755,
"s": 8478,
"text": "This metadata management is scalable in Spark and its processing is distributed across the nodes just like the data. This captures the schema, time of the creation of the atomic commit, GUID (globally unique identifier), the format of the file and other configuration options."
},
{
"code": null,
"e": 8918,
"s": 8755,
"text": "The read/list operation is expensive in native object stores, whereas in the case of a delta lake the metadata read is parallelized from the log over the cluster."
},
{
"code": null,
"e": 9140,
"s": 8918,
"text": "This can be done using DESCRIBE HISTORY , DESCRIBE DETAIL SQL commands. This runs on the parallel processing engine and gives the underlying metadata information. For further reference, you can see the documentation here."
},
{
"code": null,
"e": 9368,
"s": 9140,
"text": "-- get the full historyDESCRIBE HISTORY '/data/balanceTable/' DESCRIBE HISTORY delta.'/data/balanceTable/'-- get the metadata of delta tableDESCRIBE DETAIL '/data/balanceTable/'DESCRIBE DETAIL delta.'/data/balanceTable/'"
},
{
"code": null,
"e": 9560,
"s": 9368,
"text": "To conclude, all these challenges posed by a data lake were handled using a delta lake. It greatly reduces the complexity of raw data handling by keeping the data flow consistent and durable."
},
{
"code": null,
"e": 9738,
"s": 9560,
"text": "The key takeaway will be to use Delta lake when there is going to be a large amount of raw data with a focus on improving the query performance, data consistency and durability."
},
{
"code": null,
"e": 9815,
"s": 9738,
"text": "Please provide your constructive thoughts, comments (or) suggestions if any."
}
] |
MySQL select query to fetch data with null value? | Let us first create a table −
mysql> create table DemoTable
(
CustomerName varchar(100),
CustomerCountryName varchar(100)
);
Query OK, 0 rows affected (0.95 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris','US');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Bob','UK');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Carol',NULL);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('David','AUS');
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable values('Mike',NULL);
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+---------------------+
| CustomerName | CustomerCountryName |
+--------------+---------------------+
| Chris | US |
| Bob | UK |
| Carol | NULL |
| David | AUS |
| Mike | NULL |
+--------------+---------------------+
5 rows in set (0.00 sec)
Following is the query to fetch data with null value −
mysql> select *from DemoTable where CustomerCountryName IS NULL;
This will produce the following output −
+--------------+---------------------+
| CustomerName | CustomerCountryName |
+--------------+---------------------+
| Carol | NULL |
| Mike | NULL |
+--------------+---------------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1230,
"s": 1092,
"text": "mysql> create table DemoTable\n(\n CustomerName varchar(100),\n CustomerCountryName varchar(100)\n);\nQuery OK, 0 rows affected (0.95 sec)"
},
{
"code": null,
"e": 1286,
"s": 1230,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1719,
"s": 1286,
"text": "mysql> insert into DemoTable values('Chris','US');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values('Bob','UK');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values('Carol',NULL);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('David','AUS');\nQuery OK, 1 row affected (0.32 sec)\nmysql> insert into DemoTable values('Mike',NULL);\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 1779,
"s": 1719,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1810,
"s": 1779,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1851,
"s": 1810,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2227,
"s": 1851,
"text": "+--------------+---------------------+\n| CustomerName | CustomerCountryName |\n+--------------+---------------------+\n| Chris | US |\n| Bob | UK |\n| Carol | NULL |\n| David | AUS |\n| Mike | NULL |\n+--------------+---------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2282,
"s": 2227,
"text": "Following is the query to fetch data with null value −"
},
{
"code": null,
"e": 2347,
"s": 2282,
"text": "mysql> select *from DemoTable where CustomerCountryName IS NULL;"
},
{
"code": null,
"e": 2388,
"s": 2347,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2647,
"s": 2388,
"text": "+--------------+---------------------+\n| CustomerName | CustomerCountryName |\n+--------------+---------------------+\n| Carol | NULL |\n| Mike | NULL |\n+--------------+---------------------+\n2 rows in set (0.00 sec)"
}
] |
java.lang.reflect.Proxy.newProxyInstance() Method Example | The java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) method returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.
Following is the declaration for java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces,
InvocationHandler h) method.
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
loader − the class loader to define the proxy class.
loader − the class loader to define the proxy class.
interfaces − the list of interfaces for the proxy class to implement.
interfaces − the list of interfaces for the proxy class to implement.
h − the invocation handler to dispatch method invocations to.
h − the invocation handler to dispatch method invocations to.
A proxy instance with the specified invocation handler of a proxy class that is defined by the specified class loader and that implements the specified interfaces.
IllegalArgumentException − if any of the restrictions on the parameters that may be passed to getProxyClass are violated.
IllegalArgumentException − if any of the restrictions on the parameters that may be passed to getProxyClass are violated.
NullPointerException − if the interfaces array argument or any of its elements are null, or if the invocation handler, h, is null.
NullPointerException − if the interfaces array argument or any of its elements are null, or if the invocation handler, h, is null.
The following example shows the usage of java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) method.
package com.tutorialspoint;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyDemo {
public static void main(String[] args) throws IllegalArgumentException {
InvocationHandler handler = new SampleInvocationHandler() ;
SampleInterface proxy = (SampleInterface) Proxy.newProxyInstance(
SampleInterface.class.getClassLoader(),
new Class[] { SampleInterface.class },
handler);
Class invocationHandler = Proxy.getInvocationHandler(proxy).getClass();
System.out.println(invocationHandler.getName());
}
}
class SampleInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("Welcome to TutorialsPoint");
return null;
}
}
interface SampleInterface {
void showMessage();
}
class SampleClass implements SampleInterface {
public void showMessage(){
System.out.println("Hello World");
}
}
Let us compile and run the above program, this will produce the following result −
com.tutorialspoint.SampleInvocationHandler
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1708,
"s": 1454,
"text": "The java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) method returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler."
},
{
"code": null,
"e": 1857,
"s": 1708,
"text": "Following is the declaration for java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces,\n InvocationHandler h) method."
},
{
"code": null,
"e": 2001,
"s": 1857,
"text": "public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,\n InvocationHandler h)\n throws IllegalArgumentException\n"
},
{
"code": null,
"e": 2054,
"s": 2001,
"text": "loader − the class loader to define the proxy class."
},
{
"code": null,
"e": 2107,
"s": 2054,
"text": "loader − the class loader to define the proxy class."
},
{
"code": null,
"e": 2177,
"s": 2107,
"text": "interfaces − the list of interfaces for the proxy class to implement."
},
{
"code": null,
"e": 2247,
"s": 2177,
"text": "interfaces − the list of interfaces for the proxy class to implement."
},
{
"code": null,
"e": 2309,
"s": 2247,
"text": "h − the invocation handler to dispatch method invocations to."
},
{
"code": null,
"e": 2371,
"s": 2309,
"text": "h − the invocation handler to dispatch method invocations to."
},
{
"code": null,
"e": 2535,
"s": 2371,
"text": "A proxy instance with the specified invocation handler of a proxy class that is defined by the specified class loader and that implements the specified interfaces."
},
{
"code": null,
"e": 2657,
"s": 2535,
"text": "IllegalArgumentException − if any of the restrictions on the parameters that may be passed to getProxyClass are violated."
},
{
"code": null,
"e": 2779,
"s": 2657,
"text": "IllegalArgumentException − if any of the restrictions on the parameters that may be passed to getProxyClass are violated."
},
{
"code": null,
"e": 2910,
"s": 2779,
"text": "NullPointerException − if the interfaces array argument or any of its elements are null, or if the invocation handler, h, is null."
},
{
"code": null,
"e": 3041,
"s": 2910,
"text": "NullPointerException − if the interfaces array argument or any of its elements are null, or if the invocation handler, h, is null."
},
{
"code": null,
"e": 3195,
"s": 3041,
"text": "The following example shows the usage of java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) method."
},
{
"code": null,
"e": 4266,
"s": 3195,
"text": "package com.tutorialspoint;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\n\npublic class ProxyDemo {\n public static void main(String[] args) throws IllegalArgumentException {\n InvocationHandler handler = new SampleInvocationHandler() ;\n SampleInterface proxy = (SampleInterface) Proxy.newProxyInstance(\n SampleInterface.class.getClassLoader(),\n new Class[] { SampleInterface.class },\n handler);\n Class invocationHandler = Proxy.getInvocationHandler(proxy).getClass();\n\n System.out.println(invocationHandler.getName());\n }\n}\n\nclass SampleInvocationHandler implements InvocationHandler {\n\n @Override\n public Object invoke(Object proxy, Method method, Object[] args)\n throws Throwable {\n System.out.println(\"Welcome to TutorialsPoint\"); \n return null;\n }\n}\n\ninterface SampleInterface {\n void showMessage();\n}\n\nclass SampleClass implements SampleInterface {\n public void showMessage(){\n System.out.println(\"Hello World\"); \n }\n}"
},
{
"code": null,
"e": 4349,
"s": 4266,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 4393,
"s": 4349,
"text": "com.tutorialspoint.SampleInvocationHandler\n"
},
{
"code": null,
"e": 4400,
"s": 4393,
"text": " Print"
},
{
"code": null,
"e": 4411,
"s": 4400,
"text": " Add Notes"
}
] |
How I can change the style of alert box using JavaScript? | You will not be able to change the style of a standard alert box in JavaScript. To change the style, use the following custom alert box. We’re using JavaScript library, jQuery to achive this.
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
function functionAlert(msg, myYes) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes").unbind().click(function() {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.show();
}
</script>
<style>
#confirm {
display: none;
background-color: #514E61;
color: #FFFFFF;
border: 1px solid #aaa;
position: fixed;
width: 250px;
left: 50%;
margin-left: -100px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#confirm button {
background-color: #48E5DA;
display: inline-block;
border-radius: 5px;
border: 1px solid #aaa;
padding: 5px;
text-align: center;
width: 80px;
cursor: pointer;
}
#confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id="confirm">
<div class="message">This is a warning message.</div>
<button class="yes">OK</button>
</div>
<input type="button" value="Click Me" onclick="functionAlert();" />
</body>
</html> | [
{
"code": null,
"e": 1254,
"s": 1062,
"text": "You will not be able to change the style of a standard alert box in JavaScript. To change the style, use the following custom alert box. We’re using JavaScript library, jQuery to achive this."
},
{
"code": null,
"e": 1264,
"s": 1254,
"text": "Live Demo"
},
{
"code": null,
"e": 2798,
"s": 1264,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n </script>\n <script>\n function functionAlert(msg, myYes) {\n var confirmBox = $(\"#confirm\");\n confirmBox.find(\".message\").text(msg);\n confirmBox.find(\".yes\").unbind().click(function() {\n confirmBox.hide();\n });\n confirmBox.find(\".yes\").click(myYes);\n confirmBox.show();\n }\n </script>\n <style>\n #confirm {\n display: none;\n background-color: #514E61;\n color: #FFFFFF;\n border: 1px solid #aaa;\n position: fixed;\n width: 250px;\n left: 50%;\n margin-left: -100px;\n padding: 6px 8px 8px;\n box-sizing: border-box;\n text-align: center;\n }\n #confirm button {\n background-color: #48E5DA;\n display: inline-block;\n border-radius: 5px;\n border: 1px solid #aaa;\n padding: 5px;\n text-align: center;\n width: 80px;\n cursor: pointer;\n }\n #confirm .message {\n text-align: left;\n }\n </style>\n </head>\n <body>\n <div id=\"confirm\">\n <div class=\"message\">This is a warning message.</div>\n <button class=\"yes\">OK</button>\n </div>\n <input type=\"button\" value=\"Click Me\" onclick=\"functionAlert();\" />\n </body>\n</html>"
}
] |
PriorityQueue clear() Method in Java | 10 Dec, 2018
The Java.util.PriorityQueue.clear() method is used to remove all the elements from a PriorityQueue. Using the clear() method only clears all the element from the queue and does not delete the queue. In other words, we can say that the clear() method is used to only empty an existing PriorityQueue.
Syntax:
Priority_Queue.clear()
Parameters: The method does not take any parameter
Return Value: The function does not returns any value.
Below programs illustrate the Java.util.PriorityQueue.clear() method:
Program 1:
// Java code to illustrate clear()import java.util.PriorityQueue; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add("Welcome"); queue.add("To"); queue.add("Geeks"); queue.add("4"); queue.add("Geeks"); // Displaying the PriorityQueue System.out.println("PriorityQueue: " + queue); // Clearing the PriorityQueue using clear() method queue.clear(); // Displaying the final Queue after clearing; System.out.println("The final Queue: " + queue); }}
PriorityQueue: [4, Geeks, To, Welcome, Geeks]
The final Queue: []
Program 2:
// Java code to illustrate clear()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); // Displaying the PriorityQueue System.out.println("PriorityQueue: " + queue); // Clearing the PriorityQueue using clear() method queue.clear(); // Displaying the final Queue after clearing; System.out.println("The final Queue: " + queue); }}
PriorityQueue: [5, 10, 30, 20, 15]
The final Queue: []
Java - util package
Java-Collections
Java-Functions
java-priority-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 327,
"s": 28,
"text": "The Java.util.PriorityQueue.clear() method is used to remove all the elements from a PriorityQueue. Using the clear() method only clears all the element from the queue and does not delete the queue. In other words, we can say that the clear() method is used to only empty an existing PriorityQueue."
},
{
"code": null,
"e": 335,
"s": 327,
"text": "Syntax:"
},
{
"code": null,
"e": 358,
"s": 335,
"text": "Priority_Queue.clear()"
},
{
"code": null,
"e": 409,
"s": 358,
"text": "Parameters: The method does not take any parameter"
},
{
"code": null,
"e": 464,
"s": 409,
"text": "Return Value: The function does not returns any value."
},
{
"code": null,
"e": 534,
"s": 464,
"text": "Below programs illustrate the Java.util.PriorityQueue.clear() method:"
},
{
"code": null,
"e": 545,
"s": 534,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate clear()import java.util.PriorityQueue; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add(\"Welcome\"); queue.add(\"To\"); queue.add(\"Geeks\"); queue.add(\"4\"); queue.add(\"Geeks\"); // Displaying the PriorityQueue System.out.println(\"PriorityQueue: \" + queue); // Clearing the PriorityQueue using clear() method queue.clear(); // Displaying the final Queue after clearing; System.out.println(\"The final Queue: \" + queue); }}",
"e": 1284,
"s": 545,
"text": null
},
{
"code": null,
"e": 1351,
"s": 1284,
"text": "PriorityQueue: [4, Geeks, To, Welcome, Geeks]\nThe final Queue: []\n"
},
{
"code": null,
"e": 1362,
"s": 1351,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate clear()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); // Displaying the PriorityQueue System.out.println(\"PriorityQueue: \" + queue); // Clearing the PriorityQueue using clear() method queue.clear(); // Displaying the final Queue after clearing; System.out.println(\"The final Queue: \" + queue); }}",
"e": 2070,
"s": 1362,
"text": null
},
{
"code": null,
"e": 2126,
"s": 2070,
"text": "PriorityQueue: [5, 10, 30, 20, 15]\nThe final Queue: []\n"
},
{
"code": null,
"e": 2146,
"s": 2126,
"text": "Java - util package"
},
{
"code": null,
"e": 2163,
"s": 2146,
"text": "Java-Collections"
},
{
"code": null,
"e": 2178,
"s": 2163,
"text": "Java-Functions"
},
{
"code": null,
"e": 2198,
"s": 2178,
"text": "java-priority-queue"
},
{
"code": null,
"e": 2203,
"s": 2198,
"text": "Java"
},
{
"code": null,
"e": 2208,
"s": 2203,
"text": "Java"
},
{
"code": null,
"e": 2225,
"s": 2208,
"text": "Java-Collections"
}
] |
Hive – Load Data Into Table | 24 Nov, 2020
Hive tables provide us the schema to store data in various formats (like CSV). Hive provides multiple ways to add data to the tables. We can use DML(Data Manipulation Language) queries in Hive to import or add data to the table. One can also directly put the table into the hive with HDFS commands. In case we have data in Relational Databases like MySQL, ORACLE, IBM DB2, etc. then we can use Sqoop to efficiently transfer PetaBytes of data between Hadoop and Hive. In this particular tutorial, we will be using Hive DML queries to Load or INSERT data to the Hive table.
To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system.
Step 1: Start all your Hadoop Daemon
start-dfs.sh # this will start namenode, datanode and secondary namenode
start-yarn.sh # this will start node manager and resource manager
jps # To check running daemons
Step 2: Launch hive from terminal
hive
In hive with DML statements, we can add data to the Hive table in 2 different ways.
Using INSERT Command
Load Data Statement
1. Using INSERT Command
Syntax:
INSERT INTO TABLE <table_name> VALUES (<add values as per column entity>);
Example:
To insert data into the table let’s create a table with the name student (By default hive uses its default database to store hive tables).
Command:
CREATE TABLE IF NOT EXISTS student(
Student_Name STRING,
Student_Rollno INT,
Student_Marks FLOAT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ',';
We have successfully created the student table in the Hive default database with the attribute Student_Name, Student_Rollno, and Student_Marks respectively.
Now, let’s insert data into this table with an INSERT query.
INSERT Query:
INSERT INTO TABLE student VALUES ('Dikshant',1,'95'),('Akshat', 2 , '96'),('Dhruv',3,'90');
We can check the data of the student table with the help of the below command.
SELECT * FROM student;
2. Load Data Statement
Hive provides us the functionality to load pre-created table entities either from our local file system or from HDFS. The LOAD DATA statement is used to load data into the hive table.
Syntax:
LOAD DATA [LOCAL] INPATH '<The table data location>' [OVERWRITE] INTO TABLE <table_name>;
Note:
The LOCAL Switch specifies that the data we are loading is available in our Local File System. If the LOCAL switch is not used, the hive will consider the location as an HDFS path location.
The OVERWRITE switch allows us to overwrite the table data.
Let’s make a CSV(Comma Separated Values) file with the name data.csv since we have provided ‘,’ as a field terminator while creating a table in the hive. We are creating this file in our local file system at ‘/home/dikshant/Documents’ for demonstration purposes.
Command:
cd /home/dikshant/Documents // To change the directory
touch data.csv // use to create data.csv file
nano data.csv // nano is a linux command line editor to edit files
cat data.csv // cat is used to see content of file
LOAD DATA to the student hive table with the help of the below command.
LOAD DATA LOCAL INPATH '/home/dikshant/Documents/data.csv' INTO TABLE student;
Let’s see the student table content to observe the effect with the help of the below command.
SELECT * FROM student;
We can observe that we have successfully added the data to the student table.
Apache-Hive
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Hadoop and Spark
Hadoop Streaming Using Python - Word Count Problem
Architecture of HBase
Hadoop - Different Modes of Operation
What is Big Data?
Architecture and Working of Hive
Applications of Big Data
Introduction to Apache Pig
What is Hadoop Streaming?
What is Schema On Read and Schema On Write in Hadoop? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 602,
"s": 28,
"text": "Hive tables provide us the schema to store data in various formats (like CSV). Hive provides multiple ways to add data to the tables. We can use DML(Data Manipulation Language) queries in Hive to import or add data to the table. One can also directly put the table into the hive with HDFS commands. In case we have data in Relational Databases like MySQL, ORACLE, IBM DB2, etc. then we can use Sqoop to efficiently transfer PetaBytes of data between Hadoop and Hive. In this particular tutorial, we will be using Hive DML queries to Load or INSERT data to the Hive table. "
},
{
"code": null,
"e": 724,
"s": 602,
"text": "To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system."
},
{
"code": null,
"e": 761,
"s": 724,
"text": "Step 1: Start all your Hadoop Daemon"
},
{
"code": null,
"e": 999,
"s": 761,
"text": "start-dfs.sh # this will start namenode, datanode and secondary namenode\nstart-yarn.sh # this will start node manager and resource manager \njps # To check running daemons\n"
},
{
"code": null,
"e": 1033,
"s": 999,
"text": "Step 2: Launch hive from terminal"
},
{
"code": null,
"e": 1039,
"s": 1033,
"text": "hive\n"
},
{
"code": null,
"e": 1123,
"s": 1039,
"text": "In hive with DML statements, we can add data to the Hive table in 2 different ways."
},
{
"code": null,
"e": 1144,
"s": 1123,
"text": "Using INSERT Command"
},
{
"code": null,
"e": 1164,
"s": 1144,
"text": "Load Data Statement"
},
{
"code": null,
"e": 1188,
"s": 1164,
"text": "1. Using INSERT Command"
},
{
"code": null,
"e": 1196,
"s": 1188,
"text": "Syntax:"
},
{
"code": null,
"e": 1272,
"s": 1196,
"text": "INSERT INTO TABLE <table_name> VALUES (<add values as per column entity>);\n"
},
{
"code": null,
"e": 1281,
"s": 1272,
"text": "Example:"
},
{
"code": null,
"e": 1420,
"s": 1281,
"text": "To insert data into the table let’s create a table with the name student (By default hive uses its default database to store hive tables)."
},
{
"code": null,
"e": 1430,
"s": 1420,
"text": "Command: "
},
{
"code": null,
"e": 1577,
"s": 1430,
"text": "CREATE TABLE IF NOT EXISTS student(\nStudent_Name STRING,\nStudent_Rollno INT,\nStudent_Marks FLOAT)\nROW FORMAT DELIMITED\nFIELDS TERMINATED BY ','; \n"
},
{
"code": null,
"e": 1735,
"s": 1577,
"text": "We have successfully created the student table in the Hive default database with the attribute Student_Name, Student_Rollno, and Student_Marks respectively. "
},
{
"code": null,
"e": 1796,
"s": 1735,
"text": "Now, let’s insert data into this table with an INSERT query."
},
{
"code": null,
"e": 1810,
"s": 1796,
"text": "INSERT Query:"
},
{
"code": null,
"e": 1903,
"s": 1810,
"text": "INSERT INTO TABLE student VALUES ('Dikshant',1,'95'),('Akshat', 2 , '96'),('Dhruv',3,'90');\n"
},
{
"code": null,
"e": 1982,
"s": 1903,
"text": "We can check the data of the student table with the help of the below command."
},
{
"code": null,
"e": 2007,
"s": 1982,
"text": "SELECT * FROM student; \n"
},
{
"code": null,
"e": 2030,
"s": 2007,
"text": "2. Load Data Statement"
},
{
"code": null,
"e": 2215,
"s": 2030,
"text": "Hive provides us the functionality to load pre-created table entities either from our local file system or from HDFS. The LOAD DATA statement is used to load data into the hive table."
},
{
"code": null,
"e": 2223,
"s": 2215,
"text": "Syntax:"
},
{
"code": null,
"e": 2314,
"s": 2223,
"text": "LOAD DATA [LOCAL] INPATH '<The table data location>' [OVERWRITE] INTO TABLE <table_name>;\n"
},
{
"code": null,
"e": 2320,
"s": 2314,
"text": "Note:"
},
{
"code": null,
"e": 2510,
"s": 2320,
"text": "The LOCAL Switch specifies that the data we are loading is available in our Local File System. If the LOCAL switch is not used, the hive will consider the location as an HDFS path location."
},
{
"code": null,
"e": 2570,
"s": 2510,
"text": "The OVERWRITE switch allows us to overwrite the table data."
},
{
"code": null,
"e": 2833,
"s": 2570,
"text": "Let’s make a CSV(Comma Separated Values) file with the name data.csv since we have provided ‘,’ as a field terminator while creating a table in the hive. We are creating this file in our local file system at ‘/home/dikshant/Documents’ for demonstration purposes."
},
{
"code": null,
"e": 2842,
"s": 2833,
"text": "Command:"
},
{
"code": null,
"e": 3119,
"s": 2842,
"text": "cd /home/dikshant/Documents // To change the directory \ntouch data.csv // use to create data.csv file \nnano data.csv // nano is a linux command line editor to edit files \ncat data.csv // cat is used to see content of file\n"
},
{
"code": null,
"e": 3191,
"s": 3119,
"text": "LOAD DATA to the student hive table with the help of the below command."
},
{
"code": null,
"e": 3271,
"s": 3191,
"text": "LOAD DATA LOCAL INPATH '/home/dikshant/Documents/data.csv' INTO TABLE student;\n"
},
{
"code": null,
"e": 3365,
"s": 3271,
"text": "Let’s see the student table content to observe the effect with the help of the below command."
},
{
"code": null,
"e": 3391,
"s": 3365,
"text": "SELECT * FROM student; \n"
},
{
"code": null,
"e": 3469,
"s": 3391,
"text": "We can observe that we have successfully added the data to the student table."
},
{
"code": null,
"e": 3481,
"s": 3469,
"text": "Apache-Hive"
},
{
"code": null,
"e": 3488,
"s": 3481,
"text": "Hadoop"
},
{
"code": null,
"e": 3495,
"s": 3488,
"text": "Hadoop"
},
{
"code": null,
"e": 3593,
"s": 3495,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3629,
"s": 3593,
"text": "Difference Between Hadoop and Spark"
},
{
"code": null,
"e": 3680,
"s": 3629,
"text": "Hadoop Streaming Using Python - Word Count Problem"
},
{
"code": null,
"e": 3702,
"s": 3680,
"text": "Architecture of HBase"
},
{
"code": null,
"e": 3740,
"s": 3702,
"text": "Hadoop - Different Modes of Operation"
},
{
"code": null,
"e": 3758,
"s": 3740,
"text": "What is Big Data?"
},
{
"code": null,
"e": 3791,
"s": 3758,
"text": "Architecture and Working of Hive"
},
{
"code": null,
"e": 3816,
"s": 3791,
"text": "Applications of Big Data"
},
{
"code": null,
"e": 3843,
"s": 3816,
"text": "Introduction to Apache Pig"
},
{
"code": null,
"e": 3869,
"s": 3843,
"text": "What is Hadoop Streaming?"
}
] |
Scala | Polymorphism | 20 Jun, 2019
Polymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as means many and means types. Scala implements polymorphism through virtual functions, overloaded functions and overloaded operators. Polymorphism is one of the most important concept of object oriented programming language. The most common use of polymorphism in object oriented programming occurs when a parent class reference is used to refer to a child class object. Here we will see how represent any function in many types and many forms. Real life example of polymorphism, a person at the same time can have different roles to play in life. Like a woman at the same time is a mother, a wife, an employee and a daughter. So the same person has to have many features but has to implement each as per the situation and the condition. Polymorphism is considered as one of the important features of Object Oriented Programming. In Scala the function can be applied to arguments of many types, or the type can have instances of many types.There are two principal forms of polymorphism:
Subtyping: In subtyping a subclass’s instance can be passed to a base class
Generics: By type parameterization, instances of a function or class are created .
Below are some examples:Example #1:
// Scala program to shows the usage of // many functions with the same name class example { // This is the first function with the name fun def func(a:Int) { println("First Execution:" + a); } // This is the second function with the name fun def func(a:Int, b:Int) { var sum = a + b; println("Second Execution:" + sum); } // This is the first function with the name fun def func(a:Int, b:Int, c:Int) { var product = a * b * c; println("Third Execution:" + product); } } // Creating objectobject Main { // Main method def main(args: Array[String]) { // Creating object of example class var ob = new example(); ob.func(120); ob.func(50, 70); ob.func(10, 5, 6); } }
Output:
First Execution:120
Second Execution:120
Third Execution:300
In above example we have three functions whose name is same (func) but parameters are different.
Example #2:
// Scala program to illustrate polymorphism// conceptclass example2{ // Function 1 def func(vehicle:String, category:String) { println("The Vehicle is:" + vehicle); println("The Vehicle category is:" + category); } // Function 2 def func(name:String, Marks:Int) { println("Student Name is:" + name); println("Marks obtained are:" + Marks); } // Function 3 def func(a:Int, b:Int) { var Sum = a + b; println("Sum is:" + Sum) } } // Creating objectobject Main { // Main method def main(args: Array[String]) { var A = new example2(); A.func("swift", "hatchback"); A.func("honda-city", "sedan"); A.func("Ashok", 95); A.func(10, 20); } }
Output:
The Vehicle is:swift
The Vehicle category is:hatchback
The Vehicle is:honda-city
The Vehicle category is:sedan
Student Name is:Ashok
Marks obtained are:95
Sum is:30
Picked
Scala
Scala-OOPS
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jun, 2019"
},
{
"code": null,
"e": 1135,
"s": 28,
"text": "Polymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as means many and means types. Scala implements polymorphism through virtual functions, overloaded functions and overloaded operators. Polymorphism is one of the most important concept of object oriented programming language. The most common use of polymorphism in object oriented programming occurs when a parent class reference is used to refer to a child class object. Here we will see how represent any function in many types and many forms. Real life example of polymorphism, a person at the same time can have different roles to play in life. Like a woman at the same time is a mother, a wife, an employee and a daughter. So the same person has to have many features but has to implement each as per the situation and the condition. Polymorphism is considered as one of the important features of Object Oriented Programming. In Scala the function can be applied to arguments of many types, or the type can have instances of many types.There are two principal forms of polymorphism:"
},
{
"code": null,
"e": 1211,
"s": 1135,
"text": "Subtyping: In subtyping a subclass’s instance can be passed to a base class"
},
{
"code": null,
"e": 1294,
"s": 1211,
"text": "Generics: By type parameterization, instances of a function or class are created ."
},
{
"code": null,
"e": 1330,
"s": 1294,
"text": "Below are some examples:Example #1:"
},
{
"code": "// Scala program to shows the usage of // many functions with the same name class example { // This is the first function with the name fun def func(a:Int) { println(\"First Execution:\" + a); } // This is the second function with the name fun def func(a:Int, b:Int) { var sum = a + b; println(\"Second Execution:\" + sum); } // This is the first function with the name fun def func(a:Int, b:Int, c:Int) { var product = a * b * c; println(\"Third Execution:\" + product); } } // Creating objectobject Main { // Main method def main(args: Array[String]) { // Creating object of example class var ob = new example(); ob.func(120); ob.func(50, 70); ob.func(10, 5, 6); } } ",
"e": 2155,
"s": 1330,
"text": null
},
{
"code": null,
"e": 2163,
"s": 2155,
"text": "Output:"
},
{
"code": null,
"e": 2225,
"s": 2163,
"text": "First Execution:120\nSecond Execution:120\nThird Execution:300\n"
},
{
"code": null,
"e": 2322,
"s": 2225,
"text": "In above example we have three functions whose name is same (func) but parameters are different."
},
{
"code": null,
"e": 2334,
"s": 2322,
"text": "Example #2:"
},
{
"code": "// Scala program to illustrate polymorphism// conceptclass example2{ // Function 1 def func(vehicle:String, category:String) { println(\"The Vehicle is:\" + vehicle); println(\"The Vehicle category is:\" + category); } // Function 2 def func(name:String, Marks:Int) { println(\"Student Name is:\" + name); println(\"Marks obtained are:\" + Marks); } // Function 3 def func(a:Int, b:Int) { var Sum = a + b; println(\"Sum is:\" + Sum) } } // Creating objectobject Main { // Main method def main(args: Array[String]) { var A = new example2(); A.func(\"swift\", \"hatchback\"); A.func(\"honda-city\", \"sedan\"); A.func(\"Ashok\", 95); A.func(10, 20); } } ",
"e": 3141,
"s": 2334,
"text": null
},
{
"code": null,
"e": 3149,
"s": 3141,
"text": "Output:"
},
{
"code": null,
"e": 3315,
"s": 3149,
"text": "The Vehicle is:swift\nThe Vehicle category is:hatchback\nThe Vehicle is:honda-city\nThe Vehicle category is:sedan\nStudent Name is:Ashok\nMarks obtained are:95\nSum is:30\n"
},
{
"code": null,
"e": 3322,
"s": 3315,
"text": "Picked"
},
{
"code": null,
"e": 3328,
"s": 3322,
"text": "Scala"
},
{
"code": null,
"e": 3339,
"s": 3328,
"text": "Scala-OOPS"
},
{
"code": null,
"e": 3345,
"s": 3339,
"text": "Scala"
}
] |
PLSQL | LOWER Function | 24 Sep, 2019
The PLSQL LOWER function is used for converting all letters in the specified string to lowercase. If there are characters in the string that are not letters, they are unaffected by this function.
The char to be converted can be any of the datatypes such as CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The value returned by the LOWER function is the same datatype as char. The database sets the case of the characters based on the binary mapping defined for the underlying character set.
Syntax:
LOWER( string )
Parameters Used:
string – It is used to specify the string which needs to be converted.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1:
DECLARE
Test_String string(20) := 'Geeksforgeeks';
BEGIN
dbms_output.put_line(LOWER(Test_String));
END;
Output:
geeksforgeeks
Example-2:
DECLARE
Test_String string(20) := 'GEEKSFORGEEKS';
BEGIN
dbms_output.put_line(LOWER(Test_String));
END;
Output:
geeksforgeeks
Example-3:
DECLARE
Test_String varchar2(30) := 'GEEKSFORGEEKS12345';
BEGIN
dbms_output.put_line(LOWER(Test_String));
END;
Output:
geeksforgeeks12345
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Sep, 2019"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "The PLSQL LOWER function is used for converting all letters in the specified string to lowercase. If there are characters in the string that are not letters, they are unaffected by this function."
},
{
"code": null,
"e": 521,
"s": 224,
"text": "The char to be converted can be any of the datatypes such as CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The value returned by the LOWER function is the same datatype as char. The database sets the case of the characters based on the binary mapping defined for the underlying character set."
},
{
"code": null,
"e": 529,
"s": 521,
"text": "Syntax:"
},
{
"code": null,
"e": 545,
"s": 529,
"text": "LOWER( string )"
},
{
"code": null,
"e": 562,
"s": 545,
"text": "Parameters Used:"
},
{
"code": null,
"e": 633,
"s": 562,
"text": "string – It is used to specify the string which needs to be converted."
},
{
"code": null,
"e": 669,
"s": 633,
"text": "Supported Versions of Oracle/PLSQL:"
},
{
"code": null,
"e": 718,
"s": 669,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 729,
"s": 718,
"text": "Oracle 12c"
},
{
"code": null,
"e": 740,
"s": 729,
"text": "Oracle 11g"
},
{
"code": null,
"e": 751,
"s": 740,
"text": "Oracle 10g"
},
{
"code": null,
"e": 761,
"s": 751,
"text": "Oracle 9i"
},
{
"code": null,
"e": 771,
"s": 761,
"text": "Oracle 8i"
},
{
"code": null,
"e": 782,
"s": 771,
"text": "Example-1:"
},
{
"code": null,
"e": 905,
"s": 782,
"text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(LOWER(Test_String)); \n \nEND; "
},
{
"code": null,
"e": 913,
"s": 905,
"text": "Output:"
},
{
"code": null,
"e": 928,
"s": 913,
"text": "geeksforgeeks "
},
{
"code": null,
"e": 939,
"s": 928,
"text": "Example-2:"
},
{
"code": null,
"e": 1064,
"s": 939,
"text": "DECLARE \n Test_String string(20) := 'GEEKSFORGEEKS';\n \nBEGIN \n dbms_output.put_line(LOWER(Test_String)); \n \nEND; "
},
{
"code": null,
"e": 1072,
"s": 1064,
"text": "Output:"
},
{
"code": null,
"e": 1087,
"s": 1072,
"text": "geeksforgeeks "
},
{
"code": null,
"e": 1098,
"s": 1087,
"text": "Example-3:"
},
{
"code": null,
"e": 1230,
"s": 1098,
"text": "DECLARE \n Test_String varchar2(30) := 'GEEKSFORGEEKS12345';\n \nBEGIN \n dbms_output.put_line(LOWER(Test_String)); \n \nEND; "
},
{
"code": null,
"e": 1238,
"s": 1230,
"text": "Output:"
},
{
"code": null,
"e": 1258,
"s": 1238,
"text": "geeksforgeeks12345 "
},
{
"code": null,
"e": 1269,
"s": 1258,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 1273,
"s": 1269,
"text": "SQL"
},
{
"code": null,
"e": 1277,
"s": 1273,
"text": "SQL"
}
] |
Different ways to Invert the Binary bits in Python | 20 Aug, 2020
We know how binary value for numbers look like. For example, the binary value for 10 (Number Ten) is 1010 (binary value).
Sometimes it is required to inverse the bits i.e., 0’s to 1’s ( zeros to ones) and 1’s to 0’s (ones to zeros). Here are there few ways by which we can inverse the bits in Python.
1) Using Loops: By iterating each and every bit we can change the bit 1 to bit 0 and vice-versa.
Python3
bit_s = '1010'inverse_s = '' for i in bit_s: if i == '0': inverse_s += '1' else: inverse_s += '0' print("Inversed string is ", inverse_s)
Output:
Inversed string is 0101
2) Using Dictionary: Dictionaries are very fast in accessing an element, which it takes O(1) time complexity.
Python3
# create a dictionaryb_dict = {'0': '1', '1': '0'} bit_s = '1010' inverse_s = '' for i in bit_s: inverse_s += b_dict[i] print("Inversed string is", inverse_s)
Output:
Inversed string is 0101
3) Using List comprehension: List comprehensions are the short hand notations of accessing, adding, manipulating a list.
Python3
bit_s = '1010' # using ternary operator with # list comprehensioninverse_s = ''.join(['1' if i == '0' else '0' for i in bit_s]) print("Inversed string is", inverse_s)
Output:
Inversed string is 0101
4) Using replace() method of strings: In python, strings has a built-in method i.e., string.replace(existing_characters, new_characters), which replaces all the existing_characters with new_characters.
Python3
bit_s = '1010' # replace "1" with "2" # output : "2020"inverse_s = bit_s.replace('1', '2') # replace "0" with "1" # output : "2121"inverse_s = inverse_s.replace('0', '1') # replace "0" with "1" # output : "0101"inverse_s = inverse_s.replace('2', '0') print("Inversed string is", inverse_s)
Output:
Inversed string is 0101
5) Using bit-wise XOR operator: XOR operator Returns 1 if one of the bit is 1 and other is 0 else returns false.
Python3
bit_s = '1010' # convert binary string # into integertemp = int(bit_s, 2) # applying Ex-or operator# b/w 10 and 31inverse_s = temp ^ (2 ** (len(bit_s) + 1) - 1) # convert the integer result # into binary result and then # slicing of the '0b1' # binary indicatorrslt = bin(inverse_s)[3 : ] # print the resultprint("Inversed string is", rslt )
Output:
Inversed string is 0101
binary-string
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 174,
"s": 52,
"text": "We know how binary value for numbers look like. For example, the binary value for 10 (Number Ten) is 1010 (binary value)."
},
{
"code": null,
"e": 353,
"s": 174,
"text": "Sometimes it is required to inverse the bits i.e., 0’s to 1’s ( zeros to ones) and 1’s to 0’s (ones to zeros). Here are there few ways by which we can inverse the bits in Python."
},
{
"code": null,
"e": 450,
"s": 353,
"text": "1) Using Loops: By iterating each and every bit we can change the bit 1 to bit 0 and vice-versa."
},
{
"code": null,
"e": 458,
"s": 450,
"text": "Python3"
},
{
"code": "bit_s = '1010'inverse_s = '' for i in bit_s: if i == '0': inverse_s += '1' else: inverse_s += '0' print(\"Inversed string is \", inverse_s)",
"e": 645,
"s": 458,
"text": null
},
{
"code": null,
"e": 653,
"s": 645,
"text": "Output:"
},
{
"code": null,
"e": 678,
"s": 653,
"text": "Inversed string is 0101\n"
},
{
"code": null,
"e": 788,
"s": 678,
"text": "2) Using Dictionary: Dictionaries are very fast in accessing an element, which it takes O(1) time complexity."
},
{
"code": null,
"e": 796,
"s": 788,
"text": "Python3"
},
{
"code": "# create a dictionaryb_dict = {'0': '1', '1': '0'} bit_s = '1010' inverse_s = '' for i in bit_s: inverse_s += b_dict[i] print(\"Inversed string is\", inverse_s)",
"e": 975,
"s": 796,
"text": null
},
{
"code": null,
"e": 983,
"s": 975,
"text": "Output:"
},
{
"code": null,
"e": 1008,
"s": 983,
"text": "Inversed string is 0101\n"
},
{
"code": null,
"e": 1129,
"s": 1008,
"text": "3) Using List comprehension: List comprehensions are the short hand notations of accessing, adding, manipulating a list."
},
{
"code": null,
"e": 1137,
"s": 1129,
"text": "Python3"
},
{
"code": "bit_s = '1010' # using ternary operator with # list comprehensioninverse_s = ''.join(['1' if i == '0' else '0' for i in bit_s]) print(\"Inversed string is\", inverse_s)",
"e": 1332,
"s": 1137,
"text": null
},
{
"code": null,
"e": 1340,
"s": 1332,
"text": "Output:"
},
{
"code": null,
"e": 1365,
"s": 1340,
"text": "Inversed string is 0101\n"
},
{
"code": null,
"e": 1567,
"s": 1365,
"text": "4) Using replace() method of strings: In python, strings has a built-in method i.e., string.replace(existing_characters, new_characters), which replaces all the existing_characters with new_characters."
},
{
"code": null,
"e": 1575,
"s": 1567,
"text": "Python3"
},
{
"code": "bit_s = '1010' # replace \"1\" with \"2\" # output : \"2020\"inverse_s = bit_s.replace('1', '2') # replace \"0\" with \"1\" # output : \"2121\"inverse_s = inverse_s.replace('0', '1') # replace \"0\" with \"1\" # output : \"0101\"inverse_s = inverse_s.replace('2', '0') print(\"Inversed string is\", inverse_s)",
"e": 1875,
"s": 1575,
"text": null
},
{
"code": null,
"e": 1883,
"s": 1875,
"text": "Output:"
},
{
"code": null,
"e": 1908,
"s": 1883,
"text": "Inversed string is 0101\n"
},
{
"code": null,
"e": 2021,
"s": 1908,
"text": "5) Using bit-wise XOR operator: XOR operator Returns 1 if one of the bit is 1 and other is 0 else returns false."
},
{
"code": null,
"e": 2029,
"s": 2021,
"text": "Python3"
},
{
"code": "bit_s = '1010' # convert binary string # into integertemp = int(bit_s, 2) # applying Ex-or operator# b/w 10 and 31inverse_s = temp ^ (2 ** (len(bit_s) + 1) - 1) # convert the integer result # into binary result and then # slicing of the '0b1' # binary indicatorrslt = bin(inverse_s)[3 : ] # print the resultprint(\"Inversed string is\", rslt )",
"e": 2381,
"s": 2029,
"text": null
},
{
"code": null,
"e": 2389,
"s": 2381,
"text": "Output:"
},
{
"code": null,
"e": 2415,
"s": 2389,
"text": "Inversed string is 0101\n"
},
{
"code": null,
"e": 2429,
"s": 2415,
"text": "binary-string"
},
{
"code": null,
"e": 2443,
"s": 2429,
"text": "python-string"
},
{
"code": null,
"e": 2450,
"s": 2443,
"text": "Python"
},
{
"code": null,
"e": 2548,
"s": 2450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2566,
"s": 2548,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2608,
"s": 2566,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2643,
"s": 2608,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2669,
"s": 2643,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2701,
"s": 2669,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2730,
"s": 2701,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2757,
"s": 2730,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2778,
"s": 2757,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2801,
"s": 2778,
"text": "Introduction To PYTHON"
}
] |
Difference Between Data Hiding and Abstraction in Java | 06 Jun, 2021
Abstraction Is hiding the internal implementation and just highlight the set of services. It is achieved by using the abstract class and interfaces and further implementing the same. Only necessarily characteristics of an object that differentiates it from all other objects. Only the important details are emphasized and the rest all are suppressed from the user or reader.
A real-life example of abstraction
By using ATM GUI screen bank people are highlighting the set of services what the bank is offering without highlighting internal implementation.
Types of Abstraction: There are basically three types of abstraction
Procedural AbstractionData AbstractionControl Abstraction
Procedural Abstraction
Data Abstraction
Control Abstraction
1. Procedural Abstraction: From the word itself, there are a series of procedures in form of functions followed by one after another in sequence to attain abstraction through classes.
2. Data Abstraction: From the word itself, abstraction is achieved from a set of data that is describing an object.
3. Control Abstraction: Abstraction is achieved in writing the program in such a way where object details are enclosed.
Advantages of Abstraction:
Users or communities can achieve security as there are no highlights to internal implementation.
The enhancement will become very easy because without affecting end users one is able to perform any type of changes in the internal system
It provides more flexibility to end-user to use the system very easily
It improves the richness of application
Implementation of Abstraction: It is implemented as a class which only represents the important traits without including background detailing. Providing only the necessary details and hiding all its internal implementation. Below is the java implementation of abstraction:
Java
// Java program showing the working of abstraction // Importing generic librariesimport java.io.*; // Creating an abstract class// demonstrate abstractionabstract class Creature { // Just providing that creatures has legs // Hiding the number of legs abstract void No_Of_legs();} // A new child class is extending// the parent abstract class aboveclass Elephant extends Creature { // Implementation of the abstract method void No_Of_legs() { // Printing message of function in non abstract // child class System.out.println("It has four legs"); }} // Again a new child class is extended from parent// Human class to override function created aboveclass Human extends Creature { // Same function over-riden public void No_Of_legs() { // Message printed if this function is called or // Implementation of the abstract method System.out.println("It has two legs"); }} public class GFG { // Main driver method public static void main(String[] args) { // Creating human object showing the implementation Human ob = new Human(); ob.No_Of_legs(); // Creating object of above class in main Elephant ob1 = new Elephant(); // Calling the function in main by // creating object of above non abstract class ob1.No_Of_legs(); // Implementation of abstraction }}
It has two legs
It has four legs
Now, jumping onto the second concept though both the concepts are used to achieve encapsulation somehow there is a sleek difference as shown below:
Data Hiding is hiding internal data from outside users. The internal data should not go directly that is outside person/classes is not able to access internal data directly. It is achieved by using an access specifier- a private modifier.
Note: The recommended modifier for data members is private. The main advantage of data hiding is security
Sample for data hiding:
class Account {
private double account_balance;
........
.......
}
Here account balance of each say employee is private to each other being working in the same organization. No body knows account balance of anybody. In java it is achieved by using a keyword ‘private’ keyword and the process is called data hiding.
It is used as security such that no internal data will be accessed without authentication. An unauthorized end user will not get access to internal data. Programmatically we can implement data hiding by declaring data elements as private. Now to access this data or for modification, we have a special method known as getter setter respectively.
Getter is used to accessing the private data and setter is used to modify the private data only after authentication.In simple terms, it is hiding internal data from outside users.
It is used as security such that no internal data will be accessed without authentication. An unauthorized end user will not get access to internal data. Programmatically we can implement data hiding by declaring data elements as private.
Now to access this data or for modification, we have a special method known as getter setter respectively.
Concept involved in data Hiding: Getter and setter
Getter is used to accessing the private data and setter is used to modify the private data only after authentication. In simple terms, it is hiding internal data from outside users. It is used as security such that no internal data will be accessed without authentication. An unauthorized end user will not get access to internal data. Programmatically we can implement data hiding by declaring data elements as private. Now to access this data or for modification, we have a special method known as getter setter respectively.
Getter is used to accessing the private data and setter is used to modify the private data only after authentication. In simple terms, it is hiding internal data from outside users. It is used as security such that no internal data will be accessed without authentication. An unauthorized end user will not get access to internal data. Programmatically we can implement data hiding by declaring data elements as private.
Now to access this data or for modification, we have a special method known as getter setter respectively. Getter is used to accessing the private data and setter is used to modify the private data only after authentication.
Implementation of Data Hiding:
Java
// Java Program showing working of data hiding // Importing generic librariesimport java.io.*; // Class created named Bankclass Bank { // Private data (data hiding) private long CurBalance = 0; // Bank_id is checked for authentication long bank_id; String name; // Getter function to modify private data public long get_balance(long Id) { // Checking whether the user is // authorised or unauthorised // Comparing bank_id of user and the give Id // then only it will get access if (this.bank_id == Id) { // Return current balance return CurBalance; } // Unauthorised user return -1; } // Setter function public void set_balance(long balance, long Id) { // Comparing bank_id of user and the give Id // then only it will get access if (this.bank_id == Id) { // Update balance in current ID CurBalance = CurBalance + balance; } }} // Another class created- Employeepublic class Emp { public static void main(String[] args) { // Creating employee object of bank type Bank _emp = new Bank(); // Assigning employee object values _emp.bank_id = 12345; _emp.name = "Roshan"; // _emp.get_balance(123456) _emp.set_balance(10000, 12345); // This will no get access as bank_id is given wrong // so // unauthorised user is not getting access that is // data hiding long emp_balance = _emp.get_balance(12345); // As this time it is valid user it will get access // Display commands System.out.println("User Name" + " " + _emp.name); System.out.println("Bank_ID" + " " + _emp.bank_id); System.out.println("Current Balance" + " " + emp_balance); }}
Output:
User Name Roshan
Bank_ID 12345
Current Balance 10000
simranarora5sos
Java-Object Oriented
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 427,
"s": 52,
"text": "Abstraction Is hiding the internal implementation and just highlight the set of services. It is achieved by using the abstract class and interfaces and further implementing the same. Only necessarily characteristics of an object that differentiates it from all other objects. Only the important details are emphasized and the rest all are suppressed from the user or reader."
},
{
"code": null,
"e": 462,
"s": 427,
"text": "A real-life example of abstraction"
},
{
"code": null,
"e": 608,
"s": 462,
"text": "By using ATM GUI screen bank people are highlighting the set of services what the bank is offering without highlighting internal implementation. "
},
{
"code": null,
"e": 677,
"s": 608,
"text": "Types of Abstraction: There are basically three types of abstraction"
},
{
"code": null,
"e": 735,
"s": 677,
"text": "Procedural AbstractionData AbstractionControl Abstraction"
},
{
"code": null,
"e": 758,
"s": 735,
"text": "Procedural Abstraction"
},
{
"code": null,
"e": 775,
"s": 758,
"text": "Data Abstraction"
},
{
"code": null,
"e": 795,
"s": 775,
"text": "Control Abstraction"
},
{
"code": null,
"e": 979,
"s": 795,
"text": "1. Procedural Abstraction: From the word itself, there are a series of procedures in form of functions followed by one after another in sequence to attain abstraction through classes."
},
{
"code": null,
"e": 1095,
"s": 979,
"text": "2. Data Abstraction: From the word itself, abstraction is achieved from a set of data that is describing an object."
},
{
"code": null,
"e": 1215,
"s": 1095,
"text": "3. Control Abstraction: Abstraction is achieved in writing the program in such a way where object details are enclosed."
},
{
"code": null,
"e": 1242,
"s": 1215,
"text": "Advantages of Abstraction:"
},
{
"code": null,
"e": 1339,
"s": 1242,
"text": "Users or communities can achieve security as there are no highlights to internal implementation."
},
{
"code": null,
"e": 1479,
"s": 1339,
"text": "The enhancement will become very easy because without affecting end users one is able to perform any type of changes in the internal system"
},
{
"code": null,
"e": 1550,
"s": 1479,
"text": "It provides more flexibility to end-user to use the system very easily"
},
{
"code": null,
"e": 1590,
"s": 1550,
"text": "It improves the richness of application"
},
{
"code": null,
"e": 1864,
"s": 1590,
"text": "Implementation of Abstraction: It is implemented as a class which only represents the important traits without including background detailing. Providing only the necessary details and hiding all its internal implementation. Below is the java implementation of abstraction: "
},
{
"code": null,
"e": 1869,
"s": 1864,
"text": "Java"
},
{
"code": "// Java program showing the working of abstraction // Importing generic librariesimport java.io.*; // Creating an abstract class// demonstrate abstractionabstract class Creature { // Just providing that creatures has legs // Hiding the number of legs abstract void No_Of_legs();} // A new child class is extending// the parent abstract class aboveclass Elephant extends Creature { // Implementation of the abstract method void No_Of_legs() { // Printing message of function in non abstract // child class System.out.println(\"It has four legs\"); }} // Again a new child class is extended from parent// Human class to override function created aboveclass Human extends Creature { // Same function over-riden public void No_Of_legs() { // Message printed if this function is called or // Implementation of the abstract method System.out.println(\"It has two legs\"); }} public class GFG { // Main driver method public static void main(String[] args) { // Creating human object showing the implementation Human ob = new Human(); ob.No_Of_legs(); // Creating object of above class in main Elephant ob1 = new Elephant(); // Calling the function in main by // creating object of above non abstract class ob1.No_Of_legs(); // Implementation of abstraction }}",
"e": 3280,
"s": 1869,
"text": null
},
{
"code": null,
"e": 3316,
"s": 3283,
"text": "It has two legs\nIt has four legs"
},
{
"code": null,
"e": 3468,
"s": 3320,
"text": "Now, jumping onto the second concept though both the concepts are used to achieve encapsulation somehow there is a sleek difference as shown below:"
},
{
"code": null,
"e": 3710,
"s": 3470,
"text": "Data Hiding is hiding internal data from outside users. The internal data should not go directly that is outside person/classes is not able to access internal data directly. It is achieved by using an access specifier- a private modifier. "
},
{
"code": null,
"e": 3818,
"s": 3712,
"text": "Note: The recommended modifier for data members is private. The main advantage of data hiding is security"
},
{
"code": null,
"e": 3844,
"s": 3820,
"text": "Sample for data hiding:"
},
{
"code": null,
"e": 3862,
"s": 3846,
"text": "class Account {"
},
{
"code": null,
"e": 3894,
"s": 3862,
"text": "private double account_balance;"
},
{
"code": null,
"e": 3903,
"s": 3894,
"text": "........"
},
{
"code": null,
"e": 3911,
"s": 3903,
"text": "......."
},
{
"code": null,
"e": 3913,
"s": 3911,
"text": "}"
},
{
"code": null,
"e": 4161,
"s": 3913,
"text": "Here account balance of each say employee is private to each other being working in the same organization. No body knows account balance of anybody. In java it is achieved by using a keyword ‘private’ keyword and the process is called data hiding."
},
{
"code": null,
"e": 4507,
"s": 4161,
"text": "It is used as security such that no internal data will be accessed without authentication. An unauthorized end user will not get access to internal data. Programmatically we can implement data hiding by declaring data elements as private. Now to access this data or for modification, we have a special method known as getter setter respectively."
},
{
"code": null,
"e": 4690,
"s": 4509,
"text": "Getter is used to accessing the private data and setter is used to modify the private data only after authentication.In simple terms, it is hiding internal data from outside users."
},
{
"code": null,
"e": 4931,
"s": 4692,
"text": "It is used as security such that no internal data will be accessed without authentication. An unauthorized end user will not get access to internal data. Programmatically we can implement data hiding by declaring data elements as private."
},
{
"code": null,
"e": 5040,
"s": 4933,
"text": "Now to access this data or for modification, we have a special method known as getter setter respectively."
},
{
"code": null,
"e": 5093,
"s": 5042,
"text": "Concept involved in data Hiding: Getter and setter"
},
{
"code": null,
"e": 5623,
"s": 5095,
"text": "Getter is used to accessing the private data and setter is used to modify the private data only after authentication. In simple terms, it is hiding internal data from outside users. It is used as security such that no internal data will be accessed without authentication. An unauthorized end user will not get access to internal data. Programmatically we can implement data hiding by declaring data elements as private. Now to access this data or for modification, we have a special method known as getter setter respectively."
},
{
"code": null,
"e": 6046,
"s": 5625,
"text": "Getter is used to accessing the private data and setter is used to modify the private data only after authentication. In simple terms, it is hiding internal data from outside users. It is used as security such that no internal data will be accessed without authentication. An unauthorized end user will not get access to internal data. Programmatically we can implement data hiding by declaring data elements as private."
},
{
"code": null,
"e": 6273,
"s": 6048,
"text": "Now to access this data or for modification, we have a special method known as getter setter respectively. Getter is used to accessing the private data and setter is used to modify the private data only after authentication."
},
{
"code": null,
"e": 6306,
"s": 6275,
"text": "Implementation of Data Hiding:"
},
{
"code": null,
"e": 6313,
"s": 6308,
"text": "Java"
},
{
"code": "// Java Program showing working of data hiding // Importing generic librariesimport java.io.*; // Class created named Bankclass Bank { // Private data (data hiding) private long CurBalance = 0; // Bank_id is checked for authentication long bank_id; String name; // Getter function to modify private data public long get_balance(long Id) { // Checking whether the user is // authorised or unauthorised // Comparing bank_id of user and the give Id // then only it will get access if (this.bank_id == Id) { // Return current balance return CurBalance; } // Unauthorised user return -1; } // Setter function public void set_balance(long balance, long Id) { // Comparing bank_id of user and the give Id // then only it will get access if (this.bank_id == Id) { // Update balance in current ID CurBalance = CurBalance + balance; } }} // Another class created- Employeepublic class Emp { public static void main(String[] args) { // Creating employee object of bank type Bank _emp = new Bank(); // Assigning employee object values _emp.bank_id = 12345; _emp.name = \"Roshan\"; // _emp.get_balance(123456) _emp.set_balance(10000, 12345); // This will no get access as bank_id is given wrong // so // unauthorised user is not getting access that is // data hiding long emp_balance = _emp.get_balance(12345); // As this time it is valid user it will get access // Display commands System.out.println(\"User Name\" + \" \" + _emp.name); System.out.println(\"Bank_ID\" + \" \" + _emp.bank_id); System.out.println(\"Current Balance\" + \" \" + emp_balance); }}",
"e": 8233,
"s": 6313,
"text": null
},
{
"code": null,
"e": 8244,
"s": 8236,
"text": "Output:"
},
{
"code": null,
"e": 8299,
"s": 8246,
"text": "User Name Roshan\nBank_ID 12345\nCurrent Balance 10000"
},
{
"code": null,
"e": 8317,
"s": 8301,
"text": "simranarora5sos"
},
{
"code": null,
"e": 8338,
"s": 8317,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 8343,
"s": 8338,
"text": "Java"
},
{
"code": null,
"e": 8348,
"s": 8343,
"text": "Java"
},
{
"code": null,
"e": 8446,
"s": 8348,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8461,
"s": 8446,
"text": "Stream In Java"
},
{
"code": null,
"e": 8482,
"s": 8461,
"text": "Introduction to Java"
},
{
"code": null,
"e": 8503,
"s": 8482,
"text": "Constructors in Java"
},
{
"code": null,
"e": 8522,
"s": 8503,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 8539,
"s": 8522,
"text": "Generics in Java"
},
{
"code": null,
"e": 8569,
"s": 8539,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 8595,
"s": 8569,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 8611,
"s": 8595,
"text": "Strings in Java"
},
{
"code": null,
"e": 8648,
"s": 8611,
"text": "Differences between JDK, JRE and JVM"
}
] |
How to use HTML in Tkinter – Python? | 31 Aug, 2021
Prerequisite: Tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
In this article, we will learn, How we can use HTML tags in Tkinter. Here we will use the tkhtmlview Module.
The tkhtmlview module is a collection of Tkinter widgets whose text can be set in HTML format. An HTML widget isn’t a web browser frame, it’s only a simple and lightweight HTML parser that formats the tags used by the Tkinter Text base class.
Installation
pip install tkhtmlview
List of HTML Tags supports in tkhtmlview:
a
b
br
code
div
em
h1, h2, h3, h4, h5, h6
i
img
li, ul, ol
mark
p
pre
span
strong
u
We will use HTMLLabel() class for writing HTML tags
HTMLLabel(): Text-box widget with label appearance
Syntax:
HTMLLabel(Object Name, html="ENTER HTML CODE")
Below are some examples to depict how to use HTML in Tkinter GUI.
Example 1: Use heading tags.
Python3
# Import Modulefrom tkinter import *from tkhtmlview import HTMLLabel # Create Objectroot = Tk() # Set Geometryroot.geometry("400x400") # Add labelmy_label = HTMLLabel(root, html=""" <h1>GEEKSFORGEEKS</h1> <h2>GEEKSFORGEEKS</h2> <h3>GEEKSFORGEEKS</h3> <h4>GEEKSFORGEEKS</h4> <h5>GEEKSFORGEEKS</h5> <h6>GEEKSFORGEEKS</h6> """) # Adjust labelmy_label.pack(pady=20, padx=20) # Execute Tkinterroot.mainloop()
Output:
Example 2: Use anchor, paragraph & image tags
Python3
# Import Modulefrom tkinter import *from tkhtmlview import HTMLLabel # Create Objectroot = Tk() # Set Geometryroot.geometry("400x400") # Add labelmy_label = HTMLLabel(root, html=""" <a href='https://www.geeksforgeeks.org/'>GEEKSFORGEEKS</a> <p>Free Tutorials, Millions of Articles, Live, Online and Classroom Courses ,Frequent Coding Competitions ,Webinars by Industry Experts, Internship opportunities and Job Opportunities.</p> <img src="gfg.png"> """) # Adjust labelmy_label.pack(pady=20, padx=20) # Execute Tkinterroot.mainloop()
Output:
Example 3: Use list tag and add a link to each tag
Python3
# Import Modulefrom tkinter import *from tkhtmlview import HTMLLabel # Create Objectroot = Tk() # Set Geometryroot.geometry("400x400") # Add labelmy_label = HTMLLabel(root, html=""" <ul> <li><a href='https://www.geeksforgeeks.org/python-programming-language/'>Python</a></li> <li><a href='https://www.geeksforgeeks.org/c-plus-plus/'>C++</a></li> <li><a href='https://www.geeksforgeeks.org/java/'>Java</a></li> </ul> """) # Adjust labelmy_label.pack(pady=20, padx=20) # Execute Tkinterroot.mainloop()
Output:
Similarly, we can use all other tags.
rs1686740
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 74,
"s": 52,
"text": "Prerequisite: Tkinter"
},
{
"code": null,
"e": 424,
"s": 74,
"text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task."
},
{
"code": null,
"e": 533,
"s": 424,
"text": "In this article, we will learn, How we can use HTML tags in Tkinter. Here we will use the tkhtmlview Module."
},
{
"code": null,
"e": 776,
"s": 533,
"text": "The tkhtmlview module is a collection of Tkinter widgets whose text can be set in HTML format. An HTML widget isn’t a web browser frame, it’s only a simple and lightweight HTML parser that formats the tags used by the Tkinter Text base class."
},
{
"code": null,
"e": 789,
"s": 776,
"text": "Installation"
},
{
"code": null,
"e": 812,
"s": 789,
"text": "pip install tkhtmlview"
},
{
"code": null,
"e": 854,
"s": 812,
"text": "List of HTML Tags supports in tkhtmlview:"
},
{
"code": null,
"e": 856,
"s": 854,
"text": "a"
},
{
"code": null,
"e": 858,
"s": 856,
"text": "b"
},
{
"code": null,
"e": 861,
"s": 858,
"text": "br"
},
{
"code": null,
"e": 866,
"s": 861,
"text": "code"
},
{
"code": null,
"e": 870,
"s": 866,
"text": "div"
},
{
"code": null,
"e": 873,
"s": 870,
"text": "em"
},
{
"code": null,
"e": 896,
"s": 873,
"text": "h1, h2, h3, h4, h5, h6"
},
{
"code": null,
"e": 898,
"s": 896,
"text": "i"
},
{
"code": null,
"e": 902,
"s": 898,
"text": "img"
},
{
"code": null,
"e": 913,
"s": 902,
"text": "li, ul, ol"
},
{
"code": null,
"e": 918,
"s": 913,
"text": "mark"
},
{
"code": null,
"e": 920,
"s": 918,
"text": "p"
},
{
"code": null,
"e": 924,
"s": 920,
"text": "pre"
},
{
"code": null,
"e": 929,
"s": 924,
"text": "span"
},
{
"code": null,
"e": 936,
"s": 929,
"text": "strong"
},
{
"code": null,
"e": 938,
"s": 936,
"text": "u"
},
{
"code": null,
"e": 990,
"s": 938,
"text": "We will use HTMLLabel() class for writing HTML tags"
},
{
"code": null,
"e": 1041,
"s": 990,
"text": "HTMLLabel(): Text-box widget with label appearance"
},
{
"code": null,
"e": 1049,
"s": 1041,
"text": "Syntax:"
},
{
"code": null,
"e": 1096,
"s": 1049,
"text": "HTMLLabel(Object Name, html=\"ENTER HTML CODE\")"
},
{
"code": null,
"e": 1162,
"s": 1096,
"text": "Below are some examples to depict how to use HTML in Tkinter GUI."
},
{
"code": null,
"e": 1191,
"s": 1162,
"text": "Example 1: Use heading tags."
},
{
"code": null,
"e": 1199,
"s": 1191,
"text": "Python3"
},
{
"code": "# Import Modulefrom tkinter import *from tkhtmlview import HTMLLabel # Create Objectroot = Tk() # Set Geometryroot.geometry(\"400x400\") # Add labelmy_label = HTMLLabel(root, html=\"\"\" <h1>GEEKSFORGEEKS</h1> <h2>GEEKSFORGEEKS</h2> <h3>GEEKSFORGEEKS</h3> <h4>GEEKSFORGEEKS</h4> <h5>GEEKSFORGEEKS</h5> <h6>GEEKSFORGEEKS</h6> \"\"\") # Adjust labelmy_label.pack(pady=20, padx=20) # Execute Tkinterroot.mainloop()",
"e": 1648,
"s": 1199,
"text": null
},
{
"code": null,
"e": 1656,
"s": 1648,
"text": "Output:"
},
{
"code": null,
"e": 1702,
"s": 1656,
"text": "Example 2: Use anchor, paragraph & image tags"
},
{
"code": null,
"e": 1710,
"s": 1702,
"text": "Python3"
},
{
"code": "# Import Modulefrom tkinter import *from tkhtmlview import HTMLLabel # Create Objectroot = Tk() # Set Geometryroot.geometry(\"400x400\") # Add labelmy_label = HTMLLabel(root, html=\"\"\" <a href='https://www.geeksforgeeks.org/'>GEEKSFORGEEKS</a> <p>Free Tutorials, Millions of Articles, Live, Online and Classroom Courses ,Frequent Coding Competitions ,Webinars by Industry Experts, Internship opportunities and Job Opportunities.</p> <img src=\"gfg.png\"> \"\"\") # Adjust labelmy_label.pack(pady=20, padx=20) # Execute Tkinterroot.mainloop()",
"e": 2260,
"s": 1710,
"text": null
},
{
"code": null,
"e": 2268,
"s": 2260,
"text": "Output:"
},
{
"code": null,
"e": 2321,
"s": 2270,
"text": "Example 3: Use list tag and add a link to each tag"
},
{
"code": null,
"e": 2329,
"s": 2321,
"text": "Python3"
},
{
"code": "# Import Modulefrom tkinter import *from tkhtmlview import HTMLLabel # Create Objectroot = Tk() # Set Geometryroot.geometry(\"400x400\") # Add labelmy_label = HTMLLabel(root, html=\"\"\" <ul> <li><a href='https://www.geeksforgeeks.org/python-programming-language/'>Python</a></li> <li><a href='https://www.geeksforgeeks.org/c-plus-plus/'>C++</a></li> <li><a href='https://www.geeksforgeeks.org/java/'>Java</a></li> </ul> \"\"\") # Adjust labelmy_label.pack(pady=20, padx=20) # Execute Tkinterroot.mainloop()",
"e": 2859,
"s": 2329,
"text": null
},
{
"code": null,
"e": 2867,
"s": 2859,
"text": "Output:"
},
{
"code": null,
"e": 2905,
"s": 2867,
"text": "Similarly, we can use all other tags."
},
{
"code": null,
"e": 2915,
"s": 2905,
"text": "rs1686740"
},
{
"code": null,
"e": 2940,
"s": 2915,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 2955,
"s": 2940,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2962,
"s": 2955,
"text": "Python"
},
{
"code": null,
"e": 3060,
"s": 2962,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3092,
"s": 3060,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3119,
"s": 3092,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3150,
"s": 3119,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3173,
"s": 3150,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3194,
"s": 3173,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3250,
"s": 3194,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3292,
"s": 3250,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3334,
"s": 3292,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3373,
"s": 3334,
"text": "Python | Get unique values from a list"
}
] |
median() function in Python statistics module | 27 Sep, 2021
Python is a very popular language when it comes to data analysis and statistics. Luckily, Python3 provide statistics module, which comes with very useful functions like mean(), median(), mode() etc.median() function in the statistics module can be used to calculate median value from an unsorted data-list. The biggest advantage of using median() function is that the data-list does not need to be sorted before being sent as parameter to the median() function.Median is the value that separates the higher half of a data sample or probability distribution from the lower half. For a dataset, it may be thought of as the middle value. The median is the measure of the central tendency of the properties of a data-set in statistics and probability theory. Median has a very big advantage over Mean, which is the median value is not skewed so much by extremely large or small values. The median value is either contained in the data-set of values provided or it doesn’t sway too much from the data provided.For odd set of elements, the median value is the middle one. For even set of elements, the median value is the mean of two middle elements.
Median can be represented by the following formula :
Syntax : median( [data-set] )Parameters : [data-set] : List or tuple or an iterable with a set of numeric valuesReturns : Return the median (middle value) of the iterable containing the dataExceptions : StatisticsError is raised when iterable passed is empty or when list is null.
Code #1 : Working
Python3
# Python code to demonstrate the # working of median() function. # importing statistics moduleimport statistics # unsorted list of random integersdata1 = [2, -2, 3, 6, 9, 4, 5, -1] # Printing median of the# random data-setprint("Median of data-set is : % s " % (statistics.median(data1)))
Output :
Median of data-set is : 3.5
Code #2 :
Python3
# Python code to demonstrate the# working of median() on various# range of data-sets # importing the statistics modulefrom statistics import median # Importing fractions module as frfrom fractions import Fraction as fr # tuple of positive integer numbersdata1 = (2, 3, 4, 5, 7, 9, 11) # tuple of floating point valuesdata2 = (2.4, 5.1, 6.7, 8.9) # tuple of fractional numbersdata3 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3)) # tuple of a set of negative integersdata4 = (-5, -1, -12, -19, -3) # tuple of set of positive# and negative integersdata5 = (-1, -2, -3, -4, 4, 3, 2, 1) # Printing the median of above datasetsprint("Median of data-set 1 is % s" % (median(data1)))print("Median of data-set 2 is % s" % (median(data2)))print("Median of data-set 3 is % s" % (median(data3)))print("Median of data-set 4 is % s" % (median(data4)))print("Median of data-set 5 is % s" % (median(data5)))
Output :
Median of data-set 1 is 5
Median of data-set 2 is 5.9
Median of data-set 3 is 2
Median of data-set 4 is -5
Median of data-set 5 is 0.0
Code #3 : Demonstrating StatisticsError
Python3
# Python code to demonstrate# StatisticsError of median() # importing the statistics modulefrom statistics import median # creating an empty data-setempty = [] # will raise StatisticsErrorprint(median(empty))
Output :
Traceback (most recent call last):
File "/home/3c98774036f97845ee9f65f6d3571e49.py", line 12, in
print(median(empty))
File "/usr/lib/python3.5/statistics.py", line 353, in median
raise StatisticsError("no median for empty data")
statistics.StatisticsError: no median for empty data
Applications : For practical applications, different measures of dispersion and population tendency are compared on the basis of how well the corresponding population values can be estimated. For example, a comparison shows that the sample mean is more statistically efficient than the sample median when the data is uncontaminated by data from heavily-tailed data distribution or from mixtures of data distribution, but less efficient otherwise and that the efficiency of the sample median is higher than that for a wide range of distributions. To be more specific, the median has 64% efficiency compared to minimum-variance-mean ( for large normal samples ).
sumitgumber28
python-modules
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 1174,
"s": 28,
"text": "Python is a very popular language when it comes to data analysis and statistics. Luckily, Python3 provide statistics module, which comes with very useful functions like mean(), median(), mode() etc.median() function in the statistics module can be used to calculate median value from an unsorted data-list. The biggest advantage of using median() function is that the data-list does not need to be sorted before being sent as parameter to the median() function.Median is the value that separates the higher half of a data sample or probability distribution from the lower half. For a dataset, it may be thought of as the middle value. The median is the measure of the central tendency of the properties of a data-set in statistics and probability theory. Median has a very big advantage over Mean, which is the median value is not skewed so much by extremely large or small values. The median value is either contained in the data-set of values provided or it doesn’t sway too much from the data provided.For odd set of elements, the median value is the middle one. For even set of elements, the median value is the mean of two middle elements. "
},
{
"code": null,
"e": 1229,
"s": 1174,
"text": "Median can be represented by the following formula :\n\n"
},
{
"code": null,
"e": 1516,
"s": 1233,
"text": "Syntax : median( [data-set] )Parameters : [data-set] : List or tuple or an iterable with a set of numeric valuesReturns : Return the median (middle value) of the iterable containing the dataExceptions : StatisticsError is raised when iterable passed is empty or when list is null. "
},
{
"code": null,
"e": 1535,
"s": 1516,
"text": "Code #1 : Working "
},
{
"code": null,
"e": 1543,
"s": 1535,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the # working of median() function. # importing statistics moduleimport statistics # unsorted list of random integersdata1 = [2, -2, 3, 6, 9, 4, 5, -1] # Printing median of the# random data-setprint(\"Median of data-set is : % s \" % (statistics.median(data1)))",
"e": 1840,
"s": 1543,
"text": null
},
{
"code": null,
"e": 1851,
"s": 1840,
"text": "Output : "
},
{
"code": null,
"e": 1880,
"s": 1851,
"text": "Median of data-set is : 3.5 "
},
{
"code": null,
"e": 1894,
"s": 1880,
"text": " Code #2 : "
},
{
"code": null,
"e": 1902,
"s": 1894,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the# working of median() on various# range of data-sets # importing the statistics modulefrom statistics import median # Importing fractions module as frfrom fractions import Fraction as fr # tuple of positive integer numbersdata1 = (2, 3, 4, 5, 7, 9, 11) # tuple of floating point valuesdata2 = (2.4, 5.1, 6.7, 8.9) # tuple of fractional numbersdata3 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3)) # tuple of a set of negative integersdata4 = (-5, -1, -12, -19, -3) # tuple of set of positive# and negative integersdata5 = (-1, -2, -3, -4, 4, 3, 2, 1) # Printing the median of above datasetsprint(\"Median of data-set 1 is % s\" % (median(data1)))print(\"Median of data-set 2 is % s\" % (median(data2)))print(\"Median of data-set 3 is % s\" % (median(data3)))print(\"Median of data-set 4 is % s\" % (median(data4)))print(\"Median of data-set 5 is % s\" % (median(data5)))",
"e": 2802,
"s": 1902,
"text": null
},
{
"code": null,
"e": 2813,
"s": 2802,
"text": "Output : "
},
{
"code": null,
"e": 2948,
"s": 2813,
"text": "Median of data-set 1 is 5\nMedian of data-set 2 is 5.9\nMedian of data-set 3 is 2\nMedian of data-set 4 is -5\nMedian of data-set 5 is 0.0"
},
{
"code": null,
"e": 2992,
"s": 2948,
"text": " Code #3 : Demonstrating StatisticsError "
},
{
"code": null,
"e": 3000,
"s": 2992,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# StatisticsError of median() # importing the statistics modulefrom statistics import median # creating an empty data-setempty = [] # will raise StatisticsErrorprint(median(empty))",
"e": 3209,
"s": 3000,
"text": null
},
{
"code": null,
"e": 3220,
"s": 3209,
"text": "Output : "
},
{
"code": null,
"e": 3515,
"s": 3220,
"text": "Traceback (most recent call last):\n File \"/home/3c98774036f97845ee9f65f6d3571e49.py\", line 12, in \n print(median(empty))\n File \"/usr/lib/python3.5/statistics.py\", line 353, in median\n raise StatisticsError(\"no median for empty data\")\nstatistics.StatisticsError: no median for empty data"
},
{
"code": null,
"e": 4179,
"s": 3515,
"text": " Applications : For practical applications, different measures of dispersion and population tendency are compared on the basis of how well the corresponding population values can be estimated. For example, a comparison shows that the sample mean is more statistically efficient than the sample median when the data is uncontaminated by data from heavily-tailed data distribution or from mixtures of data distribution, but less efficient otherwise and that the efficiency of the sample median is higher than that for a wide range of distributions. To be more specific, the median has 64% efficiency compared to minimum-variance-mean ( for large normal samples ). "
},
{
"code": null,
"e": 4193,
"s": 4179,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4208,
"s": 4193,
"text": "python-modules"
},
{
"code": null,
"e": 4215,
"s": 4208,
"text": "Python"
},
{
"code": null,
"e": 4231,
"s": 4215,
"text": "Python Programs"
}
] |
Install Tensorflow on MacOS | 23 May, 2021
TensorFlow is an open-source software library developed by the Google brain team. It widely used to implement deep learning models which helps in solving real world problems. In this article, we learn how to install TensorFlow on macOS using Homebrew.
Requirements:
Python 3.6–3.8macOS 10.12.6 (Sierra) or later (no GPU support)
Python 3.6–3.8
macOS 10.12.6 (Sierra) or later (no GPU support)
Step 1: Verify the python version:
$ python3 --version
Step 2: Verify if the brew is installed:
$ brew --version
Step 3: Create the virtual environment:
$ brew install virtualenv
Step 4: After creating a new virtual environment, create a ./pythonenv directory to hold it.
$ virtualenv --system-site-packages -p python3 ./pythonenv
Step 5: Go inside ./pythonenv
$ cd ./pythonenv
Step 6: Activate the virtual environment
source bin/activate
Step 7: Install TensorFlow.
brew install tensorflow
Step 8: Create a new folder inside /pythonenv called tfdemo. Create a new file inside tfdemo called tfdemofile.py.
Step 9: Run the file:
$ python3 tfdemofile.py
Python3
# importing tensorflowimport tensorflow as tf # creating nodes in computation graphnode1 = tf.constant(3, dtype = tf.int32)node2 = tf.constant(5, dtype = tf.int32)node3 = tf.add(node1, node2) # create tensorflow session objectsess = tf.Session() # evaluating node3 and printing the resultprint("Sum of node1 and node2 is:", sess.run(node3)) # closing the sessionsess.close()
Output:
Picked
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 306,
"s": 54,
"text": "TensorFlow is an open-source software library developed by the Google brain team. It widely used to implement deep learning models which helps in solving real world problems. In this article, we learn how to install TensorFlow on macOS using Homebrew."
},
{
"code": null,
"e": 320,
"s": 306,
"text": "Requirements:"
},
{
"code": null,
"e": 383,
"s": 320,
"text": "Python 3.6–3.8macOS 10.12.6 (Sierra) or later (no GPU support)"
},
{
"code": null,
"e": 398,
"s": 383,
"text": "Python 3.6–3.8"
},
{
"code": null,
"e": 447,
"s": 398,
"text": "macOS 10.12.6 (Sierra) or later (no GPU support)"
},
{
"code": null,
"e": 482,
"s": 447,
"text": "Step 1: Verify the python version:"
},
{
"code": null,
"e": 502,
"s": 482,
"text": "$ python3 --version"
},
{
"code": null,
"e": 543,
"s": 502,
"text": "Step 2: Verify if the brew is installed:"
},
{
"code": null,
"e": 560,
"s": 543,
"text": "$ brew --version"
},
{
"code": null,
"e": 600,
"s": 560,
"text": "Step 3: Create the virtual environment:"
},
{
"code": null,
"e": 626,
"s": 600,
"text": "$ brew install virtualenv"
},
{
"code": null,
"e": 720,
"s": 626,
"text": "Step 4: After creating a new virtual environment, create a ./pythonenv directory to hold it."
},
{
"code": null,
"e": 779,
"s": 720,
"text": "$ virtualenv --system-site-packages -p python3 ./pythonenv"
},
{
"code": null,
"e": 809,
"s": 779,
"text": "Step 5: Go inside ./pythonenv"
},
{
"code": null,
"e": 826,
"s": 809,
"text": "$ cd ./pythonenv"
},
{
"code": null,
"e": 867,
"s": 826,
"text": "Step 6: Activate the virtual environment"
},
{
"code": null,
"e": 887,
"s": 867,
"text": "source bin/activate"
},
{
"code": null,
"e": 915,
"s": 887,
"text": "Step 7: Install TensorFlow."
},
{
"code": null,
"e": 939,
"s": 915,
"text": "brew install tensorflow"
},
{
"code": null,
"e": 1054,
"s": 939,
"text": "Step 8: Create a new folder inside /pythonenv called tfdemo. Create a new file inside tfdemo called tfdemofile.py."
},
{
"code": null,
"e": 1076,
"s": 1054,
"text": "Step 9: Run the file:"
},
{
"code": null,
"e": 1100,
"s": 1076,
"text": "$ python3 tfdemofile.py"
},
{
"code": null,
"e": 1108,
"s": 1100,
"text": "Python3"
},
{
"code": "# importing tensorflowimport tensorflow as tf # creating nodes in computation graphnode1 = tf.constant(3, dtype = tf.int32)node2 = tf.constant(5, dtype = tf.int32)node3 = tf.add(node1, node2) # create tensorflow session objectsess = tf.Session() # evaluating node3 and printing the resultprint(\"Sum of node1 and node2 is:\", sess.run(node3)) # closing the sessionsess.close()",
"e": 1495,
"s": 1108,
"text": null
},
{
"code": null,
"e": 1503,
"s": 1495,
"text": "Output:"
},
{
"code": null,
"e": 1510,
"s": 1503,
"text": "Picked"
},
{
"code": null,
"e": 1528,
"s": 1510,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 1535,
"s": 1528,
"text": "Python"
},
{
"code": null,
"e": 1633,
"s": 1535,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1665,
"s": 1633,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1692,
"s": 1665,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1713,
"s": 1692,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1736,
"s": 1713,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1792,
"s": 1736,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1823,
"s": 1792,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1865,
"s": 1823,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1907,
"s": 1865,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1946,
"s": 1907,
"text": "Python | Get unique values from a list"
}
] |
ES6 - switchâ¦case Statement | The switch statement evaluates an expression, matches the expression’s value to a case clause and executes the statements associated with that case.
Following is the syntax.
switch(variable_expression) {
case constant_expr1: {
//statements;
break;
}
case constant_expr2: {
//statements;
break;
}
default: {
//statements;
break;
}
}
The value of the variable_expression is tested against all cases in the switch. If the variable matches one of the cases, the corresponding code block is executed. If no case expression matches the value of the variable_expression, the code within the default block is associated.
The following rules apply to a switch statement −
There can be any number of case statements within a switch.
The case statements can include only constants. It cannot be a variable or an expression.
The data type of the variable_expression and the constant expression must match.
Unless you put a break after each block of code, the execution flows into the next block.
The case expression must be unique.
The default block is optional.
var grade="A";
switch(grade) {
case "A": {
console.log("Excellent");
break;
}
case "B": {
console.log("Good");
break;
}
case "C": {
console.log("Fair");
break;
}
case "D": {
console.log("Poor");
break;
}
default: {
console.log("Invalid choice");
break;
}
}
The following output is displayed on successful execution on the above code.
Excellent
The example verifies the value of the variable grade against the set of constants (A, B, C, D, and E) and executes the corresponding blocks. If the value in the variable doesn’t match any of the constants mentioned above, the default block will be executed. | [
{
"code": null,
"e": 2560,
"s": 2411,
"text": "The switch statement evaluates an expression, matches the expression’s value to a case clause and executes the statements associated with that case."
},
{
"code": null,
"e": 2585,
"s": 2560,
"text": "Following is the syntax."
},
{
"code": null,
"e": 2798,
"s": 2585,
"text": "switch(variable_expression) {\n case constant_expr1: {\n //statements;\n break;\n }\n case constant_expr2: {\n //statements;\n break;\n }\n default: {\n //statements;\n break;\n }\n}\n"
},
{
"code": null,
"e": 3079,
"s": 2798,
"text": "The value of the variable_expression is tested against all cases in the switch. If the variable matches one of the cases, the corresponding code block is executed. If no case expression matches the value of the variable_expression, the code within the default block is associated."
},
{
"code": null,
"e": 3129,
"s": 3079,
"text": "The following rules apply to a switch statement −"
},
{
"code": null,
"e": 3189,
"s": 3129,
"text": "There can be any number of case statements within a switch."
},
{
"code": null,
"e": 3279,
"s": 3189,
"text": "The case statements can include only constants. It cannot be a variable or an expression."
},
{
"code": null,
"e": 3360,
"s": 3279,
"text": "The data type of the variable_expression and the constant expression must match."
},
{
"code": null,
"e": 3450,
"s": 3360,
"text": "Unless you put a break after each block of code, the execution flows into the next block."
},
{
"code": null,
"e": 3486,
"s": 3450,
"text": "The case expression must be unique."
},
{
"code": null,
"e": 3517,
"s": 3486,
"text": "The default block is optional."
},
{
"code": null,
"e": 3864,
"s": 3517,
"text": "var grade=\"A\";\nswitch(grade) {\n case \"A\": {\n console.log(\"Excellent\");\n break;\n }\n case \"B\": {\n console.log(\"Good\");\n break;\n }\n case \"C\": {\n console.log(\"Fair\");\n break;\n }\n case \"D\": {\n console.log(\"Poor\");\n break;\n }\n default: {\n console.log(\"Invalid choice\");\n break;\n }\n}"
},
{
"code": null,
"e": 3941,
"s": 3864,
"text": "The following output is displayed on successful execution on the above code."
},
{
"code": null,
"e": 3952,
"s": 3941,
"text": "Excellent\n"
}
] |
Python | Split Sublist Strings | 01 May, 2019
Yet another variation of splitting strings is splitting the strings that are an element of the sublist. This is quite peculiar problem, but one can get the data in this format and knowledge of splitting it anyways quite useful. Let’s discuss certain ways in which this particular task can be performed.
Method #1 : Using list comprehension + split()
This method is the shorthand version of the longer loop version that one could choose to solve this particular problem. We just split the strings fetching the sublist using the loop in list comprehension using split function.
# Python3 code to demonstrate# Split Sublist Strings# using split() + list comprehension # initializing listtest_list = [['GfG is best'], ['All love Gfg'], ['Including me']] # printing original listprint("The original list : " + str(test_list)) # using split() + list comprehension# Split Sublist Stringsres = [sub.split() for subl in test_list for sub in subl] # print resultprint("The list after splitting strings : " + str(res))
The original list : [[‘GfG is best’], [‘All love Gfg’], [‘Including me’]]The list after splitting strings : [[‘GfG’, ‘is’, ‘best’], [‘All’, ‘love’, ‘Gfg’], [‘Including’, ‘me’]]
Method #2 : Using map() + lambda + split()
This task can also be performed using the combination of above 3 functions. The map function binds the splitting logic to each element which is written using the lambda function that uses split function to perform the split.
# Python3 code to demonstrate# Split Sublist Strings# using map() + lambda + split() # initializing listtest_list = [['GfG is best'], ['All love Gfg'], ['Including me']] # printing original listprint("The original list : " + str(test_list)) # using map() + lambda + split()# Split Sublist Stringsres = list(map(lambda sub: sub[0].split(' '), test_list)) # print resultprint("The list after splitting strings : " + str(res))
The original list : [[‘GfG is best’], [‘All love Gfg’], [‘Including me’]]The list after splitting strings : [[‘GfG’, ‘is’, ‘best’], [‘All’, ‘love’, ‘Gfg’], [‘Including’, ‘me’]]
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 May, 2019"
},
{
"code": null,
"e": 331,
"s": 28,
"text": "Yet another variation of splitting strings is splitting the strings that are an element of the sublist. This is quite peculiar problem, but one can get the data in this format and knowledge of splitting it anyways quite useful. Let’s discuss certain ways in which this particular task can be performed."
},
{
"code": null,
"e": 378,
"s": 331,
"text": "Method #1 : Using list comprehension + split()"
},
{
"code": null,
"e": 604,
"s": 378,
"text": "This method is the shorthand version of the longer loop version that one could choose to solve this particular problem. We just split the strings fetching the sublist using the loop in list comprehension using split function."
},
{
"code": "# Python3 code to demonstrate# Split Sublist Strings# using split() + list comprehension # initializing listtest_list = [['GfG is best'], ['All love Gfg'], ['Including me']] # printing original listprint(\"The original list : \" + str(test_list)) # using split() + list comprehension# Split Sublist Stringsres = [sub.split() for subl in test_list for sub in subl] # print resultprint(\"The list after splitting strings : \" + str(res))",
"e": 1040,
"s": 604,
"text": null
},
{
"code": null,
"e": 1217,
"s": 1040,
"text": "The original list : [[‘GfG is best’], [‘All love Gfg’], [‘Including me’]]The list after splitting strings : [[‘GfG’, ‘is’, ‘best’], [‘All’, ‘love’, ‘Gfg’], [‘Including’, ‘me’]]"
},
{
"code": null,
"e": 1262,
"s": 1219,
"text": "Method #2 : Using map() + lambda + split()"
},
{
"code": null,
"e": 1487,
"s": 1262,
"text": "This task can also be performed using the combination of above 3 functions. The map function binds the splitting logic to each element which is written using the lambda function that uses split function to perform the split."
},
{
"code": "# Python3 code to demonstrate# Split Sublist Strings# using map() + lambda + split() # initializing listtest_list = [['GfG is best'], ['All love Gfg'], ['Including me']] # printing original listprint(\"The original list : \" + str(test_list)) # using map() + lambda + split()# Split Sublist Stringsres = list(map(lambda sub: sub[0].split(' '), test_list)) # print resultprint(\"The list after splitting strings : \" + str(res))",
"e": 1915,
"s": 1487,
"text": null
},
{
"code": null,
"e": 2092,
"s": 1915,
"text": "The original list : [[‘GfG is best’], [‘All love Gfg’], [‘Including me’]]The list after splitting strings : [[‘GfG’, ‘is’, ‘best’], [‘All’, ‘love’, ‘Gfg’], [‘Including’, ‘me’]]"
},
{
"code": null,
"e": 2113,
"s": 2092,
"text": "Python list-programs"
},
{
"code": null,
"e": 2136,
"s": 2113,
"text": "Python string-programs"
},
{
"code": null,
"e": 2143,
"s": 2136,
"text": "Python"
},
{
"code": null,
"e": 2159,
"s": 2143,
"text": "Python Programs"
},
{
"code": null,
"e": 2257,
"s": 2159,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2289,
"s": 2257,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2316,
"s": 2289,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2347,
"s": 2316,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2370,
"s": 2347,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2391,
"s": 2370,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2413,
"s": 2391,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2452,
"s": 2413,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2490,
"s": 2452,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2539,
"s": 2490,
"text": "Python | Convert string dictionary to dictionary"
}
] |
turtle.Screen().turtles() function in Python | 27 Aug, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to return the list of turtles on the screen. This doesn’t require any argument.
Syntax :
turtle.Screen().turtles()
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # make screen object# and set sizesc = turtle.Screen()sc.setup(400,300) # make turtle objectt1=turtle.Turtle(shape='square') # do some motion with propertiest1.color("red")t1.circle(50) # make another turtle objectt2=turtle.Turtle(shape='circle') # do some motion with propertiest2.color("green")t2.circle(40) # get all turtle objects on screenprint(sc.turtles())
Output :
[<turtle.Turtle object at 0x000001E90622DAC8>, <turtle.Turtle object at 0x000001E90625CC88>]
Example 2 :
Python3
# import packageimport turtle # make screen object and set sizesc = turtle.Screen()sc.setup(400, 300) # make first turtle and do somethingt1 = turtle.Turtle(shape='square')t1.color("red")t1.circle(50) # make another turtle and do somethingt2 = turtle.Turtle(shape='circle')t2.color("green")t2.circle(40) # get all turtles objectturt = sc.turtles() # use first turtle objectturt[0].circle(-40) # use another turtle objectturt[1].circle(-50)
Output :
surindertarika1234
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 270,
"s": 53,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 372,
"s": 270,
"text": "This function is used to return the list of turtles on the screen. This doesn’t require any argument."
},
{
"code": null,
"e": 381,
"s": 372,
"text": "Syntax :"
},
{
"code": null,
"e": 407,
"s": 381,
"text": "turtle.Screen().turtles()"
},
{
"code": null,
"e": 476,
"s": 407,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 488,
"s": 476,
"text": "Example 1 :"
},
{
"code": null,
"e": 496,
"s": 488,
"text": "Python3"
},
{
"code": "# import packageimport turtle # make screen object# and set sizesc = turtle.Screen()sc.setup(400,300) # make turtle objectt1=turtle.Turtle(shape='square') # do some motion with propertiest1.color(\"red\")t1.circle(50) # make another turtle objectt2=turtle.Turtle(shape='circle') # do some motion with propertiest2.color(\"green\")t2.circle(40) # get all turtle objects on screenprint(sc.turtles())",
"e": 890,
"s": 496,
"text": null
},
{
"code": null,
"e": 899,
"s": 890,
"text": "Output :"
},
{
"code": null,
"e": 994,
"s": 899,
"text": "[<turtle.Turtle object at 0x000001E90622DAC8>, <turtle.Turtle object at 0x000001E90625CC88>] "
},
{
"code": null,
"e": 1008,
"s": 996,
"text": "Example 2 :"
},
{
"code": null,
"e": 1016,
"s": 1008,
"text": "Python3"
},
{
"code": "# import packageimport turtle # make screen object and set sizesc = turtle.Screen()sc.setup(400, 300) # make first turtle and do somethingt1 = turtle.Turtle(shape='square')t1.color(\"red\")t1.circle(50) # make another turtle and do somethingt2 = turtle.Turtle(shape='circle')t2.color(\"green\")t2.circle(40) # get all turtles objectturt = sc.turtles() # use first turtle objectturt[0].circle(-40) # use another turtle objectturt[1].circle(-50)",
"e": 1456,
"s": 1016,
"text": null
},
{
"code": null,
"e": 1465,
"s": 1456,
"text": "Output :"
},
{
"code": null,
"e": 1484,
"s": 1465,
"text": "surindertarika1234"
},
{
"code": null,
"e": 1498,
"s": 1484,
"text": "Python-turtle"
},
{
"code": null,
"e": 1505,
"s": 1498,
"text": "Python"
},
{
"code": null,
"e": 1603,
"s": 1505,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1635,
"s": 1603,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1662,
"s": 1635,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1693,
"s": 1662,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1716,
"s": 1693,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1737,
"s": 1716,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1793,
"s": 1737,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1835,
"s": 1793,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1877,
"s": 1835,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1916,
"s": 1877,
"text": "Python | Get unique values from a list"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.