title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Data Cleaning, Detection and Imputation of Missing Values in R Markdown — Part 2 | by Wendy Wong | Towards Data Science | Data cleaning and transforming variables in R using Australian Tennis Open data on the Men’s tour from 2000 to 2018.
Today is Day 4 and marks the continuation of my #29dayproject bootcamp of data science and things I have learnt in data science. This is a tutorial guide of cleaning and pre-processing the tennis data from the Australian Open Tennis tournament from 2000 to 2019 to predict who might win using R. Yesterday we merged multiple csv files and subsetted the data you may follow here from the blog post.
If you take a class in Data Analytics at General Assembly, take a data science course at your university in data science algorithms, take an IT elective of interest, study an online course or you may work on a data mining project for your Professor you will come across the data mining principles of CRISP-DM.
CRISP-DM is the cross-industry process for data mining. It is also a prescribed analytics workflow I learnt at General Assembly Sydney and the principles are used in data science projects when you are consulting in government.
This the workflow of CRISP-DM methodology used to guide you through data analytics and data science problems.You may review each of the steps from Smart Vision Europe 2018.
This is not a business problem but the scope of the problem statement was to predict the winner of this year’s Australian Open Tennis Finals based on data from 2000 to 2018.
Previously we obtained a data dictionary and explored the data by analysing the overall structure of the data.
Here is the data dictionary of the variables:
ATP = Tournament number (men)WTA = Tournament number (women)Location = Venue of tournamentTournament = Name of tounament (including sponsor if relevant)Data = Date of match (note: prior to 2003 the date shown for all matches played in a single tournament is the start date)Series = Name of ATP tennis series (Grand Slam, Masters, International or International Gold)Tier = Tier (tournament ranking) of WTA tennis series.Court = Type of court (outdoors or indoors)Surface = Type of surface (clay, hard, carpet or grass)Round = Round of matchBest of = Maximum number of sets playable in matchWinner = Match winnerLoser = Match loserWRank = ATP Entry ranking of the match winner as of the start of the tournamentLRank = ATP Entry ranking of the match loser as of the start of the tournamentWPts = ATP Entry points of the match winner as of the start of the tournamentLPts = ATP Entry points of the match loser as of the start of the tournamentW1 = Number of games won in 1st set by match winnerL1 = Number of games won in 1st set by match loserW2 = Number of games won in 2nd set by match winnerL2 = Number of games won in 2nd set by match loserW3 = Number of games won in 3rd set by match winnerL3 = Number of games won in 3rd set by match loserW4 = Number of games won in 4th set by match winnerL4 = Number of games won in 4th set by match loserW5 = Number of games won in 5th set by match winnerL5 = Number of games won in 5th set by match loserWsets = Number of sets won by match winnerLsets = Number of sets won by match loserComment = Comment on the match (Completed, won through retirement of loser, or via Walkover)
The data has been cleaned by the encoding of categorical variables, transforming variables and the detection of missing values. We have already merged the original data and the “aus_open.csv” dataframe is read into R using StringAsfactors =FALSE to ensure all the variables are not automatically read as a factor.
#################################### Pre-Processing the Training Data#################################### Exported aust_open.csv file was exported and a new column was created in Excel to extract the year from the data with non-standardised formattinga <- read.csv("aus_open.csv",stringsAsFactors = FALSE,header = TRUE)
Using Hadley Wickham’s dplyr package, I explored the structure of the data using the function glimpse().
############################## Exploratory Data Analysis#############################glimpse(a) # view the structure of the training data
The output of the descriptive statistics is provided below, a summary of all of the numeric variables and missing values.
summary(a) # descriptive statistics ATP Location Tournament Date Min. :6 Length:2413 Length:2413 Length:2413 1st Qu.:6 Class :character Class :character Class :character Median :6 Mode :character Mode :character Mode :character Mean :6 3rd Qu.:6 Max. :6 Year Series Court Surface Min. :2000 Length:2413 Length:2413 Length:2413 1st Qu.:2004 Class :character Class :character Class :character Median :2009 Mode :character Mode :character Mode :character Mean :2009 3rd Qu.:2014 Max. :2018 Round Best.of Winner Loser Length:2413 Min. :5 Length:2413 Length:2413 Class :character 1st Qu.:5 Class :character Class :character Mode :character Median :5 Mode :character Mode :character Mean :5 3rd Qu.:5 Max. :5 WRank LRank W1 L1 Min. : 1.00 Length:2413 Min. : 0 Length:2413 1st Qu.: 10.00 Class :character 1st Qu.: 7 Class :character Median : 28.00 Mode :character Median : 860 Mode :character Mean : 46.97 Mean : 1863 3rd Qu.: 65.00 3rd Qu.: 2145 Max. :768.00 Max. :16790 NA's :128 W2 L2 W3 L3 Min. :0.000 Min. :0.000 Min. :0.000 Min. :0.000 1st Qu.:6.000 1st Qu.:3.000 1st Qu.:6.000 1st Qu.:2.000 Median :6.000 Median :4.000 Median :6.000 Median :4.000 Mean :5.687 Mean :4.027 Mean :5.743 Mean :3.903 3rd Qu.:6.000 3rd Qu.:6.000 3rd Qu.:6.000 3rd Qu.:6.000 Max. :7.000 Max. :7.000 Max. :7.000 Max. :7.000 NA's :10 NA's :10 NA's :33 NA's :33 W4 L4 W5 L5 Min. :0.000 Min. :0.000 Min. : 0.000 Min. : 0.000 1st Qu.:6.000 1st Qu.:2.000 1st Qu.: 6.000 1st Qu.: 2.000 Median :6.000 Median :4.000 Median : 6.000 Median : 4.000 Mean :5.753 Mean :3.734 Mean : 5.883 Mean : 3.813 3rd Qu.:6.000 3rd Qu.:6.000 3rd Qu.: 6.000 3rd Qu.: 6.000 Max. :7.000 Max. :7.000 Max. :21.000 Max. :19.000 NA's :346 NA's :346 NA's :1440 NA's :1440 Wsets Lsets Comment Min. : 0.000 Min. : 0.0 Length:2413 1st Qu.: 3.000 1st Qu.: 0.0 Class :character Median : 3.000 Median : 1.0 Mode :character Mean : 4.192 Mean : 1.7 3rd Qu.: 6.000 3rd Qu.: 2.0 Max. :22.000 Max. :20.0 NA's :1444 NA's :1444
From the glimpse of the structure above, some of the data attributes were not cast in their correct data type. This is my favourite part the chance to transform the variables! Here we go...
# Transform character variables into numeric variables a$W1 <- as.numeric(a$W1)a$L1 <- as.numeric(a$L1)a$WRank <- as.numeric(a$WRank)a$LRank <- as.numeric(a$LRank)########################################################### encoding categorical features########################################################### Convert categorical variables into factors to represent their levelsa$Location <- factor(a$Location)a$Tournament <- factor(a$Tournament)a$Series <- factor(a$Series)a$Court <- factor(a$Court)a$Surface <- factor(a$Surface)a$Best.of <- factor(a$Best.of)a$Round <- factor(a$Round)a$Winner <- factor(a$Winner)a$Loser <- factor(a$Loser)a$Comment <- factor(a$Comment)glimpse(a) # check that structure of categorical variables have converted with levels
library(dummies)Round <- dummy(a$Round)Best.of <- dummy(a$Best.of)Winner <- dummy(a$Winner)Loser <- dummy(a$Loser)Comment <- dummy(a$Comment)head(a) # check that the values are been converted to dummy variablesstr(a)
# Descriptive statisticssummary(a)# View the structure of the transformed variables the 'dplyr' way > glimpse(a)Observations: 2,413Variables: 27$ ATP <int> 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...$ Location <fct> Melbourne, Melbourne, Melbourne, Melbourne, Melbourne,...$ Tournament <fct> Australian Open, Australian Open, Australian Open, Aus...$ Date <chr> "1/17/00", "1/17/00", "1/17/00", "1/17/00", "1/17/00",...$ Year <int> 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, ...$ Series <fct> Grand Slam, Grand Slam, Grand Slam, Grand Slam, Grand ...$ Court <fct> Outdoor, Outdoor, Outdoor, Outdoor, Outdoor, Outdoor, ...$ Surface <fct> Hard, Hard, Hard, Hard, Hard, Hard, Hard, Hard, Hard, ...$ Round <fct> 1st Round, 1st Round, 1st Round, 1st Round, 1st Round,...$ Best.of <fct> 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ...$ Winner <fct> Agassi A., Alami K., Arazi H., Behrend T., Bjorkman J....$ Loser <fct> Puerta M., Manta L., Alonso J., Meligeni F., Stoltenbe...$ WRank <dbl> 1, 35, 41, 106, 76, 151, 39, 54, 30, 64, 98, 29, 34, 6...$ LRank <dbl> 112, 107, 111, 28, 81, 57, 22, 66, 51, 155, 119, 257, ...$ W1 <dbl> 6, 6, 6, 6, 6, 7, 3, 7, 7, 7, 6, 6, 6, 6, 6, 7, 6, 6, ...$ L1 <dbl> 2, 4, 3, 2, 7, 6, 6, 6, 6, 6, 4, 7, 7, 4, 3, 6, 4, 3, ...$ W2 <int> 6, 7, 7, 4, 6, 6, 6, 6, 6, 5, 6, 7, 6, 6, 6, 6, 7, 6, ...$ L2 <int> 2, 6, 6, 6, 4, 1, 1, 4, 4, 7, 4, 6, 3, 4, 3, 3, 6, 3, ...$ W3 <int> 6, 7, 6, 6, 6, 6, 6, NA, 6, 6, 7, 1, 7, 7, 4, 7, 4, 6,...$ L3 <int> 3, 5, 2, 7, 4, 4, 4, NA, 4, 3, 6, 6, 5, 6, 6, 6, 6, 2,...$ W4 <int> NA, NA, NA, 6, 0, NA, 7, NA, NA, 7, NA, 6, 6, NA, 7, N...$ L4 <int> NA, NA, NA, 3, 6, NA, 6, NA, NA, 5, NA, 3, 1, NA, 6, N...$ W5 <int> NA, NA, NA, 6, 6, NA, NA, NA, NA, NA, NA, 6, NA, NA, N...$ L5 <int> NA, NA, NA, 0, 4, NA, NA, NA, NA, NA, NA, 1, NA, NA, N...$ Wsets <int> 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, ...$ Lsets <int> 0, 0, 0, 2, 2, 0, 1, 0, 0, 1, 0, 2, 1, 0, 1, 0, 2, 0, ...$ Comment <fct> Completed, Completed, Completed, Completed, Completed,...
We will try a few methods to detect the missing values such as counting the number of missing values per column, sum and taking the mean.
# Sum the number of missing values> sum(is.na(a)) [1] 6810# average of the missing values in each column> mean(is.na(a)) [1] 0.1045264# Count the number of missing values per column> colSums(is.na(a)) ATP Location Tournament Date Year Series Court 0 0 0 0 0 0 0 Surface Round Best.of Winner Loser WRank LRank 0 0 0 0 0 0 5 W1 L1 W2 L2 W3 L3 W4 128 131 10 10 33 33 346 L4 W5 L5 Wsets Lsets Comment 346 1440 1440 1444 1444 0
In detecting missing values 5% is the acceptable threshold for each column.The output confirms that the columns : L4, W4, L5,W5, Wsets and Lsets have missing values greater than 5% and can be removed or imputed.
sapply(a, function(df){ sum(is.na(df) ==TRUE)/length(df); }) ATP Location Tournament Date Year Series 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 Court Surface Round Best.of Winner Loser 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 WRank LRank W1 L1 W2 L2 0.000000000 0.002072109 0.053046001 0.054289266 0.004144219 0.004144219 W3 L3 W4 L4 W5 L5 0.013675922 0.013675922 0.143389971 0.143389971 0.596767509 0.596767509 Wsets Lsets Comment 0.598425197 0.598425197 0.000000000
We installed Amelia package via install.packages(“Amelia”) into the console to assist with plotting a map for visualising missing values.From the map we observe the missing values are detected from the following columns:
Lsets — Loser set
Wsets — Winner set
W5 — Winner in the fifth set
L5 — Loser in the fifth set
L4 — Loser in the fourth set
W4 — Winner in the fourth set
I tried this but, the last line of code helped me create a vector to remove NAs but it also removed more than 50% of my training data so it was not helpful!
View(a) # view the missing valuescomplete.cases(a) # view missing valueswhich(complete.cases(a)) # view which row has full row values are located inwhich(!complete.cases(a)) # view which row has ‘full ‘NA’ row values are l
na_vec <- which(complete.cases(a))na_vec <- which(!complete.cases(a)) # create a vector for NA values
a[-na_vec] # vector with NA rows removed.
The imputed data was plotted to understand the distribution of the original data. The techniques for imputation that I followed were from the author Michy Alice from his blog. These are the steps:
# Impute missing values with "pmm" - predicted mean matching. m=5 imputed data sets is defaultimputed_Data <- mice(a.mis, m=5, maxit = 50, method = 'pmm', seed = 500)summary(imputed_Data)# inspect that missing data has been imputedimputed_Data$imp$Lsets# check imputed methodimputed_Data$meth# Plot the imputed data and inspect the distributionxyplot(imputed_Data,WRank ~ W1+L1+W2+L2+W3+L3+W4+L4+L5+W5+LRank,pch=18,cex=1)
I used ggplot to examine the numeric attributes that had less than 5% missing values to visualise via density plots.
p1 <- ggplot(a, aes(x=a$Year)) + geom_histogram() + ggtitle(" Histogram of Year")p1p2 <- ggplot(a, aes(x=a$WRank)) + geom_histogram()+ ggtitle(" Histogram of Winner's Ranking")p2p3 <- ggplot(a, aes(x=a$LRank)) + geom_histogram()+ ggtitle(" Histogram of Loser's Ranking")p3p4 <- ggplot(a, aes(x=a$W1)) + geom_histogram()+ ggtitle(" Histogram of Winner in the first set")p4p5 <- ggplot(a, aes(x=a$L1)) + geom_histogram()+ ggtitle(" Histogram of Loser in the first set")p5p6 <- ggplot(a, aes(x=a$W2)) + geom_histogram()+ ggtitle(" Histogram of Winner in the second set")p6p7 <- ggplot(a, aes(x=a$L2)) + geom_histogram()+ ggtitle(" Histogram of Loser in the second set")p7p8 <- ggplot(a, aes(x=a$W3)) + geom_histogram()+ ggtitle(" Histogram of Winner in the third set")p8p9 <- ggplot(a, aes(x=a$L3)) + geom_histogram()+ ggtitle(" Histogram of Loser in the third set")p9
p16 <- plot(x = a$Comment, main = "Distribution of Comment", xlab = "Comment", ylab = "count")p16p17 <- plot(x= a$Winner,main = "Distribution of Winner", xlab = "Winner", ylab = "count")p17p18 <- plot( x = a$Loser, main = "Distribution of Loser", xlab = "Loser", ylab = "Count")p18p19 <- plot( x = a$Best.of, main = "Distribution of Best.of", xlab = "Best Of", ylab = "Count")p19p20 <- plot( x = a$Round, main = "Distribution of Tennis Round", xlab = "Round", ylab = "Count")p20
This a density plot of the imputed numeric data:
densityplot(imputed_Data)
Key: colour magenta (imputed data) and blue (observed data)
# View the data as individual pointsstripplot(imputed_Data, pch = 20, cex = 1.2)
The R script for this pre-processing and EDA is shared here on Github.
R Markdown script is also saved in Github and can be viewed as a html file via the command Knit to Html, this is especially useful on a web browser for all the plotting of the data attributes.
** Note to self:
1. When using R Markdown, insert the R code below ```{r cars} as per the screenshot below to be exact it is line 23:
2. Secondly, I inserted the second chunk of R code relating to charts and plots below the section ```{r pressure, echo=FALSE} and code is inserted at line 214.
After we have visualised the data in R, we want to use other analytic tools such as Tableau to explore and visualise Australian Open data.
Happy coding as we continue the next post with Tableau in Part 3! | [
{
"code": null,
"e": 289,
"s": 172,
"text": "Data cleaning and transforming variables in R using Australian Tennis Open data on the Men’s tour from 2000 to 2018."
},
{
"code": null,
"e": 687,
"s": 289,
"text": "Today is Day 4 and marks the continuation of my #29dayproject bootcamp of data science and things I have learnt in data science. This is a tutorial guide of cleaning and pre-processing the tennis data from the Australian Open Tennis tournament from 2000 to 2019 to predict who might win using R. Yesterday we merged multiple csv files and subsetted the data you may follow here from the blog post."
},
{
"code": null,
"e": 997,
"s": 687,
"text": "If you take a class in Data Analytics at General Assembly, take a data science course at your university in data science algorithms, take an IT elective of interest, study an online course or you may work on a data mining project for your Professor you will come across the data mining principles of CRISP-DM."
},
{
"code": null,
"e": 1224,
"s": 997,
"text": "CRISP-DM is the cross-industry process for data mining. It is also a prescribed analytics workflow I learnt at General Assembly Sydney and the principles are used in data science projects when you are consulting in government."
},
{
"code": null,
"e": 1397,
"s": 1224,
"text": "This the workflow of CRISP-DM methodology used to guide you through data analytics and data science problems.You may review each of the steps from Smart Vision Europe 2018."
},
{
"code": null,
"e": 1571,
"s": 1397,
"text": "This is not a business problem but the scope of the problem statement was to predict the winner of this year’s Australian Open Tennis Finals based on data from 2000 to 2018."
},
{
"code": null,
"e": 1682,
"s": 1571,
"text": "Previously we obtained a data dictionary and explored the data by analysing the overall structure of the data."
},
{
"code": null,
"e": 1728,
"s": 1682,
"text": "Here is the data dictionary of the variables:"
},
{
"code": null,
"e": 3349,
"s": 1728,
"text": "ATP = Tournament number (men)WTA = Tournament number (women)Location = Venue of tournamentTournament = Name of tounament (including sponsor if relevant)Data = Date of match (note: prior to 2003 the date shown for all matches played in a single tournament is the start date)Series = Name of ATP tennis series (Grand Slam, Masters, International or International Gold)Tier = Tier (tournament ranking) of WTA tennis series.Court = Type of court (outdoors or indoors)Surface = Type of surface (clay, hard, carpet or grass)Round = Round of matchBest of = Maximum number of sets playable in matchWinner = Match winnerLoser = Match loserWRank = ATP Entry ranking of the match winner as of the start of the tournamentLRank = ATP Entry ranking of the match loser as of the start of the tournamentWPts = ATP Entry points of the match winner as of the start of the tournamentLPts = ATP Entry points of the match loser as of the start of the tournamentW1 = Number of games won in 1st set by match winnerL1 = Number of games won in 1st set by match loserW2 = Number of games won in 2nd set by match winnerL2 = Number of games won in 2nd set by match loserW3 = Number of games won in 3rd set by match winnerL3 = Number of games won in 3rd set by match loserW4 = Number of games won in 4th set by match winnerL4 = Number of games won in 4th set by match loserW5 = Number of games won in 5th set by match winnerL5 = Number of games won in 5th set by match loserWsets = Number of sets won by match winnerLsets = Number of sets won by match loserComment = Comment on the match (Completed, won through retirement of loser, or via Walkover)"
},
{
"code": null,
"e": 3663,
"s": 3349,
"text": "The data has been cleaned by the encoding of categorical variables, transforming variables and the detection of missing values. We have already merged the original data and the “aus_open.csv” dataframe is read into R using StringAsfactors =FALSE to ensure all the variables are not automatically read as a factor."
},
{
"code": null,
"e": 3983,
"s": 3663,
"text": "#################################### Pre-Processing the Training Data#################################### Exported aust_open.csv file was exported and a new column was created in Excel to extract the year from the data with non-standardised formattinga <- read.csv(\"aus_open.csv\",stringsAsFactors = FALSE,header = TRUE)"
},
{
"code": null,
"e": 4088,
"s": 3983,
"text": "Using Hadley Wickham’s dplyr package, I explored the structure of the data using the function glimpse()."
},
{
"code": null,
"e": 4227,
"s": 4088,
"text": "############################## Exploratory Data Analysis#############################glimpse(a) # view the structure of the training data"
},
{
"code": null,
"e": 4349,
"s": 4227,
"text": "The output of the descriptive statistics is provided below, a summary of all of the numeric variables and missing values."
},
{
"code": null,
"e": 8060,
"s": 4349,
"text": "summary(a) # descriptive statistics ATP Location Tournament Date Min. :6 Length:2413 Length:2413 Length:2413 1st Qu.:6 Class :character Class :character Class :character Median :6 Mode :character Mode :character Mode :character Mean :6 3rd Qu.:6 Max. :6 Year Series Court Surface Min. :2000 Length:2413 Length:2413 Length:2413 1st Qu.:2004 Class :character Class :character Class :character Median :2009 Mode :character Mode :character Mode :character Mean :2009 3rd Qu.:2014 Max. :2018 Round Best.of Winner Loser Length:2413 Min. :5 Length:2413 Length:2413 Class :character 1st Qu.:5 Class :character Class :character Mode :character Median :5 Mode :character Mode :character Mean :5 3rd Qu.:5 Max. :5 WRank LRank W1 L1 Min. : 1.00 Length:2413 Min. : 0 Length:2413 1st Qu.: 10.00 Class :character 1st Qu.: 7 Class :character Median : 28.00 Mode :character Median : 860 Mode :character Mean : 46.97 Mean : 1863 3rd Qu.: 65.00 3rd Qu.: 2145 Max. :768.00 Max. :16790 NA's :128 W2 L2 W3 L3 Min. :0.000 Min. :0.000 Min. :0.000 Min. :0.000 1st Qu.:6.000 1st Qu.:3.000 1st Qu.:6.000 1st Qu.:2.000 Median :6.000 Median :4.000 Median :6.000 Median :4.000 Mean :5.687 Mean :4.027 Mean :5.743 Mean :3.903 3rd Qu.:6.000 3rd Qu.:6.000 3rd Qu.:6.000 3rd Qu.:6.000 Max. :7.000 Max. :7.000 Max. :7.000 Max. :7.000 NA's :10 NA's :10 NA's :33 NA's :33 W4 L4 W5 L5 Min. :0.000 Min. :0.000 Min. : 0.000 Min. : 0.000 1st Qu.:6.000 1st Qu.:2.000 1st Qu.: 6.000 1st Qu.: 2.000 Median :6.000 Median :4.000 Median : 6.000 Median : 4.000 Mean :5.753 Mean :3.734 Mean : 5.883 Mean : 3.813 3rd Qu.:6.000 3rd Qu.:6.000 3rd Qu.: 6.000 3rd Qu.: 6.000 Max. :7.000 Max. :7.000 Max. :21.000 Max. :19.000 NA's :346 NA's :346 NA's :1440 NA's :1440 Wsets Lsets Comment Min. : 0.000 Min. : 0.0 Length:2413 1st Qu.: 3.000 1st Qu.: 0.0 Class :character Median : 3.000 Median : 1.0 Mode :character Mean : 4.192 Mean : 1.7 3rd Qu.: 6.000 3rd Qu.: 2.0 Max. :22.000 Max. :20.0 NA's :1444 NA's :1444"
},
{
"code": null,
"e": 8250,
"s": 8060,
"text": "From the glimpse of the structure above, some of the data attributes were not cast in their correct data type. This is my favourite part the chance to transform the variables! Here we go..."
},
{
"code": null,
"e": 9009,
"s": 8250,
"text": "# Transform character variables into numeric variables a$W1 <- as.numeric(a$W1)a$L1 <- as.numeric(a$L1)a$WRank <- as.numeric(a$WRank)a$LRank <- as.numeric(a$LRank)########################################################### encoding categorical features########################################################### Convert categorical variables into factors to represent their levelsa$Location <- factor(a$Location)a$Tournament <- factor(a$Tournament)a$Series <- factor(a$Series)a$Court <- factor(a$Court)a$Surface <- factor(a$Surface)a$Best.of <- factor(a$Best.of)a$Round <- factor(a$Round)a$Winner <- factor(a$Winner)a$Loser <- factor(a$Loser)a$Comment <- factor(a$Comment)glimpse(a) # check that structure of categorical variables have converted with levels"
},
{
"code": null,
"e": 9228,
"s": 9009,
"text": "library(dummies)Round <- dummy(a$Round)Best.of <- dummy(a$Best.of)Winner <- dummy(a$Winner)Loser <- dummy(a$Loser)Comment <- dummy(a$Comment)head(a) # check that the values are been converted to dummy variablesstr(a)"
},
{
"code": null,
"e": 11426,
"s": 9228,
"text": "# Descriptive statisticssummary(a)# View the structure of the transformed variables the 'dplyr' way > glimpse(a)Observations: 2,413Variables: 27$ ATP <int> 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...$ Location <fct> Melbourne, Melbourne, Melbourne, Melbourne, Melbourne,...$ Tournament <fct> Australian Open, Australian Open, Australian Open, Aus...$ Date <chr> \"1/17/00\", \"1/17/00\", \"1/17/00\", \"1/17/00\", \"1/17/00\",...$ Year <int> 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, ...$ Series <fct> Grand Slam, Grand Slam, Grand Slam, Grand Slam, Grand ...$ Court <fct> Outdoor, Outdoor, Outdoor, Outdoor, Outdoor, Outdoor, ...$ Surface <fct> Hard, Hard, Hard, Hard, Hard, Hard, Hard, Hard, Hard, ...$ Round <fct> 1st Round, 1st Round, 1st Round, 1st Round, 1st Round,...$ Best.of <fct> 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ...$ Winner <fct> Agassi A., Alami K., Arazi H., Behrend T., Bjorkman J....$ Loser <fct> Puerta M., Manta L., Alonso J., Meligeni F., Stoltenbe...$ WRank <dbl> 1, 35, 41, 106, 76, 151, 39, 54, 30, 64, 98, 29, 34, 6...$ LRank <dbl> 112, 107, 111, 28, 81, 57, 22, 66, 51, 155, 119, 257, ...$ W1 <dbl> 6, 6, 6, 6, 6, 7, 3, 7, 7, 7, 6, 6, 6, 6, 6, 7, 6, 6, ...$ L1 <dbl> 2, 4, 3, 2, 7, 6, 6, 6, 6, 6, 4, 7, 7, 4, 3, 6, 4, 3, ...$ W2 <int> 6, 7, 7, 4, 6, 6, 6, 6, 6, 5, 6, 7, 6, 6, 6, 6, 7, 6, ...$ L2 <int> 2, 6, 6, 6, 4, 1, 1, 4, 4, 7, 4, 6, 3, 4, 3, 3, 6, 3, ...$ W3 <int> 6, 7, 6, 6, 6, 6, 6, NA, 6, 6, 7, 1, 7, 7, 4, 7, 4, 6,...$ L3 <int> 3, 5, 2, 7, 4, 4, 4, NA, 4, 3, 6, 6, 5, 6, 6, 6, 6, 2,...$ W4 <int> NA, NA, NA, 6, 0, NA, 7, NA, NA, 7, NA, 6, 6, NA, 7, N...$ L4 <int> NA, NA, NA, 3, 6, NA, 6, NA, NA, 5, NA, 3, 1, NA, 6, N...$ W5 <int> NA, NA, NA, 6, 6, NA, NA, NA, NA, NA, NA, 6, NA, NA, N...$ L5 <int> NA, NA, NA, 0, 4, NA, NA, NA, NA, NA, NA, 1, NA, NA, N...$ Wsets <int> 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, ...$ Lsets <int> 0, 0, 0, 2, 2, 0, 1, 0, 0, 1, 0, 2, 1, 0, 1, 0, 2, 0, ...$ Comment <fct> Completed, Completed, Completed, Completed, Completed,..."
},
{
"code": null,
"e": 11564,
"s": 11426,
"text": "We will try a few methods to detect the missing values such as counting the number of missing values per column, sum and taking the mean."
},
{
"code": null,
"e": 12359,
"s": 11564,
"text": "# Sum the number of missing values> sum(is.na(a)) [1] 6810# average of the missing values in each column> mean(is.na(a)) [1] 0.1045264# Count the number of missing values per column> colSums(is.na(a)) ATP Location Tournament Date Year Series Court 0 0 0 0 0 0 0 Surface Round Best.of Winner Loser WRank LRank 0 0 0 0 0 0 5 W1 L1 W2 L2 W3 L3 W4 128 131 10 10 33 33 346 L4 W5 L5 Wsets Lsets Comment 346 1440 1440 1444 1444 0"
},
{
"code": null,
"e": 12571,
"s": 12359,
"text": "In detecting missing values 5% is the acceptable threshold for each column.The output confirms that the columns : L4, W4, L5,W5, Wsets and Lsets have missing values greater than 5% and can be removed or imputed."
},
{
"code": null,
"e": 13280,
"s": 12571,
"text": "sapply(a, function(df){ sum(is.na(df) ==TRUE)/length(df); }) ATP Location Tournament Date Year Series 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 Court Surface Round Best.of Winner Loser 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 WRank LRank W1 L1 W2 L2 0.000000000 0.002072109 0.053046001 0.054289266 0.004144219 0.004144219 W3 L3 W4 L4 W5 L5 0.013675922 0.013675922 0.143389971 0.143389971 0.596767509 0.596767509 Wsets Lsets Comment 0.598425197 0.598425197 0.000000000"
},
{
"code": null,
"e": 13501,
"s": 13280,
"text": "We installed Amelia package via install.packages(“Amelia”) into the console to assist with plotting a map for visualising missing values.From the map we observe the missing values are detected from the following columns:"
},
{
"code": null,
"e": 13519,
"s": 13501,
"text": "Lsets — Loser set"
},
{
"code": null,
"e": 13538,
"s": 13519,
"text": "Wsets — Winner set"
},
{
"code": null,
"e": 13567,
"s": 13538,
"text": "W5 — Winner in the fifth set"
},
{
"code": null,
"e": 13595,
"s": 13567,
"text": "L5 — Loser in the fifth set"
},
{
"code": null,
"e": 13624,
"s": 13595,
"text": "L4 — Loser in the fourth set"
},
{
"code": null,
"e": 13654,
"s": 13624,
"text": "W4 — Winner in the fourth set"
},
{
"code": null,
"e": 13811,
"s": 13654,
"text": "I tried this but, the last line of code helped me create a vector to remove NAs but it also removed more than 50% of my training data so it was not helpful!"
},
{
"code": null,
"e": 14034,
"s": 13811,
"text": "View(a) # view the missing valuescomplete.cases(a) # view missing valueswhich(complete.cases(a)) # view which row has full row values are located inwhich(!complete.cases(a)) # view which row has ‘full ‘NA’ row values are l"
},
{
"code": null,
"e": 14136,
"s": 14034,
"text": "na_vec <- which(complete.cases(a))na_vec <- which(!complete.cases(a)) # create a vector for NA values"
},
{
"code": null,
"e": 14178,
"s": 14136,
"text": "a[-na_vec] # vector with NA rows removed."
},
{
"code": null,
"e": 14375,
"s": 14178,
"text": "The imputed data was plotted to understand the distribution of the original data. The techniques for imputation that I followed were from the author Michy Alice from his blog. These are the steps:"
},
{
"code": null,
"e": 14797,
"s": 14375,
"text": "# Impute missing values with \"pmm\" - predicted mean matching. m=5 imputed data sets is defaultimputed_Data <- mice(a.mis, m=5, maxit = 50, method = 'pmm', seed = 500)summary(imputed_Data)# inspect that missing data has been imputedimputed_Data$imp$Lsets# check imputed methodimputed_Data$meth# Plot the imputed data and inspect the distributionxyplot(imputed_Data,WRank ~ W1+L1+W2+L2+W3+L3+W4+L4+L5+W5+LRank,pch=18,cex=1)"
},
{
"code": null,
"e": 14914,
"s": 14797,
"text": "I used ggplot to examine the numeric attributes that had less than 5% missing values to visualise via density plots."
},
{
"code": null,
"e": 15780,
"s": 14914,
"text": "p1 <- ggplot(a, aes(x=a$Year)) + geom_histogram() + ggtitle(\" Histogram of Year\")p1p2 <- ggplot(a, aes(x=a$WRank)) + geom_histogram()+ ggtitle(\" Histogram of Winner's Ranking\")p2p3 <- ggplot(a, aes(x=a$LRank)) + geom_histogram()+ ggtitle(\" Histogram of Loser's Ranking\")p3p4 <- ggplot(a, aes(x=a$W1)) + geom_histogram()+ ggtitle(\" Histogram of Winner in the first set\")p4p5 <- ggplot(a, aes(x=a$L1)) + geom_histogram()+ ggtitle(\" Histogram of Loser in the first set\")p5p6 <- ggplot(a, aes(x=a$W2)) + geom_histogram()+ ggtitle(\" Histogram of Winner in the second set\")p6p7 <- ggplot(a, aes(x=a$L2)) + geom_histogram()+ ggtitle(\" Histogram of Loser in the second set\")p7p8 <- ggplot(a, aes(x=a$W3)) + geom_histogram()+ ggtitle(\" Histogram of Winner in the third set\")p8p9 <- ggplot(a, aes(x=a$L3)) + geom_histogram()+ ggtitle(\" Histogram of Loser in the third set\")p9"
},
{
"code": null,
"e": 16286,
"s": 15780,
"text": "p16 <- plot(x = a$Comment, main = \"Distribution of Comment\", xlab = \"Comment\", ylab = \"count\")p16p17 <- plot(x= a$Winner,main = \"Distribution of Winner\", xlab = \"Winner\", ylab = \"count\")p17p18 <- plot( x = a$Loser, main = \"Distribution of Loser\", xlab = \"Loser\", ylab = \"Count\")p18p19 <- plot( x = a$Best.of, main = \"Distribution of Best.of\", xlab = \"Best Of\", ylab = \"Count\")p19p20 <- plot( x = a$Round, main = \"Distribution of Tennis Round\", xlab = \"Round\", ylab = \"Count\")p20"
},
{
"code": null,
"e": 16335,
"s": 16286,
"text": "This a density plot of the imputed numeric data:"
},
{
"code": null,
"e": 16361,
"s": 16335,
"text": "densityplot(imputed_Data)"
},
{
"code": null,
"e": 16421,
"s": 16361,
"text": "Key: colour magenta (imputed data) and blue (observed data)"
},
{
"code": null,
"e": 16502,
"s": 16421,
"text": "# View the data as individual pointsstripplot(imputed_Data, pch = 20, cex = 1.2)"
},
{
"code": null,
"e": 16573,
"s": 16502,
"text": "The R script for this pre-processing and EDA is shared here on Github."
},
{
"code": null,
"e": 16766,
"s": 16573,
"text": "R Markdown script is also saved in Github and can be viewed as a html file via the command Knit to Html, this is especially useful on a web browser for all the plotting of the data attributes."
},
{
"code": null,
"e": 16783,
"s": 16766,
"text": "** Note to self:"
},
{
"code": null,
"e": 16900,
"s": 16783,
"text": "1. When using R Markdown, insert the R code below ```{r cars} as per the screenshot below to be exact it is line 23:"
},
{
"code": null,
"e": 17060,
"s": 16900,
"text": "2. Secondly, I inserted the second chunk of R code relating to charts and plots below the section ```{r pressure, echo=FALSE} and code is inserted at line 214."
},
{
"code": null,
"e": 17199,
"s": 17060,
"text": "After we have visualised the data in R, we want to use other analytic tools such as Tableau to explore and visualise Australian Open data."
}
] |
Building a Text Normalizer using NLTK ft. POS tagger | by Nabanita Roy | Towards Data Science | Tokenization and text normalization are the two most fundamental steps of Natural Language Processing (NLP) techniques. Text normalization is the technique which transforms a word into its root or basic form in order to standardize text representation. Note that the basic form is not necessarily a meaningful word and we will see that by the end of this blog. These basic forms are termed as stems and the process is called stemming. A specialised approach to derive the stem of a word is called lemmatization which uses rules according to the part-of-speech(POS) family the word belongs to.
Text normalization is essential for Information Retrieval (IR) systems, data or text mining applications and NLP pipelines. To facilitate faster and efficient IR systems, indexing and searching algorithms require different word forms — derivational or inflectional — reduced to their normalized forms. Besides, it also helps in saving disk space and interlingual text matching.
The process of deriving lemmas deals with the semantics, morphology and the parts-of-speech(POS) the word belongs to, while Stemming refers to a crude heuristic process that chops off the ends of words in the hope of achieving this goal correctly most of the time, and often includes the removal of derivational affixes. [1] This is the reason, in most applications, lemmatization has better performance over stemming, although narrowing down to a decision requires the bigger picture.
In Python’s NLTK Library, the nltk.stem package has both — stemmers and lemmatizers implemented.
Enough! Let’s dig into some text normalizing code now...
What could possibly go wrong??!
Note: Here is the complete jupyter notebook on GitHub.
Step 1: Tokenization
import nltkimport stringhermione_said = '''Books! And cleverness! There are more important things - friendship and bravery and - oh Harry - be careful!'''## Tokenizationfrom nltk import sent_tokenize, word_tokenizesequences = sent_tokenize(hermione_said)seq_tokens = [word_tokenize(seq) for seq in sequences]## Remove punctuationno_punct_seq_tokens = []for seq_token in seq_tokens: no_punct_seq_tokens.append([token for token in seq_token if token not in string.punctuation])print(no_punct_seq_tokens)Output:[['Books'], ['And', 'cleverness'], ['There', 'are', 'more', 'important', 'things', 'friendship', 'and', 'bravery', 'and', 'oh', 'Harry', 'be', 'careful']]
Sweet!
Step 2: Normalization Techniques
We start with Stemming:
# Using Porter Stemmer implementation in nltkfrom nltk.stem import PorterStemmerstemmer = PorterStemmer()stemmed_tokens = [stemmer.stem(token) for seq in no_punct_seq_tokens for token in seq]print(stemmed_tokens)Output:['book', 'and', 'clever', 'there', 'are', 'more', 'import', 'thing', 'friendship', 'and', 'braveri', 'and', 'oh', 'harri', 'be', 'care']
So we have our first problem — out of the 16 tokens, the highlighted 3 does not look good!
All three are products of the crude heuristic process but ‘Harry’ to ‘harri’ is misleading, especially, for NER applications and ‘important’ to ‘import’ is information lost. ‘bravery’ to ‘bravery’ is an example of a stem that does not bear any meaning but could still be used in IR systems for indexing. A better example would be — argue,arguing, argued — all of which becomes ‘argu’, preserving the meaning of the original words but itself does not bear any meaning in the English dictionary.
Now, let’s lemmatize:
from nltk.stem.wordnet import WordNetLemmatizerfrom nltk.corpus import wordnetlm = WordNetLemmatizer()lemmatized_tokens = [lm.lemmatize(token) for seq in no_punct_seq_tokens for token in seq]print(lemmatized_tokens)Output:['Books', 'And', 'cleverness', 'There', 'are', 'more', 'important', 'thing', 'friendship', 'and', 'bravery', 'and', 'oh', 'Harry', 'be', 'careful']
Here, the previous three words that were incorrectly stemmed, look better. But, “Books” should have become “Book” just like “things” to “thing”.
That’s our second problem.
Now, WordNetLemmatizer.lemma() takes in an argument pos to understand the POS tag of the word/token because word-forms could be same but contextually or semantically different. For example:
print(lm.lemmatize("Books", pos="n"))Output: 'Books'print(lm.lemmatize("books", pos="v"))Output: 'book'
Therefore, taking help from POS tagger seems like a convenient option and we shall proceed to use POS tagger to solve this problem.
But before that, let’s look at which one to use — stemmer? lemmatizer? both? To answer this question, we need to take a step back and answer questions like:
What is the problem statement?
What features are important to address the problem statement?
Is this feature an overhead for computation and infrastructure?
The example above is a simple taster for the larger challenges that NLP practitioners face while processing millions of tokens’ basic forms. Besides, maintaining precision while processing huge corpora with additional checks like POS tagger (in this case), NER tagger, matching tokens in a Bag-of-Words(BOW) and spelling corrections are computationally expensive.
Step 3: POS Tagger to rescue
Let’s apply POS tagger on the already stemmed and lemmatized token to check their behaviours.
from nltk.tag import StanfordPOSTaggerst = StanfordPOSTagger(path_to_model, path_to_jar, encoding=’utf8')## Tagging Lemmatized Tokenstext_tags_lemmatized_tokens = st.tag(lemmatized_tokens)print(text_tags_lemmatized_tokens)Output:[('Books', 'NNS'), ('And', 'CC'), ('cleverness', 'NN'), ('There', 'EX'), ('are', 'VBP'), ('more', 'RBR'), ('important', 'JJ'), ('thing', 'NN'), ('friendship', 'NN'), ('and', 'CC'), ('bravery', 'NN'), ('and', 'CC'), ('oh', 'UH'), ('Harry', 'NNP'), ('be', 'VB'), ('careful', 'JJ')]## Tagging Stemmed Tokenstext_tags_stemmed_tokens = st.tag(stemmed_tokens)print(text_tags_stemmed_tokens)Output:[('book', 'NN'), ('and', 'CC'), ('clever', 'JJ'), ('there', 'EX'), ('are', 'VBP'), ('more', 'JJR'), ('import', 'NN'), ('thing', 'NN'), ('friendship', 'NN'), ('and', 'CC'), ('braveri', 'NN'), ('and', 'CC'), ('oh', 'UH'), ('harri', 'NNS'), ('be', 'VB'), ('care', 'NN')]
Spot the highlighted differences?
The first token — book — the stemmed token’s tag is NN (Noun) and that of the lemmatized one is NNS (Plural Noun), which more specific.
Second, Harry — wrongly stemmed to harri and as a result the POS tagger fails to identify it correctly as a Proper Noun. On the other hand, the lemmatized token correctly classified Harry and the POS tagger specifically identified it as a Proper Noun.
Lastly, harri and braveri — even though these words are not anywhere in the english lexical dictionary, they should have been classified as a FW. This I have no explanation or right now.
Step 4: Building the POS mapper for token tags
I first created a POS mapper like below. This mapper is for the arguments to wordnet according to the treebank POS tag codes.
from nltk.corpus.reader.wordnet import VERB, NOUN, ADJ, ADVdict_pos_map = { # Look for NN in the POS tag because all nouns begin with NN 'NN': NOUN, # Look for VB in the POS tag because all nouns begin with VB 'VB':VERB, # Look for JJ in the POS tag because all nouns begin with JJ 'JJ' : ADJ, # Look for RB in the POS tag because all nouns begin with RB 'RB':ADV }
Step 5: Building the normalizer while addressing the problems
Identify the Proper Nouns and skips processing and retain Upper CaseIdentify the POS family the token’s POS tag belongs to — NN, VB, JJ, RB and pass the correct argument for lemmatizationGet the stems of the lemmatized tokens.
Identify the Proper Nouns and skips processing and retain Upper Case
Identify the POS family the token’s POS tag belongs to — NN, VB, JJ, RB and pass the correct argument for lemmatization
Get the stems of the lemmatized tokens.
Here, is the final code. I used st.tag_sents() to retain the order of the sequences (sentence-wise nested tokens)
With Stemming
normalized_sequence = []for each_seq in st.tag_sents(sentences=no_punct_seq_tokens): normalized_tokens = [] for tuples in each_seq: temp = tuples[0] if tuples[1] == "NNP" or tuples[1] == "NNPS": continue if tuples[1][:2] in dict_pos_map.keys(): temp = lm.lemmatize(tuples[0].lower(), pos=dict_pos_map[tuples[1][:2]]) temp = stemmer.stem(temp) normalized_tokens.append(temp) normalized_sequence.append(normalized_tokens)normalized_sequenceOutput:[['book'], ['and', 'clever'], ['there', 'be', 'more', 'import', 'thing', 'friendship', 'and', 'braveri', 'and', 'oh', 'be', 'care']]
Without Stemming
normalized_sequence = []for each_seq in st.tag_sents(sentences=no_punct_seq_tokens): normalized_tokens = [] for tuples in each_seq: temp = tuples[0] if tuples[1] == "NNP" or tuples[1] == "NNPS": continue if tuples[1][:2] in dict_pos_map.keys(): temp = lm.lemmatize(tuples[0].lower(), pos=dict_pos_map[tuples[1][:2]]) normalized_tokens.append(temp) normalized_sequence.append(normalized_tokens)normalized_sequenceOutput:[['book'], ['And', 'cleverness'], ['There', 'be', 'more', 'important', 'thing', 'friendship', 'and', 'bravery', 'and', 'oh', 'be', 'careful']]
The two differences I still have in the process is important is stemmed to import and bravery to braveri. While “braveri” is considerably unambiguous, “import” poses a challenge because it could mean different things. This is why, in general, stemming has poorer performance than lemmatization as it increases search term ambiguities and therefore detects similarities which are not actually similar.
Note: Here is the complete jupyter notebook on GitHub. | [
{
"code": null,
"e": 765,
"s": 172,
"text": "Tokenization and text normalization are the two most fundamental steps of Natural Language Processing (NLP) techniques. Text normalization is the technique which transforms a word into its root or basic form in order to standardize text representation. Note that the basic form is not necessarily a meaningful word and we will see that by the end of this blog. These basic forms are termed as stems and the process is called stemming. A specialised approach to derive the stem of a word is called lemmatization which uses rules according to the part-of-speech(POS) family the word belongs to."
},
{
"code": null,
"e": 1143,
"s": 765,
"text": "Text normalization is essential for Information Retrieval (IR) systems, data or text mining applications and NLP pipelines. To facilitate faster and efficient IR systems, indexing and searching algorithms require different word forms — derivational or inflectional — reduced to their normalized forms. Besides, it also helps in saving disk space and interlingual text matching."
},
{
"code": null,
"e": 1629,
"s": 1143,
"text": "The process of deriving lemmas deals with the semantics, morphology and the parts-of-speech(POS) the word belongs to, while Stemming refers to a crude heuristic process that chops off the ends of words in the hope of achieving this goal correctly most of the time, and often includes the removal of derivational affixes. [1] This is the reason, in most applications, lemmatization has better performance over stemming, although narrowing down to a decision requires the bigger picture."
},
{
"code": null,
"e": 1726,
"s": 1629,
"text": "In Python’s NLTK Library, the nltk.stem package has both — stemmers and lemmatizers implemented."
},
{
"code": null,
"e": 1783,
"s": 1726,
"text": "Enough! Let’s dig into some text normalizing code now..."
},
{
"code": null,
"e": 1815,
"s": 1783,
"text": "What could possibly go wrong??!"
},
{
"code": null,
"e": 1870,
"s": 1815,
"text": "Note: Here is the complete jupyter notebook on GitHub."
},
{
"code": null,
"e": 1891,
"s": 1870,
"text": "Step 1: Tokenization"
},
{
"code": null,
"e": 2569,
"s": 1891,
"text": "import nltkimport stringhermione_said = '''Books! And cleverness! There are more important things - friendship and bravery and - oh Harry - be careful!'''## Tokenizationfrom nltk import sent_tokenize, word_tokenizesequences = sent_tokenize(hermione_said)seq_tokens = [word_tokenize(seq) for seq in sequences]## Remove punctuationno_punct_seq_tokens = []for seq_token in seq_tokens: no_punct_seq_tokens.append([token for token in seq_token if token not in string.punctuation])print(no_punct_seq_tokens)Output:[['Books'], ['And', 'cleverness'], ['There', 'are', 'more', 'important', 'things', 'friendship', 'and', 'bravery', 'and', 'oh', 'Harry', 'be', 'careful']]"
},
{
"code": null,
"e": 2576,
"s": 2569,
"text": "Sweet!"
},
{
"code": null,
"e": 2609,
"s": 2576,
"text": "Step 2: Normalization Techniques"
},
{
"code": null,
"e": 2633,
"s": 2609,
"text": "We start with Stemming:"
},
{
"code": null,
"e": 2989,
"s": 2633,
"text": "# Using Porter Stemmer implementation in nltkfrom nltk.stem import PorterStemmerstemmer = PorterStemmer()stemmed_tokens = [stemmer.stem(token) for seq in no_punct_seq_tokens for token in seq]print(stemmed_tokens)Output:['book', 'and', 'clever', 'there', 'are', 'more', 'import', 'thing', 'friendship', 'and', 'braveri', 'and', 'oh', 'harri', 'be', 'care']"
},
{
"code": null,
"e": 3080,
"s": 2989,
"text": "So we have our first problem — out of the 16 tokens, the highlighted 3 does not look good!"
},
{
"code": null,
"e": 3574,
"s": 3080,
"text": "All three are products of the crude heuristic process but ‘Harry’ to ‘harri’ is misleading, especially, for NER applications and ‘important’ to ‘import’ is information lost. ‘bravery’ to ‘bravery’ is an example of a stem that does not bear any meaning but could still be used in IR systems for indexing. A better example would be — argue,arguing, argued — all of which becomes ‘argu’, preserving the meaning of the original words but itself does not bear any meaning in the English dictionary."
},
{
"code": null,
"e": 3596,
"s": 3574,
"text": "Now, let’s lemmatize:"
},
{
"code": null,
"e": 3966,
"s": 3596,
"text": "from nltk.stem.wordnet import WordNetLemmatizerfrom nltk.corpus import wordnetlm = WordNetLemmatizer()lemmatized_tokens = [lm.lemmatize(token) for seq in no_punct_seq_tokens for token in seq]print(lemmatized_tokens)Output:['Books', 'And', 'cleverness', 'There', 'are', 'more', 'important', 'thing', 'friendship', 'and', 'bravery', 'and', 'oh', 'Harry', 'be', 'careful']"
},
{
"code": null,
"e": 4111,
"s": 3966,
"text": "Here, the previous three words that were incorrectly stemmed, look better. But, “Books” should have become “Book” just like “things” to “thing”."
},
{
"code": null,
"e": 4138,
"s": 4111,
"text": "That’s our second problem."
},
{
"code": null,
"e": 4328,
"s": 4138,
"text": "Now, WordNetLemmatizer.lemma() takes in an argument pos to understand the POS tag of the word/token because word-forms could be same but contextually or semantically different. For example:"
},
{
"code": null,
"e": 4432,
"s": 4328,
"text": "print(lm.lemmatize(\"Books\", pos=\"n\"))Output: 'Books'print(lm.lemmatize(\"books\", pos=\"v\"))Output: 'book'"
},
{
"code": null,
"e": 4564,
"s": 4432,
"text": "Therefore, taking help from POS tagger seems like a convenient option and we shall proceed to use POS tagger to solve this problem."
},
{
"code": null,
"e": 4721,
"s": 4564,
"text": "But before that, let’s look at which one to use — stemmer? lemmatizer? both? To answer this question, we need to take a step back and answer questions like:"
},
{
"code": null,
"e": 4752,
"s": 4721,
"text": "What is the problem statement?"
},
{
"code": null,
"e": 4814,
"s": 4752,
"text": "What features are important to address the problem statement?"
},
{
"code": null,
"e": 4878,
"s": 4814,
"text": "Is this feature an overhead for computation and infrastructure?"
},
{
"code": null,
"e": 5242,
"s": 4878,
"text": "The example above is a simple taster for the larger challenges that NLP practitioners face while processing millions of tokens’ basic forms. Besides, maintaining precision while processing huge corpora with additional checks like POS tagger (in this case), NER tagger, matching tokens in a Bag-of-Words(BOW) and spelling corrections are computationally expensive."
},
{
"code": null,
"e": 5271,
"s": 5242,
"text": "Step 3: POS Tagger to rescue"
},
{
"code": null,
"e": 5365,
"s": 5271,
"text": "Let’s apply POS tagger on the already stemmed and lemmatized token to check their behaviours."
},
{
"code": null,
"e": 6253,
"s": 5365,
"text": "from nltk.tag import StanfordPOSTaggerst = StanfordPOSTagger(path_to_model, path_to_jar, encoding=’utf8')## Tagging Lemmatized Tokenstext_tags_lemmatized_tokens = st.tag(lemmatized_tokens)print(text_tags_lemmatized_tokens)Output:[('Books', 'NNS'), ('And', 'CC'), ('cleverness', 'NN'), ('There', 'EX'), ('are', 'VBP'), ('more', 'RBR'), ('important', 'JJ'), ('thing', 'NN'), ('friendship', 'NN'), ('and', 'CC'), ('bravery', 'NN'), ('and', 'CC'), ('oh', 'UH'), ('Harry', 'NNP'), ('be', 'VB'), ('careful', 'JJ')]## Tagging Stemmed Tokenstext_tags_stemmed_tokens = st.tag(stemmed_tokens)print(text_tags_stemmed_tokens)Output:[('book', 'NN'), ('and', 'CC'), ('clever', 'JJ'), ('there', 'EX'), ('are', 'VBP'), ('more', 'JJR'), ('import', 'NN'), ('thing', 'NN'), ('friendship', 'NN'), ('and', 'CC'), ('braveri', 'NN'), ('and', 'CC'), ('oh', 'UH'), ('harri', 'NNS'), ('be', 'VB'), ('care', 'NN')]"
},
{
"code": null,
"e": 6287,
"s": 6253,
"text": "Spot the highlighted differences?"
},
{
"code": null,
"e": 6423,
"s": 6287,
"text": "The first token — book — the stemmed token’s tag is NN (Noun) and that of the lemmatized one is NNS (Plural Noun), which more specific."
},
{
"code": null,
"e": 6675,
"s": 6423,
"text": "Second, Harry — wrongly stemmed to harri and as a result the POS tagger fails to identify it correctly as a Proper Noun. On the other hand, the lemmatized token correctly classified Harry and the POS tagger specifically identified it as a Proper Noun."
},
{
"code": null,
"e": 6862,
"s": 6675,
"text": "Lastly, harri and braveri — even though these words are not anywhere in the english lexical dictionary, they should have been classified as a FW. This I have no explanation or right now."
},
{
"code": null,
"e": 6909,
"s": 6862,
"text": "Step 4: Building the POS mapper for token tags"
},
{
"code": null,
"e": 7035,
"s": 6909,
"text": "I first created a POS mapper like below. This mapper is for the arguments to wordnet according to the treebank POS tag codes."
},
{
"code": null,
"e": 7426,
"s": 7035,
"text": "from nltk.corpus.reader.wordnet import VERB, NOUN, ADJ, ADVdict_pos_map = { # Look for NN in the POS tag because all nouns begin with NN 'NN': NOUN, # Look for VB in the POS tag because all nouns begin with VB 'VB':VERB, # Look for JJ in the POS tag because all nouns begin with JJ 'JJ' : ADJ, # Look for RB in the POS tag because all nouns begin with RB 'RB':ADV }"
},
{
"code": null,
"e": 7488,
"s": 7426,
"text": "Step 5: Building the normalizer while addressing the problems"
},
{
"code": null,
"e": 7715,
"s": 7488,
"text": "Identify the Proper Nouns and skips processing and retain Upper CaseIdentify the POS family the token’s POS tag belongs to — NN, VB, JJ, RB and pass the correct argument for lemmatizationGet the stems of the lemmatized tokens."
},
{
"code": null,
"e": 7784,
"s": 7715,
"text": "Identify the Proper Nouns and skips processing and retain Upper Case"
},
{
"code": null,
"e": 7904,
"s": 7784,
"text": "Identify the POS family the token’s POS tag belongs to — NN, VB, JJ, RB and pass the correct argument for lemmatization"
},
{
"code": null,
"e": 7944,
"s": 7904,
"text": "Get the stems of the lemmatized tokens."
},
{
"code": null,
"e": 8058,
"s": 7944,
"text": "Here, is the final code. I used st.tag_sents() to retain the order of the sequences (sentence-wise nested tokens)"
},
{
"code": null,
"e": 8072,
"s": 8058,
"text": "With Stemming"
},
{
"code": null,
"e": 8759,
"s": 8072,
"text": "normalized_sequence = []for each_seq in st.tag_sents(sentences=no_punct_seq_tokens): normalized_tokens = [] for tuples in each_seq: temp = tuples[0] if tuples[1] == \"NNP\" or tuples[1] == \"NNPS\": continue if tuples[1][:2] in dict_pos_map.keys(): temp = lm.lemmatize(tuples[0].lower(), pos=dict_pos_map[tuples[1][:2]]) temp = stemmer.stem(temp) normalized_tokens.append(temp) normalized_sequence.append(normalized_tokens)normalized_sequenceOutput:[['book'], ['and', 'clever'], ['there', 'be', 'more', 'import', 'thing', 'friendship', 'and', 'braveri', 'and', 'oh', 'be', 'care']]"
},
{
"code": null,
"e": 8776,
"s": 8759,
"text": "Without Stemming"
},
{
"code": null,
"e": 9440,
"s": 8776,
"text": "normalized_sequence = []for each_seq in st.tag_sents(sentences=no_punct_seq_tokens): normalized_tokens = [] for tuples in each_seq: temp = tuples[0] if tuples[1] == \"NNP\" or tuples[1] == \"NNPS\": continue if tuples[1][:2] in dict_pos_map.keys(): temp = lm.lemmatize(tuples[0].lower(), pos=dict_pos_map[tuples[1][:2]]) normalized_tokens.append(temp) normalized_sequence.append(normalized_tokens)normalized_sequenceOutput:[['book'], ['And', 'cleverness'], ['There', 'be', 'more', 'important', 'thing', 'friendship', 'and', 'bravery', 'and', 'oh', 'be', 'careful']]"
},
{
"code": null,
"e": 9841,
"s": 9440,
"text": "The two differences I still have in the process is important is stemmed to import and bravery to braveri. While “braveri” is considerably unambiguous, “import” poses a challenge because it could mean different things. This is why, in general, stemming has poorer performance than lemmatization as it increases search term ambiguities and therefore detects similarities which are not actually similar."
}
] |
Extends vs Implements in Java - GeeksforGeeks | 22 May, 2020
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. There are two main keywords, “extends” and “implements” which are used in Java for inheritance. In this article, the difference between extends and implements is discussed.
Before getting into the differences, lets first understand in what scenarios each of the keywords are used.
Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the subclass. In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can extend only one class to avoid ambiguity.
Example:
class One { public void methodOne() { // Some Functionality }} class Two extends One { public static void main(String args[]) { Two t = new Two(); // Calls the method one // of the above class t.methodOne(); }}
Implements: In Java, the implements keyword is used to implement an interface. An interface is a special type of class which implements a complete abstraction and only contains abstract methods. To access the interface methods, the interface must be “implemented” by another class with the implements keyword and the methods need to be implemented in the class which is inheriting the properties of the interface. Since an interface is not having the implementation of the methods, a class can implement any number of interfaces at a time.
Example
// Defining an interfaceinterface One { public void methodOne();} // Defining the second interfaceinterface Two { public void methodTwo();} // Implementing the two interfacesclass Three implements One, Two { public void methodOne() { // Implementation of the method } public void methodTwo() { // Implementation of the method }}
Note: A class can extend a class and can implement any number of interfaces simultaneously.
Example
// Defining the interfaceinterface One { // Abstract method void methodOne();} // Defining a classclass Two { // Defining a method public void methodTwo() { }} // Class which extends the class Two// and implements the interface Oneclass Three extends Two implements One { public void methodOne() { // Implementation of the method }}
Note: An interface can extend any number of interfaces at a time.
Example:
// Defining the interface Oneinterface One { void methodOne();} // Defining the interface Twointerface Two { void methodTwo();} // Interface extending both the// defined interfacesinterface Three extends One, Two {}
The following table explains the difference between the extends and interface:
java-inheritance
Java-Object Oriented
Articles
Difference Between
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Mutex vs Semaphore
SQL | Views
Time Complexity and Space Complexity
SQL Interview Questions
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java | [
{
"code": null,
"e": 24324,
"s": 24296,
"text": "\n22 May, 2020"
},
{
"code": null,
"e": 24689,
"s": 24324,
"text": "Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. There are two main keywords, “extends” and “implements” which are used in Java for inheritance. In this article, the difference between extends and implements is discussed."
},
{
"code": null,
"e": 24797,
"s": 24689,
"text": "Before getting into the differences, lets first understand in what scenarios each of the keywords are used."
},
{
"code": null,
"e": 25176,
"s": 24797,
"text": "Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the subclass. In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can extend only one class to avoid ambiguity."
},
{
"code": null,
"e": 25185,
"s": 25176,
"text": "Example:"
},
{
"code": "class One { public void methodOne() { // Some Functionality }} class Two extends One { public static void main(String args[]) { Two t = new Two(); // Calls the method one // of the above class t.methodOne(); }}",
"e": 25456,
"s": 25185,
"text": null
},
{
"code": null,
"e": 25996,
"s": 25456,
"text": "Implements: In Java, the implements keyword is used to implement an interface. An interface is a special type of class which implements a complete abstraction and only contains abstract methods. To access the interface methods, the interface must be “implemented” by another class with the implements keyword and the methods need to be implemented in the class which is inheriting the properties of the interface. Since an interface is not having the implementation of the methods, a class can implement any number of interfaces at a time."
},
{
"code": null,
"e": 26004,
"s": 25996,
"text": "Example"
},
{
"code": "// Defining an interfaceinterface One { public void methodOne();} // Defining the second interfaceinterface Two { public void methodTwo();} // Implementing the two interfacesclass Three implements One, Two { public void methodOne() { // Implementation of the method } public void methodTwo() { // Implementation of the method }}",
"e": 26379,
"s": 26004,
"text": null
},
{
"code": null,
"e": 26471,
"s": 26379,
"text": "Note: A class can extend a class and can implement any number of interfaces simultaneously."
},
{
"code": null,
"e": 26479,
"s": 26471,
"text": "Example"
},
{
"code": "// Defining the interfaceinterface One { // Abstract method void methodOne();} // Defining a classclass Two { // Defining a method public void methodTwo() { }} // Class which extends the class Two// and implements the interface Oneclass Three extends Two implements One { public void methodOne() { // Implementation of the method }}",
"e": 26856,
"s": 26479,
"text": null
},
{
"code": null,
"e": 26922,
"s": 26856,
"text": "Note: An interface can extend any number of interfaces at a time."
},
{
"code": null,
"e": 26931,
"s": 26922,
"text": "Example:"
},
{
"code": "// Defining the interface Oneinterface One { void methodOne();} // Defining the interface Twointerface Two { void methodTwo();} // Interface extending both the// defined interfacesinterface Three extends One, Two {}",
"e": 27155,
"s": 26931,
"text": null
},
{
"code": null,
"e": 27234,
"s": 27155,
"text": "The following table explains the difference between the extends and interface:"
},
{
"code": null,
"e": 27251,
"s": 27234,
"text": "java-inheritance"
},
{
"code": null,
"e": 27272,
"s": 27251,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 27281,
"s": 27272,
"text": "Articles"
},
{
"code": null,
"e": 27300,
"s": 27281,
"text": "Difference Between"
},
{
"code": null,
"e": 27305,
"s": 27300,
"text": "Java"
},
{
"code": null,
"e": 27319,
"s": 27305,
"text": "Java Programs"
},
{
"code": null,
"e": 27324,
"s": 27319,
"text": "Java"
},
{
"code": null,
"e": 27422,
"s": 27324,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27431,
"s": 27422,
"text": "Comments"
},
{
"code": null,
"e": 27444,
"s": 27431,
"text": "Old Comments"
},
{
"code": null,
"e": 27497,
"s": 27444,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 27516,
"s": 27497,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 27528,
"s": 27516,
"text": "SQL | Views"
},
{
"code": null,
"e": 27565,
"s": 27528,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 27589,
"s": 27565,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 27620,
"s": 27589,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 27660,
"s": 27620,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 27692,
"s": 27660,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27753,
"s": 27692,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
6 New Awesome Features in Python 3.10 | by Sara A. Metwalli | Towards Data Science | Python is one of the most popular programming languages today. It is used in a wide variety of fields and applications, from learning the basics of computer science to performing complex and straightforward scientific computing tasks to building games. It is even used in advanced areas like data science and quantum computing.
Python gained popularity for many reasons. The two most important ones are how versatile Python is and how relatively easy it is to learn compared to other programming languages. In addition, Python is maintained and developed by the Python Software Foundation, which is always working on new ways to improve Python.
A week ago (Oct 4th, 2021), a new version of Python was released, Python 3.10. In this new version, unique and valuable features were added to Python, while some old features were removed. We can categorize the features added or removed to several categories in any new software release, such as syntax features, add to the default library, or improvements to an existing feature.
towardsdatascience.com
Python 3.10 has several new and cool features that make working with Python an even better experience. In this article, I will share with you 6 new features and add-ons that I am most excited about and glad to see added to Python.
As a person who uses Python every day to write code and teach coding, I am well aware of the frustration of getting a syntax error. Although syntax errors are easy to fix once you get ahold of Python and programming, sometimes we wish for better error messages that can help us locate the error better and save time on debugging.
In Python 3.10, dealing with errors is much better because of two features, better error messages and precise line numbers for debugging. For example, let’s consider the following code, where we have a dictionary and a function. However, in this code, we forgot to close the dictionary.
some_dict = {1: "jack", 2: "john", 3: "james" ,a_results = a_useful_function()
In previous versions of Python, the error message for this would look something like this:
File "amazing_code.py", line 3 a_results = a_useful_function() ^SyntaxError: invalid syntax
But, with the new error messages and line numbering improvement, the new error message will have better information, like the exact type of error and its precise line number.
File "amazing_code.py", line 1 expected = {1: "jack", 2: "john", 3: "james" , ^SyntaxError: '{' was never closed
This new feature will help make debugging much faster and decrease the frustration for people starting to learn Python.
If you have used other programming languages like C++, you may have wished if Python had the switch statement, so you don’t have to go through the long if, elif, elif,...., else statement. Well, one of the new features of Python 3.10 is the addition of what they call the structural pattern matching, or in other words, the switch, case statement which has the following syntax.
match subject: case <patt1>: <act1> case <patt2>: <act2> case <patt3>: <act3> case _: <action_default>
towardsdatascience.com
Although Python is a dynamically typed programming language, there are ways to make some portions of it statically typed. For example, if you’re writing a function and the type of attributes is significant for the commutations inside your function. In previous versions, you could specify the type of an attribute such as:
def func(num: int) -> int: return num + 5
But, if you wanted to accept two types, then you would need to use the Union keyword.
def func(num: Union[int, float]) -> Union[int, float]: return num + 5
In the new version of Python, you can choose between two types, using the | operator instead of Union for a more straightforward type decision.
def func(num: int | float) -> int | float: return num + 5
One of the fun Python functions in Python is the zip() function, which is a built-in function in Python that allows you to combine and iterate over elements from several sequences. In previous versions, you could’ve used zip with sequences of different lengths, but, now, a new parameter strict was introduced to check if all iterables passed to the zip function are of the same length.
towardsdatascience.com
As a programmer, we come across or say the phrase “it works on my machine!”. There are various reasons why a code will work on one machine but not the other; text encoding can cause such an error.
In previous versions of Python, if you don’t explicitly state an encoding type, the preferred local encoding may cause the code to fail on other machines. In Python 3.10, a warning can be activated to inform the user when/ if they open a text file without a specific encoding type.
A powerful and advanced programming paradigm is Asynchronous programming, which has been a part of Python since version 3.5. In Python 3.10, there are two new asynchronous built-in functions aiter() and anext() to make your code more readable.
When I was doing my undergraduate degree, I took several classes where we used C++ or Java to write code and implement applications. But, when it came the time to work on my graduation thesis, I decided to learn and use Python. That was almost a decade ago, and I never looked back; Python has then become my programming language of choice whenever I tackle a problem.
Then, I started teaching computer science to kids, and I realized how Python could inspire the young generation to pursue a career in tech. Aside from the easiness of writing or reading code in Python and how fast you can start implementing code in Python, my favorite thing about this programming language is how hard the Python Software Foundation works to keep Python relevant.
towardsdatascience.com
With every new release of Python, incredible new features are added, features that most of the use has been asking for, features that will make it more efficient for us to write code in Python and make it easier for people to get into programming — in general — and Python — in particular. In this article, I shared with you the 6 new features in Python 3.10 that I am most excited about using with my students. | [
{
"code": null,
"e": 500,
"s": 172,
"text": "Python is one of the most popular programming languages today. It is used in a wide variety of fields and applications, from learning the basics of computer science to performing complex and straightforward scientific computing tasks to building games. It is even used in advanced areas like data science and quantum computing."
},
{
"code": null,
"e": 817,
"s": 500,
"text": "Python gained popularity for many reasons. The two most important ones are how versatile Python is and how relatively easy it is to learn compared to other programming languages. In addition, Python is maintained and developed by the Python Software Foundation, which is always working on new ways to improve Python."
},
{
"code": null,
"e": 1198,
"s": 817,
"text": "A week ago (Oct 4th, 2021), a new version of Python was released, Python 3.10. In this new version, unique and valuable features were added to Python, while some old features were removed. We can categorize the features added or removed to several categories in any new software release, such as syntax features, add to the default library, or improvements to an existing feature."
},
{
"code": null,
"e": 1221,
"s": 1198,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1452,
"s": 1221,
"text": "Python 3.10 has several new and cool features that make working with Python an even better experience. In this article, I will share with you 6 new features and add-ons that I am most excited about and glad to see added to Python."
},
{
"code": null,
"e": 1782,
"s": 1452,
"text": "As a person who uses Python every day to write code and teach coding, I am well aware of the frustration of getting a syntax error. Although syntax errors are easy to fix once you get ahold of Python and programming, sometimes we wish for better error messages that can help us locate the error better and save time on debugging."
},
{
"code": null,
"e": 2069,
"s": 1782,
"text": "In Python 3.10, dealing with errors is much better because of two features, better error messages and precise line numbers for debugging. For example, let’s consider the following code, where we have a dictionary and a function. However, in this code, we forgot to close the dictionary."
},
{
"code": null,
"e": 2148,
"s": 2069,
"text": "some_dict = {1: \"jack\", 2: \"john\", 3: \"james\" ,a_results = a_useful_function()"
},
{
"code": null,
"e": 2239,
"s": 2148,
"text": "In previous versions of Python, the error message for this would look something like this:"
},
{
"code": null,
"e": 2347,
"s": 2239,
"text": "File \"amazing_code.py\", line 3 a_results = a_useful_function() ^SyntaxError: invalid syntax"
},
{
"code": null,
"e": 2522,
"s": 2347,
"text": "But, with the new error messages and line numbering improvement, the new error message will have better information, like the exact type of error and its precise line number."
},
{
"code": null,
"e": 2686,
"s": 2522,
"text": "File \"amazing_code.py\", line 1 expected = {1: \"jack\", 2: \"john\", 3: \"james\" , ^SyntaxError: '{' was never closed"
},
{
"code": null,
"e": 2806,
"s": 2686,
"text": "This new feature will help make debugging much faster and decrease the frustration for people starting to learn Python."
},
{
"code": null,
"e": 3185,
"s": 2806,
"text": "If you have used other programming languages like C++, you may have wished if Python had the switch statement, so you don’t have to go through the long if, elif, elif,...., else statement. Well, one of the new features of Python 3.10 is the addition of what they call the structural pattern matching, or in other words, the switch, case statement which has the following syntax."
},
{
"code": null,
"e": 3328,
"s": 3185,
"text": "match subject: case <patt1>: <act1> case <patt2>: <act2> case <patt3>: <act3> case _: <action_default>"
},
{
"code": null,
"e": 3351,
"s": 3328,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3674,
"s": 3351,
"text": "Although Python is a dynamically typed programming language, there are ways to make some portions of it statically typed. For example, if you’re writing a function and the type of attributes is significant for the commutations inside your function. In previous versions, you could specify the type of an attribute such as:"
},
{
"code": null,
"e": 3719,
"s": 3674,
"text": "def func(num: int) -> int: return num + 5"
},
{
"code": null,
"e": 3805,
"s": 3719,
"text": "But, if you wanted to accept two types, then you would need to use the Union keyword."
},
{
"code": null,
"e": 3878,
"s": 3805,
"text": "def func(num: Union[int, float]) -> Union[int, float]: return num + 5"
},
{
"code": null,
"e": 4022,
"s": 3878,
"text": "In the new version of Python, you can choose between two types, using the | operator instead of Union for a more straightforward type decision."
},
{
"code": null,
"e": 4083,
"s": 4022,
"text": "def func(num: int | float) -> int | float: return num + 5"
},
{
"code": null,
"e": 4470,
"s": 4083,
"text": "One of the fun Python functions in Python is the zip() function, which is a built-in function in Python that allows you to combine and iterate over elements from several sequences. In previous versions, you could’ve used zip with sequences of different lengths, but, now, a new parameter strict was introduced to check if all iterables passed to the zip function are of the same length."
},
{
"code": null,
"e": 4493,
"s": 4470,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4690,
"s": 4493,
"text": "As a programmer, we come across or say the phrase “it works on my machine!”. There are various reasons why a code will work on one machine but not the other; text encoding can cause such an error."
},
{
"code": null,
"e": 4972,
"s": 4690,
"text": "In previous versions of Python, if you don’t explicitly state an encoding type, the preferred local encoding may cause the code to fail on other machines. In Python 3.10, a warning can be activated to inform the user when/ if they open a text file without a specific encoding type."
},
{
"code": null,
"e": 5216,
"s": 4972,
"text": "A powerful and advanced programming paradigm is Asynchronous programming, which has been a part of Python since version 3.5. In Python 3.10, there are two new asynchronous built-in functions aiter() and anext() to make your code more readable."
},
{
"code": null,
"e": 5585,
"s": 5216,
"text": "When I was doing my undergraduate degree, I took several classes where we used C++ or Java to write code and implement applications. But, when it came the time to work on my graduation thesis, I decided to learn and use Python. That was almost a decade ago, and I never looked back; Python has then become my programming language of choice whenever I tackle a problem."
},
{
"code": null,
"e": 5966,
"s": 5585,
"text": "Then, I started teaching computer science to kids, and I realized how Python could inspire the young generation to pursue a career in tech. Aside from the easiness of writing or reading code in Python and how fast you can start implementing code in Python, my favorite thing about this programming language is how hard the Python Software Foundation works to keep Python relevant."
},
{
"code": null,
"e": 5989,
"s": 5966,
"text": "towardsdatascience.com"
}
] |
How to Configure IT Automation Management Using Ansible | This article provides a basic understanding of Ansible technology along with steps to install it. Ansible is an open source IT automation software for configuring, managing and installing software’s on the clients or nodes without any downtime and agent installed on the nodes. It uses SSH to communicate with the clients.
Currently, most of the IT Automation tools runs as an agent in remote host, but Ansible needs only an SSH connection, a user and a Python (2.4 or later).
Server
Operating System: Centos 6.7
IP Address: 192.168.87.140
Host-name: ansible.hanuman.com
User: root
Remote Nodes
Node 1: 192.168.87.156
Node 2: 192.168.87.157
There is no official Ansible repository for RPB based clones, but we can install Ansible by enabling epel repository using RHEL/CentOS 6. X, 7. X using the currently supported fedora distributions.
# rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
Output:
Retrieving http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.no arch.rpm
warning: /var/tmp/rpm-tmp.nHoRHj: Header V3 RSA/SHA256 Signature, key ID 0608b89 5: NOKEY
Preparing... ########################################### [100%]
package epel-release-6-8.noarch is installed
After configuring epel repository, you can now install Ansible using yum with the below command.
# sudo yum install ansible -y
Output:
Loaded plugins: fastestmirror, security
Setting up Install Process
Determining fastest mirrors
epel/metalink | 4.3 kB 00:00
* base: centosmirror.go4hosting.in
* epel: epel.mirror.net.in
* extras: centosmirror.go4hosting.in
* updates: centosmirror.go4hosting.in
Resolving Dependencies
.
.
.
Installed:
ansible.noarch 0:1.9.4-1.el6
Dependency Installed:
PyYAML.x86_64 0:3.10-3.1.el6 libyaml.x86_64 0:0.1.3-4.el6_6
python-babel.noarch 0:0.9.4-5.1.el6 python-crypto2.6.x86_64 0:2.6.1-2.el6
python-httplib2.noarch 0:0.7.7-1.el6 python-jinja2.x86_64 0:2.2.1-2.el6_5
python-keyczar.noarch 0:0.71c-1.el6 python-pyasn1.noarch 0:0.0.12a-1.el6
python-simplejson.x86_64 0:2.0.9-3.1.el6 sshpass.x86_64 0:1.05-1.el6
Complete!
After configuring epel repository, you can now install Ansible using yum with the below command.
# ansible --version
ansible 1.9.4
configured module search path = None
To perform any deployment or up-gradation from the ansible server, for every host, there should be a user account to communicate. Also, we need to copy the ssh keys from the Anisble server to the remote host for password-less connection.
First, let us create an SSH key using the below command and copy the key to remote hosts.
# ssh-keygen -t rsa -b 4096 -C "ansible.hanuman.com"
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in ansible_key.
Your public key has been saved in ansible_key.pub.
The key fingerprint is:
28:ae:0c:8d:91:0a:fa:ac:2f:e2:8c:e5:fd:28:4b:c6 ansible.hanuman.com
The key's randomart image is:
+--[ RSA 4096]----+
| |
| |
| |
| . . |
|+ . . S |
|+= . . |
|= E . |
|=X.o . |
|=*Ooo.. |
+-----------------+
After creating SSH Key success, now copy the created key to all the two remote servers, We need a user to do ansible here for a demo and I am using root user from where we can perform the ansible tasks.
# ssh-copy-id [email protected]
Output:
[email protected]'s password:
Now try logging into the machine, with "ssh '[email protected]'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
# ssh-copy-id [email protected]
Output:
[email protected]'s password:
Now try logging into the machine, with "ssh '[email protected]'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
After copying all SSH Keys to remote host, now perform an ssh key authentication on all remote hosts to check whether authentication working or not run below commands to test.
# ssh [email protected]
[ansible@localhost ~]#
Connection to 192.168.87.156 closed.
# ssh [email protected]
[ansible@localhost ~]#
Inventory file, This file has information about the hosts for which host we need to get connected from local to remote. The default configuration file will be under /etc/ansible/hosts.
Now, we will add the two nodes to configuration file. Open and edit file using your favorite editor, Here we are using vim.
# sudo vim /etc/ansible/hosts
Add the following two hosts IP address..
[webservers]
192.168.87.156
192.168.87.157
Note - [webservers] in the brackets indicates as group names, it is used to classify the nodes and group them and to controlling at what times and for what reason.
Now time to check our all server by just doing a ping from our Ansible server. To perform the action we need to use the command ‘ansible’ with options ‘-m‘ (module) and ‘-all‘ (group of servers).
# ansible -m ping webservers
Output:
[root@localhost ~]# ansible -m ping webservers
192.168.87.157 | success >> {
"changed": false,
"ping": "pong"
}
192.168.87.156 | success >> {
"changed": false,
"ping": "pong"
}
OR
# ansible -m ping -all
Output:
[root@localhost ~]# ansible -m ping webservers
192.168.87.157 | success >> {
"changed": false,
"ping": "pong"
}
192.168.87.156 | success >> {
"changed": false,
"ping": "pong"
}
Now, here we are using another module called ‘command’, which is used to execute a list of shell commands (like, df, free, uptime, etc.) on all selected remote hosts at one go. For demo you can execute the below commands.
# ansible -m command -a "df -h" webservers
Output:
192.168.87.156 | success | rc=0 >>
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root
18G 2.0G 15G 12% /
tmpfs 491M 0 491M 0% /dev/shm
/dev/sda1 477M 42M 411M 10% /boot
192.168.87.157 | success | rc=0 >>
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root
18G 2.0G 15G 12% /
tmpfs 491M 0 491M 0% /dev/shm
/dev/sda1 477M 42M 411M 10% /boot
# ansible -m command -a "free -mt" webservers
Output:
192.168.87.156 | success | rc=0 >>
total used free shared buffers cached
Mem: 981 528 453 0 39 322
-/+ buffers/cache: 166 815
Swap: 2047 0 2047
Total: 3029 528 2501
192.168.87.157 | success | rc=0 >>
total used free shared buffers cached
Mem: 981 526 455 0 39 322
-/+ buffers/cache: 164 817
Swap: 2047 0 2047
Total: 3029 526 2503
# ansible -m shell -a "service httpd status" webservers > service_status.txt
Output:
# cat service_status.txt
192.168.87.156 | FAILED | rc=3 >>
httpd is stopped
192.168.87.157 | FAILED | rc=3 >>
httpd is stopped
#ansible -m shell -a "init 0" webservers
OutPut:
192.168.87.157 | success | rc=0 >>
192.168.87.156 | success | rc=0 >>
Ansible is a Powerful IT automation tool which is mostly used by every Linux Admins for deploying applications and managing servers at one go. Among any other automation tool such as Puppet, Chef, etc., Ansible is quite very interesting and very easy to configure and good for a simple environment. | [
{
"code": null,
"e": 1385,
"s": 1062,
"text": "This article provides a basic understanding of Ansible technology along with steps to install it. Ansible is an open source IT automation software for configuring, managing and installing software’s on the clients or nodes without any downtime and agent installed on the nodes. It uses SSH to communicate with the clients."
},
{
"code": null,
"e": 1539,
"s": 1385,
"text": "Currently, most of the IT Automation tools runs as an agent in remote host, but Ansible needs only an SSH connection, a user and a Python (2.4 or later)."
},
{
"code": null,
"e": 1703,
"s": 1539,
"text": "Server\nOperating System: Centos 6.7\nIP Address: 192.168.87.140\nHost-name: ansible.hanuman.com\nUser: root\nRemote Nodes\nNode 1: 192.168.87.156\nNode 2: 192.168.87.157"
},
{
"code": null,
"e": 1901,
"s": 1703,
"text": "There is no official Ansible repository for RPB based clones, but we can install Ansible by enabling epel repository using RHEL/CentOS 6. X, 7. X using the currently supported fedora distributions."
},
{
"code": null,
"e": 2289,
"s": 1901,
"text": "# rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm\n\nOutput:\n\nRetrieving http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.no arch.rpm\nwarning: /var/tmp/rpm-tmp.nHoRHj: Header V3 RSA/SHA256 Signature, key ID 0608b89 5: NOKEY\nPreparing... ########################################### [100%]\npackage epel-release-6-8.noarch is installed"
},
{
"code": null,
"e": 2386,
"s": 2289,
"text": "After configuring epel repository, you can now install Ansible using yum with the below command."
},
{
"code": null,
"e": 3239,
"s": 2386,
"text": "# sudo yum install ansible -y\n\nOutput:\nLoaded plugins: fastestmirror, security\nSetting up Install Process\nDetermining fastest mirrors\nepel/metalink | 4.3 kB 00:00\n* base: centosmirror.go4hosting.in\n* epel: epel.mirror.net.in\n* extras: centosmirror.go4hosting.in\n* updates: centosmirror.go4hosting.in\nResolving Dependencies\n.\n.\n.\nInstalled:\n ansible.noarch 0:1.9.4-1.el6\nDependency Installed:\n PyYAML.x86_64 0:3.10-3.1.el6 libyaml.x86_64 0:0.1.3-4.el6_6\n python-babel.noarch 0:0.9.4-5.1.el6 python-crypto2.6.x86_64 0:2.6.1-2.el6\n python-httplib2.noarch 0:0.7.7-1.el6 python-jinja2.x86_64 0:2.2.1-2.el6_5\n python-keyczar.noarch 0:0.71c-1.el6 python-pyasn1.noarch 0:0.0.12a-1.el6\n python-simplejson.x86_64 0:2.0.9-3.1.el6 sshpass.x86_64 0:1.05-1.el6\n\nComplete!"
},
{
"code": null,
"e": 3336,
"s": 3239,
"text": "After configuring epel repository, you can now install Ansible using yum with the below command."
},
{
"code": null,
"e": 3410,
"s": 3336,
"text": "# ansible --version\nansible 1.9.4\n configured module search path = None"
},
{
"code": null,
"e": 3648,
"s": 3410,
"text": "To perform any deployment or up-gradation from the ansible server, for every host, there should be a user account to communicate. Also, we need to copy the ssh keys from the Anisble server to the remote host for password-less connection."
},
{
"code": null,
"e": 3738,
"s": 3648,
"text": "First, let us create an SSH key using the below command and copy the key to remote hosts."
},
{
"code": null,
"e": 3791,
"s": 3738,
"text": "# ssh-keygen -t rsa -b 4096 -C \"ansible.hanuman.com\""
},
{
"code": null,
"e": 4365,
"s": 3791,
"text": "Enter file in which to save the key (/root/.ssh/id_rsa):\nEnter passphrase (empty for no passphrase):\nEnter same passphrase again:\nYour identification has been saved in ansible_key.\nYour public key has been saved in ansible_key.pub.\nThe key fingerprint is:\n28:ae:0c:8d:91:0a:fa:ac:2f:e2:8c:e5:fd:28:4b:c6 ansible.hanuman.com\nThe key's randomart image is:\n+--[ RSA 4096]----+\n| |\n| |\n| |\n| . . |\n|+ . . S |\n|+= . . |\n|= E . |\n|=X.o . |\n|=*Ooo.. |\n+-----------------+"
},
{
"code": null,
"e": 4568,
"s": 4365,
"text": "After creating SSH Key success, now copy the created key to all the two remote servers, We need a user to do ansible here for a demo and I am using root user from where we can perform the ansible tasks."
},
{
"code": null,
"e": 5074,
"s": 4568,
"text": "# ssh-copy-id [email protected]\n\nOutput:\n\[email protected]'s password:\nNow try logging into the machine, with \"ssh '[email protected]'\", and check in:\n\n .ssh/authorized_keys\n\nto make sure we haven't added extra keys that you weren't expecting.\n\n# ssh-copy-id [email protected]\n\nOutput:\n\[email protected]'s password:\nNow try logging into the machine, with \"ssh '[email protected]'\", and check in:\n\n .ssh/authorized_keys\nto make sure we haven't added extra keys that you weren't expecting."
},
{
"code": null,
"e": 5250,
"s": 5074,
"text": "After copying all SSH Keys to remote host, now perform an ssh key authentication on all remote hosts to check whether authentication working or not run below commands to test."
},
{
"code": null,
"e": 5385,
"s": 5250,
"text": "# ssh [email protected]\n[ansible@localhost ~]#\nConnection to 192.168.87.156 closed.\n# ssh [email protected]\n[ansible@localhost ~]#"
},
{
"code": null,
"e": 5570,
"s": 5385,
"text": "Inventory file, This file has information about the hosts for which host we need to get connected from local to remote. The default configuration file will be under /etc/ansible/hosts."
},
{
"code": null,
"e": 5694,
"s": 5570,
"text": "Now, we will add the two nodes to configuration file. Open and edit file using your favorite editor, Here we are using vim."
},
{
"code": null,
"e": 5809,
"s": 5694,
"text": "# sudo vim /etc/ansible/hosts\nAdd the following two hosts IP address..\n\n[webservers]\n192.168.87.156\n192.168.87.157"
},
{
"code": null,
"e": 5974,
"s": 5809,
"text": "Note - [webservers] in the brackets indicates as group names, it is used to classify the nodes and group them and to controlling at what times and for what reason."
},
{
"code": null,
"e": 6170,
"s": 5974,
"text": "Now time to check our all server by just doing a ping from our Ansible server. To perform the action we need to use the command ‘ansible’ with options ‘-m‘ (module) and ‘-all‘ (group of servers)."
},
{
"code": null,
"e": 6396,
"s": 6170,
"text": "# ansible -m ping webservers\nOutput:\n[root@localhost ~]# ansible -m ping webservers\n192.168.87.157 | success >> {\n \"changed\": false,\n \"ping\": \"pong\"\n}\n192.168.87.156 | success >> {\n \"changed\": false,\n \"ping\": \"pong\"\n}"
},
{
"code": null,
"e": 6399,
"s": 6396,
"text": "OR"
},
{
"code": null,
"e": 6622,
"s": 6399,
"text": "# ansible -m ping -all\n\nOutput:\n\n[root@localhost ~]# ansible -m ping webservers\n192.168.87.157 | success >> {\n \"changed\": false,\n \"ping\": \"pong\"\n}\n\n192.168.87.156 | success >> {\n \"changed\": false,\n \"ping\": \"pong\"\n}"
},
{
"code": null,
"e": 6844,
"s": 6622,
"text": "Now, here we are using another module called ‘command’, which is used to execute a list of shell commands (like, df, free, uptime, etc.) on all selected remote hosts at one go. For demo you can execute the below commands."
},
{
"code": null,
"e": 7334,
"s": 6844,
"text": "# ansible -m command -a \"df -h\" webservers\n\nOutput:\n\n192.168.87.156 | success | rc=0 >>\nFilesystem Size Used Avail Use% Mounted on\n/dev/mapper/VolGroup-lv_root\n18G 2.0G 15G 12% /\ntmpfs 491M 0 491M 0% /dev/shm\n/dev/sda1 477M 42M 411M 10% /boot\n192.168.87.157 | success | rc=0 >>\nFilesystem Size Used Avail Use% Mounted on\n/dev/mapper/VolGroup-lv_root\n18G 2.0G 15G 12% /\ntmpfs 491M 0 491M 0% /dev/shm\n/dev/sda1 477M 42M 411M 10% /boot"
},
{
"code": null,
"e": 7910,
"s": 7334,
"text": "# ansible -m command -a \"free -mt\" webservers\nOutput:\n192.168.87.156 | success | rc=0 >>\ntotal used free shared buffers cached\nMem: 981 528 453 0 39 322\n-/+ buffers/cache: 166 815\nSwap: 2047 0 2047\nTotal: 3029 528 2501\n192.168.87.157 | success | rc=0 >>\ntotal used free shared buffers cached\nMem: 981 526 455 0 39 322\n-/+ buffers/cache: 164 817\nSwap: 2047 0 2047\nTotal: 3029 526 2503"
},
{
"code": null,
"e": 8124,
"s": 7910,
"text": "# ansible -m shell -a \"service httpd status\" webservers > service_status.txt\n\nOutput:\n\n# cat service_status.txt\n192.168.87.156 | FAILED | rc=3 >>\nhttpd is stopped\n192.168.87.157 | FAILED | rc=3 >>\nhttpd is stopped"
},
{
"code": null,
"e": 8243,
"s": 8124,
"text": "#ansible -m shell -a \"init 0\" webservers\nOutPut:\n192.168.87.157 | success | rc=0 >>\n192.168.87.156 | success | rc=0 >>"
},
{
"code": null,
"e": 8542,
"s": 8243,
"text": "Ansible is a Powerful IT automation tool which is mostly used by every Linux Admins for deploying applications and managing servers at one go. Among any other automation tool such as Puppet, Chef, etc., Ansible is quite very interesting and very easy to configure and good for a simple environment."
}
] |
Add AD authentication to your Dash app | by Erik Petrovski | Towards Data Science | In most organizations, login credentials are managed by a directory service like Active Directory. If you manage to integrate Dash with your organization’s directory service then users can simply log in to your Dash app with their existing credentials. A common way of doing this is by way of LDAP (an open protocol for speaking with directory services like Active Directory) and Flask (a lightweight web application framework). In this post, I’ll demonstrate how to integrate LDAP and FLASK with Dash in Python in — as far as I know — the simplest way possible.
Before getting into any code, you need to have LDAP already up and running. This is a major step that’s out of the scope of this article which only focuses on the Python side of things. If you need AD integration however, I’m assuming that you work in a pretty large organization with its own IT-department and hopefully that department is (1) not you and (2) willing to help!
Assuming LDAP is up and running, go ahead and clone the example code from GitHub by running:
git clone https://github.com/epetrovski/dash_ldap
We also need a few libraries to build a Dash app and make it work with LDAP — four in total. If you already use Pipenv, just run the following in a terminal inside the cloned dash_ldap directory to get a full working virtual environment with dependencies installed:
pipenv sync
If you don’t want to mess with Pipenv, just install the dependencies you need with:
pip install dash flask flask-simpleldap gunicorn
All the code you need is in app.py. Let’s go through it line by line.
The first trick is to make Dash run inside a Flask app that serves your Dash app to the outside world. This is done by passing a Flask object to the Dash app’s server argument at initialization like so:
app = Dash(__name__, server=Flask(__name__))
We then define a Dash app for purpose of example. This app is just a simple placeholder but don’t worry, when you build your own app with advanced callbacks etc., it won’t require any changes to the LDAP integration setup.
app.layout = html.P('Hello world!')
You’ll now need to configure Flask for LDAP by updating Flask’s configuration dictionary. The details below is just a placeholder as your credentials will depend on your company’s LDAP setup — again, ask IT!
app.server.config.update({ 'LDAP_BASE_DN': 'OU=users,dc=example,dc=org', 'LDAP_USERNAME': 'CN=user,OU=Users,DC=example,DC=org', 'LDAP_PASSWORD': os.getenv('LDAP_PASSWORD')})
You may have noticed that I’ve taken the liberty and added the LDAP_PASSWORD with an os.getenv(). I’m assuming that you would never store a password in code but use something like an environment variable instead.
Very importantly, now we need to protect all of Dash’s view functions that have been registered with Flask with an authentication requirement by wrapping them with LDAP(app.server).basic_auth_required():
for view_func in app.server.view_functions: app.server.view_functions[view_func] = LDAP(app.server).basic_auth_required(app.server.view_functions[view_func])
Finally, we may want a way to run the Flask app quickly for testing purposes. Usually we would use app.run() but since the app is served on a Flask server, we use app.run_server():
if __name__ == '__main__': app.run_server()
You can confirm that the AD integration is working by running:
python3 app.py
Now navigate to http://127.0.0.1:8000 and you should see a login prompt. Punch in your credentials and you should see the ‘Hello world!’ frontpage.
Now that you’re pleased with having everything running smoothly, please remember that a crucial part to making this all work is the flask-simpleldap package. It’s one of those great Python packages that just works and solves a very unglamorous but crucial IT need.
If you’re running your Dash app in production, you should be running the app on a production grade http server like gunicorn. You already have this installed, so just run:
gunicorn app:server
This works because in app.py, I’ve defined:
server = app.server
There you go, a login protected Dash app that integrates with a directory service and is fit for production! | [
{
"code": null,
"e": 735,
"s": 172,
"text": "In most organizations, login credentials are managed by a directory service like Active Directory. If you manage to integrate Dash with your organization’s directory service then users can simply log in to your Dash app with their existing credentials. A common way of doing this is by way of LDAP (an open protocol for speaking with directory services like Active Directory) and Flask (a lightweight web application framework). In this post, I’ll demonstrate how to integrate LDAP and FLASK with Dash in Python in — as far as I know — the simplest way possible."
},
{
"code": null,
"e": 1112,
"s": 735,
"text": "Before getting into any code, you need to have LDAP already up and running. This is a major step that’s out of the scope of this article which only focuses on the Python side of things. If you need AD integration however, I’m assuming that you work in a pretty large organization with its own IT-department and hopefully that department is (1) not you and (2) willing to help!"
},
{
"code": null,
"e": 1205,
"s": 1112,
"text": "Assuming LDAP is up and running, go ahead and clone the example code from GitHub by running:"
},
{
"code": null,
"e": 1255,
"s": 1205,
"text": "git clone https://github.com/epetrovski/dash_ldap"
},
{
"code": null,
"e": 1521,
"s": 1255,
"text": "We also need a few libraries to build a Dash app and make it work with LDAP — four in total. If you already use Pipenv, just run the following in a terminal inside the cloned dash_ldap directory to get a full working virtual environment with dependencies installed:"
},
{
"code": null,
"e": 1533,
"s": 1521,
"text": "pipenv sync"
},
{
"code": null,
"e": 1617,
"s": 1533,
"text": "If you don’t want to mess with Pipenv, just install the dependencies you need with:"
},
{
"code": null,
"e": 1666,
"s": 1617,
"text": "pip install dash flask flask-simpleldap gunicorn"
},
{
"code": null,
"e": 1736,
"s": 1666,
"text": "All the code you need is in app.py. Let’s go through it line by line."
},
{
"code": null,
"e": 1939,
"s": 1736,
"text": "The first trick is to make Dash run inside a Flask app that serves your Dash app to the outside world. This is done by passing a Flask object to the Dash app’s server argument at initialization like so:"
},
{
"code": null,
"e": 1984,
"s": 1939,
"text": "app = Dash(__name__, server=Flask(__name__))"
},
{
"code": null,
"e": 2207,
"s": 1984,
"text": "We then define a Dash app for purpose of example. This app is just a simple placeholder but don’t worry, when you build your own app with advanced callbacks etc., it won’t require any changes to the LDAP integration setup."
},
{
"code": null,
"e": 2243,
"s": 2207,
"text": "app.layout = html.P('Hello world!')"
},
{
"code": null,
"e": 2451,
"s": 2243,
"text": "You’ll now need to configure Flask for LDAP by updating Flask’s configuration dictionary. The details below is just a placeholder as your credentials will depend on your company’s LDAP setup — again, ask IT!"
},
{
"code": null,
"e": 2631,
"s": 2451,
"text": "app.server.config.update({ 'LDAP_BASE_DN': 'OU=users,dc=example,dc=org', 'LDAP_USERNAME': 'CN=user,OU=Users,DC=example,DC=org', 'LDAP_PASSWORD': os.getenv('LDAP_PASSWORD')})"
},
{
"code": null,
"e": 2844,
"s": 2631,
"text": "You may have noticed that I’ve taken the liberty and added the LDAP_PASSWORD with an os.getenv(). I’m assuming that you would never store a password in code but use something like an environment variable instead."
},
{
"code": null,
"e": 3048,
"s": 2844,
"text": "Very importantly, now we need to protect all of Dash’s view functions that have been registered with Flask with an authentication requirement by wrapping them with LDAP(app.server).basic_auth_required():"
},
{
"code": null,
"e": 3208,
"s": 3048,
"text": "for view_func in app.server.view_functions: app.server.view_functions[view_func] = LDAP(app.server).basic_auth_required(app.server.view_functions[view_func])"
},
{
"code": null,
"e": 3389,
"s": 3208,
"text": "Finally, we may want a way to run the Flask app quickly for testing purposes. Usually we would use app.run() but since the app is served on a Flask server, we use app.run_server():"
},
{
"code": null,
"e": 3435,
"s": 3389,
"text": "if __name__ == '__main__': app.run_server()"
},
{
"code": null,
"e": 3498,
"s": 3435,
"text": "You can confirm that the AD integration is working by running:"
},
{
"code": null,
"e": 3513,
"s": 3498,
"text": "python3 app.py"
},
{
"code": null,
"e": 3661,
"s": 3513,
"text": "Now navigate to http://127.0.0.1:8000 and you should see a login prompt. Punch in your credentials and you should see the ‘Hello world!’ frontpage."
},
{
"code": null,
"e": 3926,
"s": 3661,
"text": "Now that you’re pleased with having everything running smoothly, please remember that a crucial part to making this all work is the flask-simpleldap package. It’s one of those great Python packages that just works and solves a very unglamorous but crucial IT need."
},
{
"code": null,
"e": 4098,
"s": 3926,
"text": "If you’re running your Dash app in production, you should be running the app on a production grade http server like gunicorn. You already have this installed, so just run:"
},
{
"code": null,
"e": 4118,
"s": 4098,
"text": "gunicorn app:server"
},
{
"code": null,
"e": 4162,
"s": 4118,
"text": "This works because in app.py, I’ve defined:"
},
{
"code": null,
"e": 4182,
"s": 4162,
"text": "server = app.server"
}
] |
JQuery | parseHTML() method - GeeksforGeeks | 27 Apr, 2020
This parseHTML() Method in jQuery is used to parses a string into an array of DOM nodes.
Syntax:
jQuery.parseHTML(data [, context ] [, keepScripts ])
Parameters: The parseXML() method accepts three parameter that is mentioned above and described below:
data: This parameter is the HTML string to be parsed.
context : This parameter is the document element to serve as the context in which the HTML fragment will be created.
keepScripts : This parameter is the boolean indicating whether to include scripts passed in the HTML string.
Example 1: In this example, the parseHTML() Method a string is parsed into an array of DOM nodes.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | parseHTML() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | parseHTML() method</h3> <pre id="geek"> </pre> <script> var $geek = $( "#geek" ), str = "A <b>computer science portal</b> for <b>geeks</b>", html = jQuery.parseHTML( str ), nodeNames = []; $geek.append( html ); </script></body></html>
Output:
Example 2: In this example, the parseHTML() Method create an array of DOM nodes using an HTML string and insert it into a div.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | parseHTML() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | parseHTML() method</h3> <div id="geek"> </div> <script> var $geek = $( "#geek" ), str = "A <b>computer science portal</b> for <b>geeks</b>", html = jQuery.parseHTML( str ), nodeNames = []; $geek.append( html ); $.each( html, function( i, el ) { nodeNames[ i ] = "<li>" + el.nodeName + "</li>"; }); $geek.append( "<h3>Node Names:</h3>" ); $( "<b></b>" ) .append( nodeNames.join( "" ) ) .appendTo( $geek ); </script></body></html>
Output:
jQuery-Methods
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
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": 24759,
"s": 24731,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 24848,
"s": 24759,
"text": "This parseHTML() Method in jQuery is used to parses a string into an array of DOM nodes."
},
{
"code": null,
"e": 24856,
"s": 24848,
"text": "Syntax:"
},
{
"code": null,
"e": 24910,
"s": 24856,
"text": "jQuery.parseHTML(data [, context ] [, keepScripts ])\n"
},
{
"code": null,
"e": 25013,
"s": 24910,
"text": "Parameters: The parseXML() method accepts three parameter that is mentioned above and described below:"
},
{
"code": null,
"e": 25067,
"s": 25013,
"text": "data: This parameter is the HTML string to be parsed."
},
{
"code": null,
"e": 25184,
"s": 25067,
"text": "context : This parameter is the document element to serve as the context in which the HTML fragment will be created."
},
{
"code": null,
"e": 25293,
"s": 25184,
"text": "keepScripts : This parameter is the boolean indicating whether to include scripts passed in the HTML string."
},
{
"code": null,
"e": 25391,
"s": 25293,
"text": "Example 1: In this example, the parseHTML() Method a string is parsed into an array of DOM nodes."
},
{
"code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | parseHTML() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script> </head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | parseHTML() method</h3> <pre id=\"geek\"> </pre> <script> var $geek = $( \"#geek\" ), str = \"A <b>computer science portal</b> for <b>geeks</b>\", html = jQuery.parseHTML( str ), nodeNames = []; $geek.append( html ); </script></body></html> ",
"e": 26066,
"s": 25391,
"text": null
},
{
"code": null,
"e": 26074,
"s": 26066,
"text": "Output:"
},
{
"code": null,
"e": 26201,
"s": 26074,
"text": "Example 2: In this example, the parseHTML() Method create an array of DOM nodes using an HTML string and insert it into a div."
},
{
"code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | parseHTML() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script> </head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | parseHTML() method</h3> <div id=\"geek\"> </div> <script> var $geek = $( \"#geek\" ), str = \"A <b>computer science portal</b> for <b>geeks</b>\", html = jQuery.parseHTML( str ), nodeNames = []; $geek.append( html ); $.each( html, function( i, el ) { nodeNames[ i ] = \"<li>\" + el.nodeName + \"</li>\"; }); $geek.append( \"<h3>Node Names:</h3>\" ); $( \"<b></b>\" ) .append( nodeNames.join( \"\" ) ) .appendTo( $geek ); </script></body></html> ",
"e": 27095,
"s": 26201,
"text": null
},
{
"code": null,
"e": 27103,
"s": 27095,
"text": "Output:"
},
{
"code": null,
"e": 27118,
"s": 27103,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 27125,
"s": 27118,
"text": "JQuery"
},
{
"code": null,
"e": 27142,
"s": 27125,
"text": "Web Technologies"
},
{
"code": null,
"e": 27240,
"s": 27142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27249,
"s": 27240,
"text": "Comments"
},
{
"code": null,
"e": 27262,
"s": 27249,
"text": "Old Comments"
},
{
"code": null,
"e": 27291,
"s": 27262,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27347,
"s": 27291,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 27401,
"s": 27347,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 27469,
"s": 27401,
"text": "How to get the ID of the clicked button using JavaScript / jQuery ?"
},
{
"code": null,
"e": 27503,
"s": 27469,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 27545,
"s": 27503,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27578,
"s": 27545,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27640,
"s": 27578,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27683,
"s": 27640,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Tryit Editor v3.7 | CSS Grid Item
Tryit: Using grid-area to name grid items | [
{
"code": null,
"e": 23,
"s": 9,
"text": "CSS Grid Item"
}
] |
How to compare two columns in an R data frame for an exact match? | Sometimes analysis requires the user to check if values in two columns of an R data frame are exactly the same or not, this is helpful to analyze very large data frames if we suspect the comparative values in two columns. This can be easily done with the help of ifelse function.
Consider the below data frame −
Live Demo
x1<-sample(c("Spring","Winter","Autumn","Summer"),20,replace=TRUE)
y1<-sample(c("Spring","Winter","Autumn","Summer"),20,replace=TRUE)
df1<-data.frame(x1,y1)
df1
x1 y1
1 Spring Autumn
2 Winter Winter
3 Summer Summer
4 Autumn Autumn
5 Summer Autumn
6 Autumn Autumn
7 Summer Winter
8 Spring Spring
9 Summer Spring
10 Winter Winter
11 Autumn Summer
12 Autumn Summer
13 Spring Winter
14 Spring Winter
15 Spring Spring
16 Summer Autumn
17 Spring Winter
18 Winter Summer
19 Summer Spring
20 Spring Autumn
Determining whether each value in x1 and y1 are same or not −
ifelse(df1$x1==df1$y1,"Yes","No")
[1] "No" "Yes" "Yes" "Yes" "No" "Yes" "No" "Yes" "No" "Yes" "No" "No"
[13] "No" "No" "Yes" "No" "No" "No" "No" "No"
Live Demo
x2<-sample(c("Male","Female"),20,replace=TRUE)
y2<-sample(c("Male","Female"),20,replace=TRUE)
df2<-data.frame(x2,y2)
df2
x2 y2
1 Male Female
2 Female Male
3 Female Female
4 Male Male
5 Female Female
6 Male Female
7 Female Female
8 Male Male
9 Male Female
10 Female Female
11 Female Female
12 Male Female
13 Male Male
14 Female Male
15 Male Male
16 Female Female
17 Male Male
18 Female Female
19 Male Female
20 Male Female
Determining whether each value in x2 and y2 are the same or not −
> ifelse(df2$x2==df2$y2,"Yes","No")
[1] "No" "No" "Yes" "Yes" "Yes" "No" "Yes" "Yes" "No" "Yes" "Yes" "No"
[13] "Yes" "No" "Yes" "Yes" "Yes" "Yes" "No" "No" | [
{
"code": null,
"e": 1342,
"s": 1062,
"text": "Sometimes analysis requires the user to check if values in two columns of an R data frame are exactly the same or not, this is helpful to analyze very large data frames if we suspect the comparative values in two columns. This can be easily done with the help of ifelse function."
},
{
"code": null,
"e": 1374,
"s": 1342,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1385,
"s": 1374,
"text": " Live Demo"
},
{
"code": null,
"e": 1546,
"s": 1385,
"text": "x1<-sample(c(\"Spring\",\"Winter\",\"Autumn\",\"Summer\"),20,replace=TRUE)\ny1<-sample(c(\"Spring\",\"Winter\",\"Autumn\",\"Summer\"),20,replace=TRUE)\ndf1<-data.frame(x1,y1)\ndf1"
},
{
"code": null,
"e": 1891,
"s": 1546,
"text": " x1 y1\n1 Spring Autumn\n2 Winter Winter\n3 Summer Summer\n4 Autumn Autumn\n5 Summer Autumn\n6 Autumn Autumn\n7 Summer Winter\n8 Spring Spring\n9 Summer Spring\n10 Winter Winter\n11 Autumn Summer\n12 Autumn Summer\n13 Spring Winter\n14 Spring Winter\n15 Spring Spring\n16 Summer Autumn\n17 Spring Winter\n18 Winter Summer\n19 Summer Spring\n20 Spring Autumn"
},
{
"code": null,
"e": 1953,
"s": 1891,
"text": "Determining whether each value in x1 and y1 are same or not −"
},
{
"code": null,
"e": 1987,
"s": 1953,
"text": "ifelse(df1$x1==df1$y1,\"Yes\",\"No\")"
},
{
"code": null,
"e": 2103,
"s": 1987,
"text": "[1] \"No\" \"Yes\" \"Yes\" \"Yes\" \"No\" \"Yes\" \"No\" \"Yes\" \"No\" \"Yes\" \"No\" \"No\"\n[13] \"No\" \"No\" \"Yes\" \"No\" \"No\" \"No\" \"No\" \"No\""
},
{
"code": null,
"e": 2114,
"s": 2103,
"text": " Live Demo"
},
{
"code": null,
"e": 2235,
"s": 2114,
"text": "x2<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\ny2<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\ndf2<-data.frame(x2,y2)\ndf2"
},
{
"code": null,
"e": 2576,
"s": 2235,
"text": " x2 y2\n1 Male Female\n2 Female Male\n3 Female Female\n4 Male Male\n5 Female Female\n6 Male Female\n7 Female Female\n8 Male Male\n9 Male Female\n10 Female Female\n11 Female Female\n12 Male Female\n13 Male Male\n14 Female Male\n15 Male Male\n16 Female Female\n17 Male Male\n18 Female Female\n19 Male Female\n20 Male Female"
},
{
"code": null,
"e": 2642,
"s": 2576,
"text": "Determining whether each value in x2 and y2 are the same or not −"
},
{
"code": null,
"e": 2678,
"s": 2642,
"text": "> ifelse(df2$x2==df2$y2,\"Yes\",\"No\")"
},
{
"code": null,
"e": 2799,
"s": 2678,
"text": "[1] \"No\" \"No\" \"Yes\" \"Yes\" \"Yes\" \"No\" \"Yes\" \"Yes\" \"No\" \"Yes\" \"Yes\" \"No\"\n[13] \"Yes\" \"No\" \"Yes\" \"Yes\" \"Yes\" \"Yes\" \"No\" \"No\""
}
] |
strace - Unix, Linux Command | strace -c [
-eexpr ]
...
[
-Ooverhead ]
[
-Ssortby ]
[
command [
arg ...
]
]
In the simplest case
strace runs the specified
command until it exits.
It intercepts and records the system calls which are called
by a process and the signals which are received by a process.
The name of each system call, its arguments and its return value
are printed on standard error or to the file specified with the
-o option.
strace is a useful diagnostic, instructional, and debugging tool.
System administrators, diagnosticians and trouble-shooters will find
it invaluable for solving problems with
programs for which the source is not readily available since
they do not need to be recompiled in order to trace them.
Students, hackers and the overly-curious will find that
a great deal can be learned about a system and its system calls by
tracing even ordinary programs. And programmers will find that
since system calls and signals are events that happen at the user/kernel
interface, a close examination of this boundary is very
useful for bug isolation, sanity checking and
attempting to capture race conditions.
Each line in the trace contains the system call name, followed
by its arguments in parentheses and its return value.
An example from stracing the command ‘‘cat /dev/null’’ is:
open("/dev/null", O_RDONLY) = 3
Errors (typically a return value of -1) have the errno symbol
and error string appended.
open("/foo/bar", O_RDONLY) = -1 ENOENT (No such file or directory)
Signals are printed as a signal symbol and a signal string.
An excerpt from stracing and interrupting the command ‘‘sleep 666’’ is:
sigsuspend([] <unfinished ...>
--- SIGINT (Interrupt) ---
+++ killed by SIGINT +++
Arguments are printed in symbolic form with a passion.
This example shows the shell performing ‘‘>>xyzzy’’ output redirection:
open("xyzzy", O_WRONLY|O_APPEND|O_CREAT, 0666) = 3
Here the three argument form of open is decoded by breaking down the
flag argument into its three bitwise-OR constituents and printing the
mode value in octal by tradition. Where traditional or native
usage differs from ANSI or POSIX, the latter forms are preferred.
In some cases,
strace output has proven to be more readable than the source.
Structure pointers are dereferenced and the members are displayed
as appropriate. In all cases arguments are formatted in the most C-like
fashion possible.
For example, the essence of the command ‘‘ls -l /dev/null’’ is captured as:
lstat("/dev/null", {st_mode=S_IFCHR|0666, st_rdev=makedev(1, 3), ...}) = 0
Notice how the ‘struct stat’ argument is dereferenced and how each member is
displayed symbolically. In particular, observe how the st_mode member
is carefully decoded into a bitwise-OR of symbolic and numeric values.
Also notice in this example that the first argument to lstat is an input
to the system call and the second argument is an output. Since output
arguments are not modified if the system call fails, arguments may not
always be dereferenced. For example, retrying the ‘‘ls -l’’ example
with a non-existent file produces the following line:
lstat("/foo/bar", 0xb004) = -1 ENOENT (No such file or directory)
In this case the porch light is on but nobody is home.
Character pointers are dereferenced and printed as C strings.
Non-printing characters in strings are normally represented by
ordinary C escape codes.
Only the first
strsize (32 by default) bytes of strings are printed;
longer strings have an ellipsis appended following the closing quote.
Here is a line from ‘‘ls -l’’ where the
getpwuid library routine is reading the password file:
read(3, "root::0:0:System Administrator:/"..., 1024) = 422
While structures are annotated using curly braces, simple pointers
and arrays are printed using square brackets with commas separating
elements. Here is an example from the command ‘‘id’’ on a system with
supplementary group ids:
getgroups(32, [100, 0]) = 2
On the other hand, bit-sets are also shown using square brackets
but set elements are separated only by a space. Here is the shell
preparing to execute an external command:
sigprocmask(SIG_BLOCK, [CHLD TTOU], []) = 0
Here the second argument is a bit-set of two signals, SIGCHLD and SIGTTOU.
In some cases the bit-set is so full that printing out the unset
elements is more valuable. In that case, the bit-set is prefixed by
a tilde like this:
sigprocmask(SIG_UNBLOCK, ~[], NULL) = 0
Here the second argument represents the full set of all signals.
ltrace (1)
ltrace (1)
time (1)
time (1)
ptrace (2)
ptrace (2)
It is instructive to think about system call inputs and outputs
as data-flow across the user/kernel boundary. Because user-space
and kernel-space are separate and address-protected, it is
sometimes possible to make deductive inferences about process
behavior using inputs and outputs as propositions.
In some cases, a system call will differ from the documented behavior
or have a different name. For example, on System V-derived systems
the true
time(2)
system call does not take an argument and the
stat function is called
xstat and takes an extra leading argument. These
discrepancies are normal but idiosyncratic characteristics of the
system call interface and are accounted for by C library wrapper
functions.
On some platforms a process that has a system call trace applied
to it with the
-p option will receive a
SIGSTOP. This signal may interrupt a system call that is not restartable.
This may have an unpredictable effect on the process
if the process takes no action to restart the system call.
A traced process ignores
SIGSTOP except on SVR4 platforms.
A traced process which tries to block SIGTRAP will be sent a SIGSTOP
in an attempt to force continuation of tracing.
A traced process runs slowly.
Traced processes which are descended from
command may be left running after an interrupt signal (
CTRL-C).
On Linux, exciting as it would be, tracing the init process is forbidden.
The
-i option is weakly supported.
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10656,
"s": 10577,
"text": "\nstrace -c [\n-eexpr ]\n...\n[\n-Ooverhead ]\n[\n-Ssortby ]\n[\ncommand [\narg ...\n]\n]\n"
},
{
"code": null,
"e": 10991,
"s": 10656,
"text": "\nIn the simplest case\nstrace runs the specified\ncommand until it exits.\nIt intercepts and records the system calls which are called\nby a process and the signals which are received by a process.\nThe name of each system call, its arguments and its return value\nare printed on standard error or to the file specified with the\n-o option.\n"
},
{
"code": null,
"e": 11688,
"s": 10991,
"text": "\nstrace is a useful diagnostic, instructional, and debugging tool.\nSystem administrators, diagnosticians and trouble-shooters will find\nit invaluable for solving problems with\nprograms for which the source is not readily available since\nthey do not need to be recompiled in order to trace them.\nStudents, hackers and the overly-curious will find that\na great deal can be learned about a system and its system calls by\ntracing even ordinary programs. And programmers will find that\nsince system calls and signals are events that happen at the user/kernel\ninterface, a close examination of this boundary is very\nuseful for bug isolation, sanity checking and\nattempting to capture race conditions.\n"
},
{
"code": null,
"e": 11866,
"s": 11688,
"text": "\nEach line in the trace contains the system call name, followed\nby its arguments in parentheses and its return value.\nAn example from stracing the command ‘‘cat /dev/null’’ is:\n"
},
{
"code": null,
"e": 11901,
"s": 11868,
"text": "open(\"/dev/null\", O_RDONLY) = 3\n"
},
{
"code": null,
"e": 11992,
"s": 11901,
"text": "\nErrors (typically a return value of -1) have the errno symbol\nand error string appended.\n"
},
{
"code": null,
"e": 12062,
"s": 11994,
"text": "open(\"/foo/bar\", O_RDONLY) = -1 ENOENT (No such file or directory)\n"
},
{
"code": null,
"e": 12196,
"s": 12062,
"text": "\nSignals are printed as a signal symbol and a signal string.\nAn excerpt from stracing and interrupting the command ‘‘sleep 666’’ is:\n"
},
{
"code": null,
"e": 12282,
"s": 12198,
"text": "sigsuspend([] <unfinished ...>\n--- SIGINT (Interrupt) ---\n+++ killed by SIGINT +++\n"
},
{
"code": null,
"e": 12411,
"s": 12282,
"text": "\nArguments are printed in symbolic form with a passion.\nThis example shows the shell performing ‘‘>>xyzzy’’ output redirection:\n"
},
{
"code": null,
"e": 12465,
"s": 12413,
"text": "open(\"xyzzy\", O_WRONLY|O_APPEND|O_CREAT, 0666) = 3\n"
},
{
"code": null,
"e": 12812,
"s": 12465,
"text": "\nHere the three argument form of open is decoded by breaking down the\nflag argument into its three bitwise-OR constituents and printing the\nmode value in octal by tradition. Where traditional or native\nusage differs from ANSI or POSIX, the latter forms are preferred.\nIn some cases,\nstrace output has proven to be more readable than the source.\n"
},
{
"code": null,
"e": 13047,
"s": 12812,
"text": "\nStructure pointers are dereferenced and the members are displayed\nas appropriate. In all cases arguments are formatted in the most C-like\nfashion possible.\nFor example, the essence of the command ‘‘ls -l /dev/null’’ is captured as:\n"
},
{
"code": null,
"e": 13125,
"s": 13049,
"text": "lstat(\"/dev/null\", {st_mode=S_IFCHR|0666, st_rdev=makedev(1, 3), ...}) = 0\n"
},
{
"code": null,
"e": 13684,
"s": 13125,
"text": "\nNotice how the ‘struct stat’ argument is dereferenced and how each member is\ndisplayed symbolically. In particular, observe how the st_mode member\nis carefully decoded into a bitwise-OR of symbolic and numeric values.\nAlso notice in this example that the first argument to lstat is an input\nto the system call and the second argument is an output. Since output\narguments are not modified if the system call fails, arguments may not\nalways be dereferenced. For example, retrying the ‘‘ls -l’’ example\nwith a non-existent file produces the following line:\n"
},
{
"code": null,
"e": 13753,
"s": 13686,
"text": "lstat(\"/foo/bar\", 0xb004) = -1 ENOENT (No such file or directory)\n"
},
{
"code": null,
"e": 13810,
"s": 13753,
"text": "\nIn this case the porch light is on but nobody is home.\n"
},
{
"code": null,
"e": 14196,
"s": 13810,
"text": "\nCharacter pointers are dereferenced and printed as C strings.\nNon-printing characters in strings are normally represented by\nordinary C escape codes.\nOnly the first\nstrsize (32 by default) bytes of strings are printed;\nlonger strings have an ellipsis appended following the closing quote.\nHere is a line from ‘‘ls -l’’ where the\ngetpwuid library routine is reading the password file:\n"
},
{
"code": null,
"e": 14258,
"s": 14198,
"text": "read(3, \"root::0:0:System Administrator:/\"..., 1024) = 422\n"
},
{
"code": null,
"e": 14491,
"s": 14258,
"text": "\nWhile structures are annotated using curly braces, simple pointers\nand arrays are printed using square brackets with commas separating\nelements. Here is an example from the command ‘‘id’’ on a system with\nsupplementary group ids:\n"
},
{
"code": null,
"e": 14522,
"s": 14493,
"text": "getgroups(32, [100, 0]) = 2\n"
},
{
"code": null,
"e": 14698,
"s": 14522,
"text": "\nOn the other hand, bit-sets are also shown using square brackets\nbut set elements are separated only by a space. Here is the shell\npreparing to execute an external command:\n"
},
{
"code": null,
"e": 14745,
"s": 14700,
"text": "sigprocmask(SIG_BLOCK, [CHLD TTOU], []) = 0\n"
},
{
"code": null,
"e": 14975,
"s": 14745,
"text": "\nHere the second argument is a bit-set of two signals, SIGCHLD and SIGTTOU.\nIn some cases the bit-set is so full that printing out the unset\nelements is more valuable. In that case, the bit-set is prefixed by\na tilde like this:\n"
},
{
"code": null,
"e": 15018,
"s": 14977,
"text": "sigprocmask(SIG_UNBLOCK, ~[], NULL) = 0\n"
},
{
"code": null,
"e": 15085,
"s": 15018,
"text": "\nHere the second argument represents the full set of all signals.\n"
},
{
"code": null,
"e": 15096,
"s": 15085,
"text": "ltrace (1)"
},
{
"code": null,
"e": 15107,
"s": 15096,
"text": "ltrace (1)"
},
{
"code": null,
"e": 15116,
"s": 15107,
"text": "time (1)"
},
{
"code": null,
"e": 15125,
"s": 15116,
"text": "time (1)"
},
{
"code": null,
"e": 15136,
"s": 15125,
"text": "ptrace (2)"
},
{
"code": null,
"e": 15147,
"s": 15136,
"text": "ptrace (2)"
},
{
"code": null,
"e": 15451,
"s": 15147,
"text": "\nIt is instructive to think about system call inputs and outputs\nas data-flow across the user/kernel boundary. Because user-space\nand kernel-space are separate and address-protected, it is\nsometimes possible to make deductive inferences about process\nbehavior using inputs and outputs as propositions.\n"
},
{
"code": null,
"e": 15870,
"s": 15451,
"text": "\nIn some cases, a system call will differ from the documented behavior\nor have a different name. For example, on System V-derived systems\nthe true\ntime(2)\nsystem call does not take an argument and the\nstat function is called\nxstat and takes an extra leading argument. These\ndiscrepancies are normal but idiosyncratic characteristics of the\nsystem call interface and are accounted for by C library wrapper\nfunctions.\n"
},
{
"code": null,
"e": 16163,
"s": 15870,
"text": "\nOn some platforms a process that has a system call trace applied\nto it with the\n-p option will receive a\nSIGSTOP. This signal may interrupt a system call that is not restartable.\nThis may have an unpredictable effect on the process\nif the process takes no action to restart the system call.\n"
},
{
"code": null,
"e": 16224,
"s": 16163,
"text": "\nA traced process ignores\nSIGSTOP except on SVR4 platforms.\n"
},
{
"code": null,
"e": 16343,
"s": 16224,
"text": "\nA traced process which tries to block SIGTRAP will be sent a SIGSTOP\nin an attempt to force continuation of tracing.\n"
},
{
"code": null,
"e": 16375,
"s": 16343,
"text": "\nA traced process runs slowly.\n"
},
{
"code": null,
"e": 16484,
"s": 16375,
"text": "\nTraced processes which are descended from\ncommand may be left running after an interrupt signal (\nCTRL-C). "
},
{
"code": null,
"e": 16560,
"s": 16484,
"text": "\nOn Linux, exciting as it would be, tracing the init process is forbidden.\n"
},
{
"code": null,
"e": 16597,
"s": 16560,
"text": "\nThe\n-i option is weakly supported.\n"
},
{
"code": null,
"e": 16614,
"s": 16597,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 16649,
"s": 16614,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 16677,
"s": 16649,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 16711,
"s": 16677,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 16728,
"s": 16711,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 16761,
"s": 16728,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 16772,
"s": 16761,
"text": " Pradeep D"
},
{
"code": null,
"e": 16807,
"s": 16772,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 16823,
"s": 16807,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 16856,
"s": 16823,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 16868,
"s": 16856,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 16900,
"s": 16868,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 16908,
"s": 16900,
"text": " Uplatz"
},
{
"code": null,
"e": 16915,
"s": 16908,
"text": " Print"
},
{
"code": null,
"e": 16926,
"s": 16915,
"text": " Add Notes"
}
] |
MySQL query to set current date in the datetime field for all the column values | Let us first create a table −
mysql> create table DemoTable821(AdmissionDate datetime);
Query OK, 0 rows affected (1.24 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable821 values('2019-01-21');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable821 values('2018-11-02');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable821 values('2016-12-31');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable821 values('2015-03-19');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable821;
This will produce the following output −
+---------------------+
| AdmissionDate |
+---------------------+
| 2019-01-21 00:00:00 |
| 2018-11-02 00:00:00 |
| 2016-12-31 00:00:00 |
| 2015-03-19 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)
Here is the query to set current date in the DateTime field −
mysql> update DemoTable821 set AdmissionDate=CURDATE();
Query OK, 4 rows affected (0.74 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable821;
This will produce the following output −
+---------------------+
| AdmissionDate |
+---------------------+
| 2019-08-03 00:00:00 |
| 2019-08-03 00:00:00 |
| 2019-08-03 00:00:00 |
| 2019-08-03 00:00:00 |
+---------------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1187,
"s": 1092,
"text": "mysql> create table DemoTable821(AdmissionDate datetime);\nQuery OK, 0 rows affected (1.24 sec)"
},
{
"code": null,
"e": 1243,
"s": 1187,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1603,
"s": 1243,
"text": "mysql> insert into DemoTable821 values('2019-01-21');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable821 values('2018-11-02');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable821 values('2016-12-31');\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into DemoTable821 values('2015-03-19');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1663,
"s": 1603,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1697,
"s": 1663,
"text": "mysql> select *from DemoTable821;"
},
{
"code": null,
"e": 1738,
"s": 1697,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1955,
"s": 1738,
"text": "+---------------------+\n| AdmissionDate |\n+---------------------+\n| 2019-01-21 00:00:00 |\n| 2018-11-02 00:00:00 |\n| 2016-12-31 00:00:00 |\n| 2015-03-19 00:00:00 |\n+---------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2017,
"s": 1955,
"text": "Here is the query to set current date in the DateTime field −"
},
{
"code": null,
"e": 2149,
"s": 2017,
"text": "mysql> update DemoTable821 set AdmissionDate=CURDATE();\nQuery OK, 4 rows affected (0.74 sec)\nRows matched: 4 Changed: 4 Warnings: 0"
},
{
"code": null,
"e": 2189,
"s": 2149,
"text": "Let us check table records once again −"
},
{
"code": null,
"e": 2223,
"s": 2189,
"text": "mysql> select *from DemoTable821;"
},
{
"code": null,
"e": 2264,
"s": 2223,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2481,
"s": 2264,
"text": "+---------------------+\n| AdmissionDate |\n+---------------------+\n| 2019-08-03 00:00:00 |\n| 2019-08-03 00:00:00 |\n| 2019-08-03 00:00:00 |\n| 2019-08-03 00:00:00 |\n+---------------------+\n4 rows in set (0.00 sec)"
}
] |
MS SQL Server - Drop Database | To remove your database from MS SQL Server, use drop database command. Following two methods can be used for this purpose.
Following is the basic syntax for removing database from MS SQL Server.
Drop database <your database name>
To remove database name ‘Testdb’, run the following query.
Drop database Testdb
Connect to SQL Server and right-click the database you want to remove. Click delete command and the following screen will appear.
Click OK to remove the database (in this example, the name is Testdb as shown in the above screen) from MS SQL Server.
32 Lectures
2.5 hours
Pavan Lalwani
18 Lectures
1.5 hours
Dr. Saatya Prasad
102 Lectures
10 hours
Pavan Lalwani
52 Lectures
4 hours
Pavan Lalwani
239 Lectures
33 hours
Gowthami Swarna
53 Lectures
5 hours
Akshay Magre
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2358,
"s": 2235,
"text": "To remove your database from MS SQL Server, use drop database command. Following two methods can be used for this purpose."
},
{
"code": null,
"e": 2430,
"s": 2358,
"text": "Following is the basic syntax for removing database from MS SQL Server."
},
{
"code": null,
"e": 2466,
"s": 2430,
"text": "Drop database <your database name>\n"
},
{
"code": null,
"e": 2525,
"s": 2466,
"text": "To remove database name ‘Testdb’, run the following query."
},
{
"code": null,
"e": 2547,
"s": 2525,
"text": "Drop database Testdb\n"
},
{
"code": null,
"e": 2677,
"s": 2547,
"text": "Connect to SQL Server and right-click the database you want to remove. Click delete command and the following screen will appear."
},
{
"code": null,
"e": 2796,
"s": 2677,
"text": "Click OK to remove the database (in this example, the name is Testdb as shown in the above screen) from MS SQL Server."
},
{
"code": null,
"e": 2831,
"s": 2796,
"text": "\n 32 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2846,
"s": 2831,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 2881,
"s": 2846,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2900,
"s": 2881,
"text": " Dr. Saatya Prasad"
},
{
"code": null,
"e": 2935,
"s": 2900,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 2950,
"s": 2935,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 2983,
"s": 2950,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2998,
"s": 2983,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3033,
"s": 2998,
"text": "\n 239 Lectures \n 33 hours \n"
},
{
"code": null,
"e": 3050,
"s": 3033,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 3083,
"s": 3050,
"text": "\n 53 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3097,
"s": 3083,
"text": " Akshay Magre"
},
{
"code": null,
"e": 3104,
"s": 3097,
"text": " Print"
},
{
"code": null,
"e": 3115,
"s": 3104,
"text": " Add Notes"
}
] |
Getter and Setter in Python | For the purpose of data encapsulation, most object oriented languages use getters and setters method. This is because we want to hide the attributes of a object class from other classes so that no accidental modification of the data happens by methods in other classes.
As the name suggests, getters are the methods which help access the private attributes or get the value of the private attributes and setters are the methods which help change or set the value of private attributes.
Below we write code to create a class, initialize it and access it variables without creating any additional methods.
class year_graduated:
def __init__(self, year=0):
self._year = year
# Instantiating the class
grad_obj = year_graduated()
#Printing the object
print(grad_obj)
#Printing the object attribute
print(grad_obj.year)
Running the above code gives us the following result -
<__main__.year_graduated object at 0x00F2DD50>
0
While the first print statement gives us the details of the object created, the second print object gives us the default value of the private attribute.
In the below examples we will make a class, initialize is and then add a getter and setter method to each of them. Then access the variables in these methods by instantiating the class and using these getter and setter methods. So you can hide your logic inside the setter method.
Live Demo
class year_graduated:
def __init__(self, year=0):
self._year = year
# getter method
def get_year(self):
return self._year
# setter method
def set_year(self, a):
self._year = a
grad_obj = year_graduated()
# Before using setter
print(grad_obj.get_year())
# After using setter
grad_obj.set_year(2019)
print(grad_obj._year)
Running the above code gives us the following result:
0
2019
In the next example we see how to make the methods private so that the variables in it cannot be manipulated by external calling functions. They can only be manipulated by functions inside the class. They become private by prefixing them with two underscores.
Live Demo
class year_graduated:
def __init__(self, year=32):
self._year = year
# make the getter method
def get_year(self):
return self.__year
# make the setter method
def set_year(self, a):
self.__year = a
grad_obj = year_graduated()
print(grad_obj._year)
# Before using setter
print(grad_obj.get_year())
#
# # After using setter
grad_obj.set_year(2019)
print(grad_obj._year)
Running the above code gives us the following result:
32
AttributeError: 'year_graduated' object has no attribute '_year_graduated__year'
No we can access the private attribute values by using the property method and without using the getter method.
Live Demo
class year_graduated:
def __init__(self, year=32):
self._year = year
@property
def Aboutyear(self):
return self.__year
@Aboutyear.setter
def Aboutyear(self, a):
self.__year = a
grad_obj = year_graduated()
print(grad_obj._year)
grad_obj.year = 2018
print(grad_obj.year)
Running the above code gives us the following result:
32
2018 | [
{
"code": null,
"e": 1332,
"s": 1062,
"text": "For the purpose of data encapsulation, most object oriented languages use getters and setters method. This is because we want to hide the attributes of a object class from other classes so that no accidental modification of the data happens by methods in other classes."
},
{
"code": null,
"e": 1548,
"s": 1332,
"text": "As the name suggests, getters are the methods which help access the private attributes or get the value of the private attributes and setters are the methods which help change or set the value of private attributes."
},
{
"code": null,
"e": 1666,
"s": 1548,
"text": "Below we write code to create a class, initialize it and access it variables without creating any additional methods."
},
{
"code": null,
"e": 1887,
"s": 1666,
"text": "class year_graduated:\n def __init__(self, year=0):\n self._year = year\n\n# Instantiating the class\ngrad_obj = year_graduated()\n#Printing the object\nprint(grad_obj)\n#Printing the object attribute\nprint(grad_obj.year)"
},
{
"code": null,
"e": 1942,
"s": 1887,
"text": "Running the above code gives us the following result -"
},
{
"code": null,
"e": 1991,
"s": 1942,
"text": "<__main__.year_graduated object at 0x00F2DD50>\n0"
},
{
"code": null,
"e": 2144,
"s": 1991,
"text": "While the first print statement gives us the details of the object created, the second print object gives us the default value of the private attribute."
},
{
"code": null,
"e": 2425,
"s": 2144,
"text": "In the below examples we will make a class, initialize is and then add a getter and setter method to each of them. Then access the variables in these methods by instantiating the class and using these getter and setter methods. So you can hide your logic inside the setter method."
},
{
"code": null,
"e": 2436,
"s": 2425,
"text": " Live Demo"
},
{
"code": null,
"e": 2781,
"s": 2436,
"text": "class year_graduated:\n def __init__(self, year=0):\n self._year = year\n\n # getter method\n def get_year(self):\n return self._year\n\n# setter method\ndef set_year(self, a):\nself._year = a\n\ngrad_obj = year_graduated()\n# Before using setter\nprint(grad_obj.get_year())\n\n# After using setter\ngrad_obj.set_year(2019)\nprint(grad_obj._year)"
},
{
"code": null,
"e": 2835,
"s": 2781,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 2842,
"s": 2835,
"text": "0\n2019"
},
{
"code": null,
"e": 3102,
"s": 2842,
"text": "In the next example we see how to make the methods private so that the variables in it cannot be manipulated by external calling functions. They can only be manipulated by functions inside the class. They become private by prefixing them with two underscores."
},
{
"code": null,
"e": 3113,
"s": 3102,
"text": " Live Demo"
},
{
"code": null,
"e": 3517,
"s": 3113,
"text": "class year_graduated:\n def __init__(self, year=32):\n self._year = year\n\n # make the getter method\n def get_year(self):\n return self.__year\n\n # make the setter method\n def set_year(self, a):\n self.__year = a\n\ngrad_obj = year_graduated()\nprint(grad_obj._year)\n\n# Before using setter\nprint(grad_obj.get_year())\n#\n# # After using setter\ngrad_obj.set_year(2019)\nprint(grad_obj._year)"
},
{
"code": null,
"e": 3571,
"s": 3517,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 3655,
"s": 3571,
"text": "32\nAttributeError: 'year_graduated' object has no attribute '_year_graduated__year'"
},
{
"code": null,
"e": 3767,
"s": 3655,
"text": "No we can access the private attribute values by using the property method and without using the getter method."
},
{
"code": null,
"e": 3778,
"s": 3767,
"text": " Live Demo"
},
{
"code": null,
"e": 4084,
"s": 3778,
"text": "class year_graduated:\n def __init__(self, year=32):\n self._year = year\n\n @property\n def Aboutyear(self):\n return self.__year\n\n @Aboutyear.setter\n def Aboutyear(self, a):\n self.__year = a\n\ngrad_obj = year_graduated()\nprint(grad_obj._year)\n\ngrad_obj.year = 2018\nprint(grad_obj.year)"
},
{
"code": null,
"e": 4138,
"s": 4084,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 4146,
"s": 4138,
"text": "32\n2018"
}
] |
Serverless - Layer Creation | Layers are a way of isolating code blocks. Say you want to import the NumPy library in your application. You trust the library and there's hardly any chance that you will be making changes in the source code of that library. Therefore, you won't like it if the source code of NumPy clutters your application workspace. Speaking very crudely, you would simply want NumPy to sit somewhere else, isolated from your application code. Layers allow you to do exactly that. You can simply bundle all your dependencies (NumPy, Pandas, SciPy, etc.) in a separate layer, and then simply reference that layer in your lambda function within serverless. And boom! All the libraries bundled within that layer can now be imported into your application. At the same time, your application workspace remains completely uncluttered. You simply see the application code to edit.
Photo by Iva Rajovic on Unsplash, indicative of code separation in layers
The really cool thing about layers is that they can be shared across functions. Say you deployed a lambda function with a python-requirements layer that contains NumPy and Pandas. Now, if another lambda function requires NumPy, you need not deploy a separate layer for this function. You can simply use the layer of the previous function and it will work well with the new function as well.
This will save you a lot of precious time during deployment. After all, you will be deploying only the application code. The dependencies are already present in an existing layer. Therefore,several developers keep the dependencies layer in a separate stack. They then use this layer in all other applications. This way, they don't need to deploy the dependencies again and again. After all, the dependencies are quite heavy. NumPy library itself is approx. 80 MB large. Deploying dependencies every time you make changes to your application code (which may measure just a few KBs) will be quite inconvenient.
And adding a dependencies layer is just one example. There are several other use-cases. For example, the example given on serverless.com concerns the creation of GIFs using the FFmpeg tool. In that example, they have stored the FFmpeg tool in a layer. In all, AWS Lambda allows us to add a maximum of 5 layers per function. The only condition is that the total size of the 5 layers and the application should be less than 250 MB.
Now let's see how the layer containing all the dependencies can be created and deployed using serverless. To do that, we need the serverless-python-requirements plugin.This plugin only works with Serverless 1.34 and above. So you may want to upgrade your Serverless version if you have a version <1.34. You can install the plugin using −
sls plugin install -n serverless-python-requirements
Next, you add this plugin in the plugins section of your serverless.yml, and mention it's configurations in the custom section −
plugins:
- serverless-python-requirements
custom:
pythonRequirements:
dockerizePip: true
layer: true
Over here, dockerizePip − true enables the usage of docker and allows you to package all the dependencies in a docker container. We've discussed about packaging using docker in the previous chapter. layer − true tells serverless that the python requirements should be stored in a separate layer. Now, at this point, you may be wondering that how does serverless understand which dependencies to package? The answer, as mentioned in the plugins chapter, lies in the requirements.txt file.
Once the layer plugin and custom configurations have been defined, you can add the layer to your individual functions within serverless as follows −
functions:
hello:
handler: handler.hello
layers:
- { Ref: PythonRequirementsLambdaLayer }
The keyword PythonRequirementsLambdaLayer comes from the CloudFormation Reference.In general, it is derived from the layer's name. The syntax is 'LayerNameLambdaLayer' (TitleCased, without spaces). In our case, since the layer name is python requirements, the reference becomes PythonRequirementsLambdaLayer. If you aren't sure about the name of your lambda layer, you can get it in the following steps −
Run sls package
Run sls package
Open .serverless/cloudformation-template-update-stack.json
Open .serverless/cloudformation-template-update-stack.json
Search for 'LambdaLayer'
Search for 'LambdaLayer'
Like I mentioned in the beginning, a really cool thing about layers is the ability to use existing layers in your function. This can be done easily by using the ARN of your existing layer.The syntax to add an existing layer to a function using the ARN is quite straightforward −
functions:
hello:
handler: handler.hello
layers:
- arn:aws:lambda:region:XXXXXX:layer:LayerName:Y
That's it. Now the layer with the specified ARN will work with your function. If the layer contains the NumPy library, you can simply go ahead and call import numpy in your 'hello' function. It will run without any error.
If you are wondering from where you can get the ARN, it is quite simple actually. Simply navigate to the function containing the layer in the AWS Console, and click on 'Layers'.
Of course, if the layer doesn't belong to your account, then it either needs to be publicly shared or shared specifically with your account. More on that later.
Also, keep in mind that the layer should be compatible with your application. Don't expect a layer compatible with node.js runtime to run with a function created in python3.6 runtime.
As mentioned in the beginning, the layers serve the main function of isolating your code blocks. Therefore, they don't need to contain just dependencies. They can contain any piece of code that you specify. Calling layer: true within pythonRequirements within custom is a kind of a shortcut made possible by the serverless-python-requirements plugin. However, to create a generic layer, the syntax within serverless.yml, as explained in the serverless docs, is as follows −
layers:
hello:
path: layer-dir # required, path to layer contents on disk
name: ${opt:stage, self:provider.stage, 'dev'}-layerName # optional, Deployed Lambda layer name
description: Description of what the lambda layer does # optional, Description to publish to AWS
compatibleRuntimes: # optional, a list of runtimes this layer is compatible with
- python3.8
licenseInfo: GPLv3 # optional, a string specifying license information
# allowedAccounts: # optional, a list of AWS account IDs allowed to access this layer.
# - '*'
# note: uncommenting this will give all AWS users access to this layer unconditionally.
retain: false # optional, false by default. If true, layer versions are not deleted as new ones are created
The various configuration parameters are self-explanatory thanks to the comments provided. Except for the 'path', all other properties are optional. The path property is a path to a directory of your choice that you want to be isolated from your application code. It will be zipped up and published as your layer. For instance, in the example project on serverless, where they host the FFmpeg tool in a layer, they download the tool in a separate folder called 'layer' and specify that in the path property.
layers:
ffmpeg:
path: layer
As told before, we can add up to 5 layers within the layers − property.
To use these generic layers in your functions, again, you can use either the CloudFormation reference or specify the ARN.
More accounts can be provided access to your layer by simply mentioning the account numbers in the 'allowedAccounts' property. For example −
layers:
testLayer:
path: testLayer
allowedAccounts:
- 999999999999 # a specific account ID
- 000123456789 # a different specific account ID
If you want the layer to be publicly accessible, you can add '*' in allowedAccounts −
layers:
testLayer:
path: testLayer
allowedAccounts:
- '*'
AWS Layers - Serverless Documentation
AWS Layers - Serverless Documentation
How to publish and use AWS Lambda Layers with the Serverless Framework
How to publish and use AWS Lambda Layers with the Serverless Framework
serverless-python-requirements
serverless-python-requirements
CloudFormation Ref
CloudFormation Ref
44 Lectures
7.5 hours
Eduonix Learning Solutions
31 Lectures
3 hours
Harshit Srivastava
25 Lectures
1 hours
Skillbakerystudios
142 Lectures
9 hours
Sundar Singh, Naveen Selvaraj
45 Lectures
1 hours
Santiago Esteva
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2863,
"s": 2003,
"text": "Layers are a way of isolating code blocks. Say you want to import the NumPy library in your application. You trust the library and there's hardly any chance that you will be making changes in the source code of that library. Therefore, you won't like it if the source code of NumPy clutters your application workspace. Speaking very crudely, you would simply want NumPy to sit somewhere else, isolated from your application code. Layers allow you to do exactly that. You can simply bundle all your dependencies (NumPy, Pandas, SciPy, etc.) in a separate layer, and then simply reference that layer in your lambda function within serverless. And boom! All the libraries bundled within that layer can now be imported into your application. At the same time, your application workspace remains completely uncluttered. You simply see the application code to edit."
},
{
"code": null,
"e": 2937,
"s": 2863,
"text": "Photo by Iva Rajovic on Unsplash, indicative of code separation in layers"
},
{
"code": null,
"e": 3328,
"s": 2937,
"text": "The really cool thing about layers is that they can be shared across functions. Say you deployed a lambda function with a python-requirements layer that contains NumPy and Pandas. Now, if another lambda function requires NumPy, you need not deploy a separate layer for this function. You can simply use the layer of the previous function and it will work well with the new function as well."
},
{
"code": null,
"e": 3937,
"s": 3328,
"text": "This will save you a lot of precious time during deployment. After all, you will be deploying only the application code. The dependencies are already present in an existing layer. Therefore,several developers keep the dependencies layer in a separate stack. They then use this layer in all other applications. This way, they don't need to deploy the dependencies again and again. After all, the dependencies are quite heavy. NumPy library itself is approx. 80 MB large. Deploying dependencies every time you make changes to your application code (which may measure just a few KBs) will be quite inconvenient."
},
{
"code": null,
"e": 4367,
"s": 3937,
"text": "And adding a dependencies layer is just one example. There are several other use-cases. For example, the example given on serverless.com concerns the creation of GIFs using the FFmpeg tool. In that example, they have stored the FFmpeg tool in a layer. In all, AWS Lambda allows us to add a maximum of 5 layers per function. The only condition is that the total size of the 5 layers and the application should be less than 250 MB."
},
{
"code": null,
"e": 4705,
"s": 4367,
"text": "Now let's see how the layer containing all the dependencies can be created and deployed using serverless. To do that, we need the serverless-python-requirements plugin.This plugin only works with Serverless 1.34 and above. So you may want to upgrade your Serverless version if you have a version <1.34. You can install the plugin using −"
},
{
"code": null,
"e": 4759,
"s": 4705,
"text": "sls plugin install -n serverless-python-requirements\n"
},
{
"code": null,
"e": 4888,
"s": 4759,
"text": "Next, you add this plugin in the plugins section of your serverless.yml, and mention it's configurations in the custom section −"
},
{
"code": null,
"e": 5007,
"s": 4888,
"text": "plugins:\n - serverless-python-requirements\ncustom:\n pythonRequirements:\n dockerizePip: true\n layer: true"
},
{
"code": null,
"e": 5495,
"s": 5007,
"text": "Over here, dockerizePip − true enables the usage of docker and allows you to package all the dependencies in a docker container. We've discussed about packaging using docker in the previous chapter. layer − true tells serverless that the python requirements should be stored in a separate layer. Now, at this point, you may be wondering that how does serverless understand which dependencies to package? The answer, as mentioned in the plugins chapter, lies in the requirements.txt file."
},
{
"code": null,
"e": 5644,
"s": 5495,
"text": "Once the layer plugin and custom configurations have been defined, you can add the layer to your individual functions within serverless as follows −"
},
{
"code": null,
"e": 5758,
"s": 5644,
"text": "functions:\n hello:\n handler: handler.hello\n layers:\n - { Ref: PythonRequirementsLambdaLayer }"
},
{
"code": null,
"e": 6163,
"s": 5758,
"text": "The keyword PythonRequirementsLambdaLayer comes from the CloudFormation Reference.In general, it is derived from the layer's name. The syntax is 'LayerNameLambdaLayer' (TitleCased, without spaces). In our case, since the layer name is python requirements, the reference becomes PythonRequirementsLambdaLayer. If you aren't sure about the name of your lambda layer, you can get it in the following steps −"
},
{
"code": null,
"e": 6179,
"s": 6163,
"text": "Run sls package"
},
{
"code": null,
"e": 6195,
"s": 6179,
"text": "Run sls package"
},
{
"code": null,
"e": 6254,
"s": 6195,
"text": "Open .serverless/cloudformation-template-update-stack.json"
},
{
"code": null,
"e": 6313,
"s": 6254,
"text": "Open .serverless/cloudformation-template-update-stack.json"
},
{
"code": null,
"e": 6338,
"s": 6313,
"text": "Search for 'LambdaLayer'"
},
{
"code": null,
"e": 6363,
"s": 6338,
"text": "Search for 'LambdaLayer'"
},
{
"code": null,
"e": 6642,
"s": 6363,
"text": "Like I mentioned in the beginning, a really cool thing about layers is the ability to use existing layers in your function. This can be done easily by using the ARN of your existing layer.The syntax to add an existing layer to a function using the ARN is quite straightforward −"
},
{
"code": null,
"e": 6764,
"s": 6642,
"text": "functions:\n hello:\n handler: handler.hello\n layers:\n - arn:aws:lambda:region:XXXXXX:layer:LayerName:Y"
},
{
"code": null,
"e": 6986,
"s": 6764,
"text": "That's it. Now the layer with the specified ARN will work with your function. If the layer contains the NumPy library, you can simply go ahead and call import numpy in your 'hello' function. It will run without any error."
},
{
"code": null,
"e": 7164,
"s": 6986,
"text": "If you are wondering from where you can get the ARN, it is quite simple actually. Simply navigate to the function containing the layer in the AWS Console, and click on 'Layers'."
},
{
"code": null,
"e": 7325,
"s": 7164,
"text": "Of course, if the layer doesn't belong to your account, then it either needs to be publicly shared or shared specifically with your account. More on that later."
},
{
"code": null,
"e": 7509,
"s": 7325,
"text": "Also, keep in mind that the layer should be compatible with your application. Don't expect a layer compatible with node.js runtime to run with a function created in python3.6 runtime."
},
{
"code": null,
"e": 7984,
"s": 7509,
"text": "As mentioned in the beginning, the layers serve the main function of isolating your code blocks. Therefore, they don't need to contain just dependencies. They can contain any piece of code that you specify. Calling layer: true within pythonRequirements within custom is a kind of a shortcut made possible by the serverless-python-requirements plugin. However, to create a generic layer, the syntax within serverless.yml, as explained in the serverless docs, is as follows −"
},
{
"code": null,
"e": 8774,
"s": 7984,
"text": "layers:\n hello:\n path: layer-dir # required, path to layer contents on disk\n name: ${opt:stage, self:provider.stage, 'dev'}-layerName # optional, Deployed Lambda layer name\n description: Description of what the lambda layer does # optional, Description to publish to AWS\n compatibleRuntimes: # optional, a list of runtimes this layer is compatible with\n - python3.8\n licenseInfo: GPLv3 # optional, a string specifying license information\n # allowedAccounts: # optional, a list of AWS account IDs allowed to access this layer.\n # - '*'\n # note: uncommenting this will give all AWS users access to this layer unconditionally.\n retain: false # optional, false by default. If true, layer versions are not deleted as new ones are created"
},
{
"code": null,
"e": 9282,
"s": 8774,
"text": "The various configuration parameters are self-explanatory thanks to the comments provided. Except for the 'path', all other properties are optional. The path property is a path to a directory of your choice that you want to be isolated from your application code. It will be zipped up and published as your layer. For instance, in the example project on serverless, where they host the FFmpeg tool in a layer, they download the tool in a separate folder called 'layer' and specify that in the path property."
},
{
"code": null,
"e": 9319,
"s": 9282,
"text": "layers:\n ffmpeg:\n path: layer"
},
{
"code": null,
"e": 9391,
"s": 9319,
"text": "As told before, we can add up to 5 layers within the layers − property."
},
{
"code": null,
"e": 9513,
"s": 9391,
"text": "To use these generic layers in your functions, again, you can use either the CloudFormation reference or specify the ARN."
},
{
"code": null,
"e": 9654,
"s": 9513,
"text": "More accounts can be provided access to your layer by simply mentioning the account numbers in the 'allowedAccounts' property. For example −"
},
{
"code": null,
"e": 9827,
"s": 9654,
"text": "layers:\n testLayer:\n path: testLayer\n allowedAccounts:\n - 999999999999 # a specific account ID\n - 000123456789 # a different specific account ID"
},
{
"code": null,
"e": 9913,
"s": 9827,
"text": "If you want the layer to be publicly accessible, you can add '*' in allowedAccounts −"
},
{
"code": null,
"e": 9992,
"s": 9913,
"text": "layers:\n testLayer:\n path: testLayer\n allowedAccounts:\n - '*'"
},
{
"code": null,
"e": 10030,
"s": 9992,
"text": "AWS Layers - Serverless Documentation"
},
{
"code": null,
"e": 10068,
"s": 10030,
"text": "AWS Layers - Serverless Documentation"
},
{
"code": null,
"e": 10139,
"s": 10068,
"text": "How to publish and use AWS Lambda Layers with the Serverless Framework"
},
{
"code": null,
"e": 10210,
"s": 10139,
"text": "How to publish and use AWS Lambda Layers with the Serverless Framework"
},
{
"code": null,
"e": 10241,
"s": 10210,
"text": "serverless-python-requirements"
},
{
"code": null,
"e": 10272,
"s": 10241,
"text": "serverless-python-requirements"
},
{
"code": null,
"e": 10291,
"s": 10272,
"text": "CloudFormation Ref"
},
{
"code": null,
"e": 10310,
"s": 10291,
"text": "CloudFormation Ref"
},
{
"code": null,
"e": 10345,
"s": 10310,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 10373,
"s": 10345,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10406,
"s": 10373,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 10426,
"s": 10406,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 10459,
"s": 10426,
"text": "\n 25 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10479,
"s": 10459,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 10513,
"s": 10479,
"text": "\n 142 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 10544,
"s": 10513,
"text": " Sundar Singh, Naveen Selvaraj"
},
{
"code": null,
"e": 10577,
"s": 10544,
"text": "\n 45 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10594,
"s": 10577,
"text": " Santiago Esteva"
},
{
"code": null,
"e": 10601,
"s": 10594,
"text": " Print"
},
{
"code": null,
"e": 10612,
"s": 10601,
"text": " Add Notes"
}
] |
Binary Search | Practice | GeeksforGeeks | Given a sorted array of size N and an integer K, find the position at which K is present in the array using binary search.
Example 1:
Input:
N = 5
arr[] = {1 2 3 4 5}
K = 4
Output: 3
Explanation: 4 appears at index 3.
Example 2:
Input:
N = 5
arr[] = {11 22 33 44 55}
K = 445
Output: -1
Explanation: 445 is not present.
Your Task:
You dont need to read input or print anything. Complete the function binarysearch() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1.
Expected Time Complexity: O(LogN)
Expected Auxiliary Space: O(LogN) if solving recursively and O(1) otherwise.
Constraints:
1 <= N <= 104
1 <= arr[i] <= 104
0
koulikmaity4 hours ago
int binarysearch(int arr[], int n, int k){ int s = 0; int e = n-1; int mid = s + (e - s) / 2; while(s <= e) { if(arr[mid] == k) return mid; if(arr[mid] <= k) { s = mid + 1 ; } if(arr[mid] > k) { e = mid - 1; } mid = s + (e - s) / 2; } return -1; }
0
sidvas582 days ago
Why does this show time limit exceeded?
class Solution{public: int binarysearch(int arr[], int n, int k){ // code here int l=0,h=n-1; int mid=l+(h-l)/2; while(l<=h) { if(arr[mid]==k) return mid; else if(arr[mid]<k) l=mid+1; else h=mid-1; } return -1; }};
0
aggshubham12339
This comment was deleted.
0
priyansh708902 days ago
int binarysearch(int arr[], int n, int k){ // code here int start = 0; int end = n-1; int mid = start + (end-start)/2; while(start<=end) { // if we find key if(arr[mid] == k) { return mid; } // if key is Less than mid else if(arr[mid] > k) { end = mid - 1; } // if key is greater than mid else { start = mid +1; } // find new mid mid = start + (end-start)/2; } return -1; }
0
ashok1si18ec0172 days ago
class Solution { int binarysearch(int arr[], int n, int k){ // code here int count=-1; for(int i=0;i<n;i++) { if(arr[i]==k) { count=i; } } return count; }}
0
mukuldhurkunde3 days ago
Python3
for i in range(len(arr)):
if arr[i] == k:
return i
return -1
0
pallemadhuyadhav29293 days ago
B
0
fenilvaghasiya2026
This comment was deleted.
+1
rahilarahman4 days ago
easy python code for binary search
class Solution: def binarysearch(self, arr, n, k): start=0 end=n-1 while start<=end : mid=(start + end)//2 if arr[mid]==k: return mid elif arr[mid]<k: start=mid+1 else: end=mid-1 return -1
0
harshscode5 days ago
int l=0; int h=n-1; while(l<=h) { int mid=(l+h)/2; if(a[mid]==k) return mid; else if(a[mid]>k) h=mid-1; else l=mid+1; } return -1;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 361,
"s": 238,
"text": "Given a sorted array of size N and an integer K, find the position at which K is present in the array using binary search."
},
{
"code": null,
"e": 373,
"s": 361,
"text": "\nExample 1:"
},
{
"code": null,
"e": 458,
"s": 373,
"text": "Input:\nN = 5\narr[] = {1 2 3 4 5} \nK = 4\nOutput: 3\nExplanation: 4 appears at index 3."
},
{
"code": null,
"e": 470,
"s": 458,
"text": "\nExample 2:"
},
{
"code": null,
"e": 561,
"s": 470,
"text": "Input:\nN = 5\narr[] = {11 22 33 44 55} \nK = 445\nOutput: -1\nExplanation: 445 is not present."
},
{
"code": null,
"e": 792,
"s": 561,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function binarysearch() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1."
},
{
"code": null,
"e": 904,
"s": 792,
"text": "\nExpected Time Complexity: O(LogN)\nExpected Auxiliary Space: O(LogN) if solving recursively and O(1) otherwise."
},
{
"code": null,
"e": 951,
"s": 904,
"text": "\nConstraints:\n1 <= N <= 104\n1 <= arr[i] <= 104"
},
{
"code": null,
"e": 953,
"s": 951,
"text": "0"
},
{
"code": null,
"e": 976,
"s": 953,
"text": "koulikmaity4 hours ago"
},
{
"code": null,
"e": 1405,
"s": 976,
"text": "int binarysearch(int arr[], int n, int k){ int s = 0; int e = n-1; int mid = s + (e - s) / 2; while(s <= e) { if(arr[mid] == k) return mid; if(arr[mid] <= k) { s = mid + 1 ; } if(arr[mid] > k) { e = mid - 1; } mid = s + (e - s) / 2; } return -1; }"
},
{
"code": null,
"e": 1407,
"s": 1405,
"text": "0"
},
{
"code": null,
"e": 1426,
"s": 1407,
"text": "sidvas582 days ago"
},
{
"code": null,
"e": 1466,
"s": 1426,
"text": "Why does this show time limit exceeded?"
},
{
"code": null,
"e": 1789,
"s": 1468,
"text": "class Solution{public: int binarysearch(int arr[], int n, int k){ // code here int l=0,h=n-1; int mid=l+(h-l)/2; while(l<=h) { if(arr[mid]==k) return mid; else if(arr[mid]<k) l=mid+1; else h=mid-1; } return -1; }};"
},
{
"code": null,
"e": 1791,
"s": 1789,
"text": "0"
},
{
"code": null,
"e": 1807,
"s": 1791,
"text": "aggshubham12339"
},
{
"code": null,
"e": 1833,
"s": 1807,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1835,
"s": 1833,
"text": "0"
},
{
"code": null,
"e": 1859,
"s": 1835,
"text": "priyansh708902 days ago"
},
{
"code": null,
"e": 2519,
"s": 1859,
"text": " int binarysearch(int arr[], int n, int k){ // code here int start = 0; int end = n-1; int mid = start + (end-start)/2; while(start<=end) { // if we find key if(arr[mid] == k) { return mid; } // if key is Less than mid else if(arr[mid] > k) { end = mid - 1; } // if key is greater than mid else { start = mid +1; } // find new mid mid = start + (end-start)/2; } return -1; }"
},
{
"code": null,
"e": 2521,
"s": 2519,
"text": "0"
},
{
"code": null,
"e": 2547,
"s": 2521,
"text": "ashok1si18ec0172 days ago"
},
{
"code": null,
"e": 2787,
"s": 2547,
"text": "class Solution { int binarysearch(int arr[], int n, int k){ // code here int count=-1; for(int i=0;i<n;i++) { if(arr[i]==k) { count=i; } } return count; }}"
},
{
"code": null,
"e": 2789,
"s": 2787,
"text": "0"
},
{
"code": null,
"e": 2814,
"s": 2789,
"text": "mukuldhurkunde3 days ago"
},
{
"code": null,
"e": 2822,
"s": 2814,
"text": "Python3"
},
{
"code": null,
"e": 2889,
"s": 2822,
"text": "for i in range(len(arr)):\n\tif arr[i] == k:\n\t return i\n return -1"
},
{
"code": null,
"e": 2891,
"s": 2889,
"text": "0"
},
{
"code": null,
"e": 2922,
"s": 2891,
"text": "pallemadhuyadhav29293 days ago"
},
{
"code": null,
"e": 2924,
"s": 2922,
"text": "B"
},
{
"code": null,
"e": 2926,
"s": 2924,
"text": "0"
},
{
"code": null,
"e": 2945,
"s": 2926,
"text": "fenilvaghasiya2026"
},
{
"code": null,
"e": 2971,
"s": 2945,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2974,
"s": 2971,
"text": "+1"
},
{
"code": null,
"e": 2997,
"s": 2974,
"text": "rahilarahman4 days ago"
},
{
"code": null,
"e": 3032,
"s": 2997,
"text": "easy python code for binary search"
},
{
"code": null,
"e": 3327,
"s": 3034,
"text": "class Solution: def binarysearch(self, arr, n, k): start=0 end=n-1 while start<=end : mid=(start + end)//2 if arr[mid]==k: return mid elif arr[mid]<k: start=mid+1 else: end=mid-1 return -1 "
},
{
"code": null,
"e": 3329,
"s": 3327,
"text": "0"
},
{
"code": null,
"e": 3350,
"s": 3329,
"text": "harshscode5 days ago"
},
{
"code": null,
"e": 3589,
"s": 3350,
"text": " int l=0; int h=n-1; while(l<=h) { int mid=(l+h)/2; if(a[mid]==k) return mid; else if(a[mid]>k) h=mid-1; else l=mid+1; } return -1;"
},
{
"code": null,
"e": 3735,
"s": 3589,
"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": 3771,
"s": 3735,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3781,
"s": 3771,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3791,
"s": 3781,
"text": "\nContest\n"
},
{
"code": null,
"e": 3854,
"s": 3791,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4002,
"s": 3854,
"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": 4210,
"s": 4002,
"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": 4316,
"s": 4210,
"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 format number in JSP? | The <fmt:formatNumber> tag is used to format numbers, percentages, and currencies.
The <fmt:formatNumber> tag has the following attributes −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>JSTL fmt:formatNumber Tag</title>
</head>
<body>
<h3>Number Format:</h3>
<c:set var = "balance" value = "120000.2309" />
<p>Formatted Number (1): <fmt:formatNumber value = "${balance}" type = "currency"/></p>
<p>Formatted Number (2): <fmt:formatNumber type = "number" maxIntegerDigits = "3" value = "${balance}" /></p>
<p>Formatted Number (3): <fmt:formatNumber type = "number" maxFractionDigits = "3" value = "${balance}" /></p>
<p>Formatted Number (4): <fmt:formatNumber type = "number" groupingUsed = "false" value = "${balance}" /></p>
</body>
</html>
The above code will generate the following result −
Number Format:
Formatted Number (1): £120,000.23
Formatted Number (2): 000.231
Formatted Number (3): 120,000.231
Formatted Number (4): 120000.231 | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "The <fmt:formatNumber> tag is used to format numbers, percentages, and currencies."
},
{
"code": null,
"e": 1203,
"s": 1145,
"text": "The <fmt:formatNumber> tag has the following attributes −"
},
{
"code": null,
"e": 1973,
"s": 1203,
"text": "<%@ taglib prefix = \"c\" uri = \"http://java.sun.com/jsp/jstl/core\" %>\n<%@ taglib prefix = \"fmt\" uri = \"http://java.sun.com/jsp/jstl/fmt\" %>\n<html>\n <head>\n <title>JSTL fmt:formatNumber Tag</title>\n </head>\n <body>\n <h3>Number Format:</h3>\n <c:set var = \"balance\" value = \"120000.2309\" />\n <p>Formatted Number (1): <fmt:formatNumber value = \"${balance}\" type = \"currency\"/></p>\n <p>Formatted Number (2): <fmt:formatNumber type = \"number\" maxIntegerDigits = \"3\" value = \"${balance}\" /></p>\n <p>Formatted Number (3): <fmt:formatNumber type = \"number\" maxFractionDigits = \"3\" value = \"${balance}\" /></p>\n <p>Formatted Number (4): <fmt:formatNumber type = \"number\" groupingUsed = \"false\" value = \"${balance}\" /></p>\n </body>\n</html>"
},
{
"code": null,
"e": 2025,
"s": 1973,
"text": "The above code will generate the following result −"
},
{
"code": null,
"e": 2171,
"s": 2025,
"text": "Number Format:\nFormatted Number (1): £120,000.23\nFormatted Number (2): 000.231\nFormatted Number (3): 120,000.231\nFormatted Number (4): 120000.231"
}
] |
Android Material Tabs in Kotlin - GeeksforGeeks | 30 Aug, 2021
In Android, TabLayout is a new element introduced in the Design Support library. It provides a horizontal layout to display tabs on the screen. We can display more screens on a single screen using tabs. We can quickly swipe between the tabs. TabLayout is basically ViewClass required to be added into our layout(XML) for creating Sliding Tabs.
In this article, we are going to develop an application that will have three tabs and users can slide from one tab to another just like in WhatsApp. For this, we will be using TabLayout. A sample GIF is given below to get an idea about what we are going to do in this article.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add dependency
Add a dependency to get access to all the material components and click on sync.
implementation ‘com.google.android.material:material:1.4.0’
Step 3: Set theme and toolbar
Navigate to res > values > color.xml, set some vibrant colors. Add the following script code for colors.
XML
<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#056008</color> <color name="colorAccent">#E39D36</color> <resources>
Now, remove the default toolbar from the screen, and we will make a custom toolbar. Navigate to res > values > styles.xml (for latest version of android studio, res > values > themes > theme.xml) and change parentTheme .
XML
<!-- Base application theme. --><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item></style>
Step 4: Working with activity_main layout
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.appbar.AppBarLayout android:id="@+id/appBarLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:layout_constraintBottom_toTopOf="@+id/viewPager" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> <com.google.android.material.tabs.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabBackground="@color/colorPrimary" app:tabGravity="fill" app:tabMode="fixed" app:tabTextColor="@android:color/white" /> </com.google.android.material.appbar.AppBarLayout> <androidx.viewpager.widget.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/appBarLayout"> </androidx.viewpager.widget.ViewPager> </androidx.constraintlayout.widget.ConstraintLayout>
Step 5: Set three tabs
We need to create three fragment classes and their three respective layouts. Here is the code for 1st fragment i.e. GeeksFragment.kt
Kotlin
import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.ViewGroup class GeeksFragment : Fragment() { // inflate the layout override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = inflater.inflate(R.layout.fragment_geeks, container, false)!!}
The corresponding layout, fragment_geeks.xml
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksForGeeks" /> </LinearLayout>
Code for the 2nd fragment i.e. CodeFragment.kt
Kotlin
import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.ViewGroup class CodeFragment : Fragment() { // inflate the layout override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = inflater.inflate(R.layout.fragment_code, container, false)!!}
The corresponding layout, fragment_code.xml
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Code Chef" /> </LinearLayout>
Code for 3rd fragment i.e. LeetFragment.kt
Kotlin
import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.ViewGroup class LeetFragment : Fragment() { // inflate the layout override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = inflater.inflate(R.layout.fragment_leet, container, false)!!}
The corresponding layout, fragment_leet.xml
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Leet Code" /> </LinearLayout>
Step 6: Create a ViewPagerAdapter class
To connect all our fragments with the ViewPager, we need an adapter class. we will pass the list of instances of fragment class and their title to show on the tabs. Below is the code for ViewPagerAdapter.kt Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.fragment.app.Fragmentimport androidx.fragment.app.FragmentManagerimport androidx.fragment.app.FragmentStatePagerAdapter class ViewPagerAdapter(supportFragmentManager: FragmentManager) : FragmentStatePagerAdapter(supportFragmentManager) { // declare arrayList to contain fragments and its title private val mFragmentList = ArrayList<Fragment>() private val mFragmentTitleList = ArrayList<String>() override fun getItem(position: Int): Fragment { // return a particular fragment page return mFragmentList[position] } override fun getCount(): Int { // return the number of tabs return mFragmentList.size } override fun getPageTitle(position: Int): CharSequence{ // return title of the tab return mFragmentTitleList[position] } fun addFragment(fragment: Fragment, title: String) { // add each fragment and its title to the array list mFragmentList.add(fragment) mFragmentTitleList.add(title) }}
Step 7: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.appcompat.widget.Toolbarimport androidx.viewpager.widget.ViewPagerimport com.google.android.material.tabs.TabLayout class MainActivity : AppCompatActivity() { private lateinit var pager: ViewPager // creating object of ViewPager private lateinit var tab: TabLayout // creating object of TabLayout private lateinit var bar: Toolbar // creating object of ToolBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // set the references of the declared objects above pager = findViewById(R.id.viewPager) tab = findViewById(R.id.tabs) bar = findViewById(R.id.toolbar) // To make our toolbar show the application // we need to give it to the ActionBar setSupportActionBar(bar) // Initializing the ViewPagerAdapter val adapter = ViewPagerAdapter(supportFragmentManager) // add fragment to the list adapter.addFragment(GeeksFragment(), "GeeksForGeeks") adapter.addFragment(CodeFragment(), "Code Chef") adapter.addFragment(LeetFragment(), "Leet Code") // Adding the Adapter to the ViewPager pager.adapter = adapter // bind the viewPager with the TabLayout. tab.setupWithViewPager(pager) }}
Now, run the app
Output:
Source Code: Click Here
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Services in Android with Example
How to Create and Add Data to SQLite Database in Android?
Content Providers in Android with Example
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Services in Android with Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Android UI Layouts | [
{
"code": null,
"e": 24106,
"s": 24078,
"text": "\n30 Aug, 2021"
},
{
"code": null,
"e": 24451,
"s": 24106,
"text": "In Android, TabLayout is a new element introduced in the Design Support library. It provides a horizontal layout to display tabs on the screen. We can display more screens on a single screen using tabs. We can quickly swipe between the tabs. TabLayout is basically ViewClass required to be added into our layout(XML) for creating Sliding Tabs. "
},
{
"code": null,
"e": 24729,
"s": 24451,
"text": "In this article, we are going to develop an application that will have three tabs and users can slide from one tab to another just like in WhatsApp. For this, we will be using TabLayout. A sample GIF is given below to get an idea about what we are going to do in this article. "
},
{
"code": null,
"e": 24758,
"s": 24729,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 24922,
"s": 24758,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 24945,
"s": 24922,
"text": "Step 2: Add dependency"
},
{
"code": null,
"e": 25026,
"s": 24945,
"text": "Add a dependency to get access to all the material components and click on sync."
},
{
"code": null,
"e": 25089,
"s": 25026,
"text": " implementation ‘com.google.android.material:material:1.4.0’"
},
{
"code": null,
"e": 25119,
"s": 25089,
"text": "Step 3: Set theme and toolbar"
},
{
"code": null,
"e": 25224,
"s": 25119,
"text": "Navigate to res > values > color.xml, set some vibrant colors. Add the following script code for colors."
},
{
"code": null,
"e": 25228,
"s": 25224,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#056008</color> <color name=\"colorAccent\">#E39D36</color> <resources>",
"e": 25432,
"s": 25228,
"text": null
},
{
"code": null,
"e": 25653,
"s": 25432,
"text": "Now, remove the default toolbar from the screen, and we will make a custom toolbar. Navigate to res > values > styles.xml (for latest version of android studio, res > values > themes > theme.xml) and change parentTheme ."
},
{
"code": null,
"e": 25657,
"s": 25653,
"text": "XML"
},
{
"code": "<!-- Base application theme. --><style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item></style>",
"e": 25989,
"s": 25657,
"text": null
},
{
"code": null,
"e": 26031,
"s": 25989,
"text": "Step 4: Working with activity_main layout"
},
{
"code": null,
"e": 26173,
"s": 26031,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 26177,
"s": 26173,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <com.google.android.material.appbar.AppBarLayout android:id=\"@+id/appBarLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:theme=\"@style/ThemeOverlay.AppCompat.Dark.ActionBar\" app:layout_constraintBottom_toTopOf=\"@+id/viewPager\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <androidx.appcompat.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:layout_height=\"?attr/actionBarSize\" android:background=\"?attr/colorPrimary\" app:popupTheme=\"@style/ThemeOverlay.AppCompat.Light\" /> <com.google.android.material.tabs.TabLayout android:id=\"@+id/tabs\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:tabBackground=\"@color/colorPrimary\" app:tabGravity=\"fill\" app:tabMode=\"fixed\" app:tabTextColor=\"@android:color/white\" /> </com.google.android.material.appbar.AppBarLayout> <androidx.viewpager.widget.ViewPager android:id=\"@+id/viewPager\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/appBarLayout\"> </androidx.viewpager.widget.ViewPager> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 28111,
"s": 26177,
"text": null
},
{
"code": null,
"e": 28134,
"s": 28111,
"text": "Step 5: Set three tabs"
},
{
"code": null,
"e": 28268,
"s": 28134,
"text": "We need to create three fragment classes and their three respective layouts. Here is the code for 1st fragment i.e. GeeksFragment.kt "
},
{
"code": null,
"e": 28275,
"s": 28268,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.ViewGroup class GeeksFragment : Fragment() { // inflate the layout override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = inflater.inflate(R.layout.fragment_geeks, container, false)!!}",
"e": 28666,
"s": 28275,
"text": null
},
{
"code": null,
"e": 28712,
"s": 28666,
"text": "The corresponding layout, fragment_geeks.xml "
},
{
"code": null,
"e": 28716,
"s": 28712,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksForGeeks\" /> </LinearLayout>",
"e": 29095,
"s": 28716,
"text": null
},
{
"code": null,
"e": 29143,
"s": 29095,
"text": "Code for the 2nd fragment i.e. CodeFragment.kt "
},
{
"code": null,
"e": 29150,
"s": 29143,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.ViewGroup class CodeFragment : Fragment() { // inflate the layout override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = inflater.inflate(R.layout.fragment_code, container, false)!!}",
"e": 29539,
"s": 29150,
"text": null
},
{
"code": null,
"e": 29583,
"s": 29539,
"text": "The corresponding layout, fragment_code.xml"
},
{
"code": null,
"e": 29587,
"s": 29583,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Code Chef\" /> </LinearLayout>",
"e": 29966,
"s": 29587,
"text": null
},
{
"code": null,
"e": 30009,
"s": 29966,
"text": "Code for 3rd fragment i.e. LeetFragment.kt"
},
{
"code": null,
"e": 30016,
"s": 30009,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.ViewGroup class LeetFragment : Fragment() { // inflate the layout override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = inflater.inflate(R.layout.fragment_leet, container, false)!!}",
"e": 30405,
"s": 30016,
"text": null
},
{
"code": null,
"e": 30449,
"s": 30405,
"text": "The corresponding layout, fragment_leet.xml"
},
{
"code": null,
"e": 30453,
"s": 30449,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Leet Code\" /> </LinearLayout>",
"e": 30832,
"s": 30453,
"text": null
},
{
"code": null,
"e": 30872,
"s": 30832,
"text": "Step 6: Create a ViewPagerAdapter class"
},
{
"code": null,
"e": 31154,
"s": 30872,
"text": "To connect all our fragments with the ViewPager, we need an adapter class. we will pass the list of instances of fragment class and their title to show on the tabs. Below is the code for ViewPagerAdapter.kt Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 31161,
"s": 31154,
"text": "Kotlin"
},
{
"code": "import androidx.fragment.app.Fragmentimport androidx.fragment.app.FragmentManagerimport androidx.fragment.app.FragmentStatePagerAdapter class ViewPagerAdapter(supportFragmentManager: FragmentManager) : FragmentStatePagerAdapter(supportFragmentManager) { // declare arrayList to contain fragments and its title private val mFragmentList = ArrayList<Fragment>() private val mFragmentTitleList = ArrayList<String>() override fun getItem(position: Int): Fragment { // return a particular fragment page return mFragmentList[position] } override fun getCount(): Int { // return the number of tabs return mFragmentList.size } override fun getPageTitle(position: Int): CharSequence{ // return title of the tab return mFragmentTitleList[position] } fun addFragment(fragment: Fragment, title: String) { // add each fragment and its title to the array list mFragmentList.add(fragment) mFragmentTitleList.add(title) }}",
"e": 32178,
"s": 31161,
"text": null
},
{
"code": null,
"e": 32224,
"s": 32178,
"text": "Step 7: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 32410,
"s": 32224,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 32417,
"s": 32410,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.appcompat.widget.Toolbarimport androidx.viewpager.widget.ViewPagerimport com.google.android.material.tabs.TabLayout class MainActivity : AppCompatActivity() { private lateinit var pager: ViewPager // creating object of ViewPager private lateinit var tab: TabLayout // creating object of TabLayout private lateinit var bar: Toolbar // creating object of ToolBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // set the references of the declared objects above pager = findViewById(R.id.viewPager) tab = findViewById(R.id.tabs) bar = findViewById(R.id.toolbar) // To make our toolbar show the application // we need to give it to the ActionBar setSupportActionBar(bar) // Initializing the ViewPagerAdapter val adapter = ViewPagerAdapter(supportFragmentManager) // add fragment to the list adapter.addFragment(GeeksFragment(), \"GeeksForGeeks\") adapter.addFragment(CodeFragment(), \"Code Chef\") adapter.addFragment(LeetFragment(), \"Leet Code\") // Adding the Adapter to the ViewPager pager.adapter = adapter // bind the viewPager with the TabLayout. tab.setupWithViewPager(pager) }}",
"e": 33840,
"s": 32417,
"text": null
},
{
"code": null,
"e": 33857,
"s": 33840,
"text": "Now, run the app"
},
{
"code": null,
"e": 33865,
"s": 33857,
"text": "Output:"
},
{
"code": null,
"e": 33889,
"s": 33865,
"text": "Source Code: Click Here"
},
{
"code": null,
"e": 33896,
"s": 33889,
"text": "Picked"
},
{
"code": null,
"e": 33904,
"s": 33896,
"text": "Android"
},
{
"code": null,
"e": 33911,
"s": 33904,
"text": "Kotlin"
},
{
"code": null,
"e": 33919,
"s": 33911,
"text": "Android"
},
{
"code": null,
"e": 34017,
"s": 33919,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34060,
"s": 34017,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 34093,
"s": 34060,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 34151,
"s": 34093,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 34193,
"s": 34151,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 34224,
"s": 34193,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 34267,
"s": 34224,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 34300,
"s": 34267,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 34342,
"s": 34300,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 34373,
"s": 34342,
"text": "Android RecyclerView in Kotlin"
}
] |
Create an italic text in HTML | The HTML <i> tag is used to display the content in italic.You can try to run the following code to create an italic text in HTML −
<!DOCTYPE html>
<html>
<head>
<title>HTML i Tag</title>
</head>
<body>
<p>We liked the movie <i>Avengers</i></p>
</body>
</html> | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "The HTML <i> tag is used to display the content in italic.You can try to run the following code to create an italic text in HTML −"
},
{
"code": null,
"e": 1346,
"s": 1193,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML i Tag</title>\n </head>\n <body>\n <p>We liked the movie <i>Avengers</i></p>\n </body>\n</html>"
}
] |
Dynamic ProgressBar in Kotlin - GeeksforGeeks | 23 Feb, 2021
Android ProgressBar is user interface control that is used to show some kind of progress. For instance, loading of some page, downloading of some file or waiting for some event to complete.
In this article we will be discussing how to programmatically create a progress bar in Kotlin .
Firstly, we need to create a project in Android Studio. To do follow these steps:
Click on File, then New and then New Project and give name whatever you like
Then, select Kotlin language Support and click next button.
Select minimum SDK, whatever you need.
Select Empty activity and then click finish.
Second step is to design our layout page. Here, we will use the RelativeLayout to get the ProgressBar from the Kotlin file.
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <RelativeLayout android:id="@+id/layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_centerHorizontal="true" android:layout_above="@+id/button"> </RelativeLayout> <Button android:id="@+id/button" android:layout_marginTop="100dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Stop Loading"/> </RelativeLayout>
Update the strings.xml file
<resources> <string name="app_name">DynamicProgressBarInKotlin</string></resources>
Open app/src/main/java/yourPackageName/MainActivity.kt. In this file , we declare a variable progressBar to create the ProgressBar widget like this
val progressBar = ProgressBar(this)
//setting height and width of progressBar
progressBar.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
then add the widget in layout using this
val layout = findViewById(R.id.layout)
// Add ProgressBar to our layout
layout?.addView(progressBar)
package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.LinearLayoutimport android.widget.ProgressBarimport android.widget.RelativeLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val progressBar = ProgressBar(this) //setting height and width of progressBar progressBar.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) //accessing our relative layout where the progressBar will add up val layout = findViewById<RelativeLayout>(R.id.layout) // Add ProgressBar to our layout layout?.addView(progressBar) //accessing the button which will handle the events, // whether to show progressBar or not val button = findViewById<Button>(R.id.button) //set a click listener to show/hide progressBar added in RelativeLayout. button?.setOnClickListener { val visibility = if (progressBar.visibility == View.GONE){ View.VISIBLE }else View.GONE progressBar.visibility = visibility //setting button text //if we click "stop loading" button, text of button will change // to "start loading.." and vice versa val btnText = if (progressBar.visibility == View.GONE) "START LOADING..." else "STOP LOADING" button.text = btnText } }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application> </manifest>
shubham_singh
Android-Bars
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Services in Android with Example
CardView in Android With Example
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Android UI Layouts
Services in Android with Example
Content Providers in Android with Example | [
{
"code": null,
"e": 23627,
"s": 23599,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 23817,
"s": 23627,
"text": "Android ProgressBar is user interface control that is used to show some kind of progress. For instance, loading of some page, downloading of some file or waiting for some event to complete."
},
{
"code": null,
"e": 23913,
"s": 23817,
"text": "In this article we will be discussing how to programmatically create a progress bar in Kotlin ."
},
{
"code": null,
"e": 23995,
"s": 23913,
"text": "Firstly, we need to create a project in Android Studio. To do follow these steps:"
},
{
"code": null,
"e": 24072,
"s": 23995,
"text": "Click on File, then New and then New Project and give name whatever you like"
},
{
"code": null,
"e": 24132,
"s": 24072,
"text": "Then, select Kotlin language Support and click next button."
},
{
"code": null,
"e": 24171,
"s": 24132,
"text": "Select minimum SDK, whatever you need."
},
{
"code": null,
"e": 24216,
"s": 24171,
"text": "Select Empty activity and then click finish."
},
{
"code": null,
"e": 24340,
"s": 24216,
"text": "Second step is to design our layout page. Here, we will use the RelativeLayout to get the ProgressBar from the Kotlin file."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <RelativeLayout android:id=\"@+id/layout\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" android:layout_centerHorizontal=\"true\" android:layout_above=\"@+id/button\"> </RelativeLayout> <Button android:id=\"@+id/button\" android:layout_marginTop=\"100dp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Stop Loading\"/> </RelativeLayout>",
"e": 25310,
"s": 24340,
"text": null
},
{
"code": null,
"e": 25338,
"s": 25310,
"text": "Update the strings.xml file"
},
{
"code": "<resources> <string name=\"app_name\">DynamicProgressBarInKotlin</string></resources>",
"e": 25425,
"s": 25338,
"text": null
},
{
"code": null,
"e": 25573,
"s": 25425,
"text": "Open app/src/main/java/yourPackageName/MainActivity.kt. In this file , we declare a variable progressBar to create the ProgressBar widget like this"
},
{
"code": null,
"e": 25823,
"s": 25573,
"text": " val progressBar = ProgressBar(this)\n //setting height and width of progressBar\n progressBar.layoutParams = LinearLayout.LayoutParams(\n ViewGroup.LayoutParams.WRAP_CONTENT,\n ViewGroup.LayoutParams.WRAP_CONTENT)\n"
},
{
"code": null,
"e": 25864,
"s": 25823,
"text": "then add the widget in layout using this"
},
{
"code": null,
"e": 25976,
"s": 25864,
"text": "val layout = findViewById(R.id.layout)\n // Add ProgressBar to our layout\n layout?.addView(progressBar)\n"
},
{
"code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.LinearLayoutimport android.widget.ProgressBarimport android.widget.RelativeLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val progressBar = ProgressBar(this) //setting height and width of progressBar progressBar.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) //accessing our relative layout where the progressBar will add up val layout = findViewById<RelativeLayout>(R.id.layout) // Add ProgressBar to our layout layout?.addView(progressBar) //accessing the button which will handle the events, // whether to show progressBar or not val button = findViewById<Button>(R.id.button) //set a click listener to show/hide progressBar added in RelativeLayout. button?.setOnClickListener { val visibility = if (progressBar.visibility == View.GONE){ View.VISIBLE }else View.GONE progressBar.visibility = visibility //setting button text //if we click \"stop loading\" button, text of button will change // to \"start loading..\" and vice versa val btnText = if (progressBar.visibility == View.GONE) \"START LOADING...\" else \"STOP LOADING\" button.text = btnText } }}",
"e": 27754,
"s": 25976,
"text": null
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity></application> </manifest>",
"e": 28409,
"s": 27754,
"text": null
},
{
"code": null,
"e": 28423,
"s": 28409,
"text": "shubham_singh"
},
{
"code": null,
"e": 28436,
"s": 28423,
"text": "Android-Bars"
},
{
"code": null,
"e": 28451,
"s": 28436,
"text": "Kotlin Android"
},
{
"code": null,
"e": 28458,
"s": 28451,
"text": "Picked"
},
{
"code": null,
"e": 28466,
"s": 28458,
"text": "Android"
},
{
"code": null,
"e": 28473,
"s": 28466,
"text": "Kotlin"
},
{
"code": null,
"e": 28481,
"s": 28473,
"text": "Android"
},
{
"code": null,
"e": 28579,
"s": 28481,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28588,
"s": 28579,
"text": "Comments"
},
{
"code": null,
"e": 28601,
"s": 28588,
"text": "Old Comments"
},
{
"code": null,
"e": 28659,
"s": 28601,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 28702,
"s": 28659,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 28733,
"s": 28702,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 28766,
"s": 28733,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 28799,
"s": 28766,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 28842,
"s": 28799,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 28873,
"s": 28842,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 28892,
"s": 28873,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 28925,
"s": 28892,
"text": "Services in Android with Example"
}
] |
Python + Selenium | How to locate elements in span class & not unique ID | We can locate elements in span class and not unique id with the help of the Selenium webdriver. We can identify an element having a class attribute with the help of the locator xpath, css or class name.
To locate elements with these locators we have to use the By.xpath, By.xpath or By.cssSelector method. Then pass the locator value as a parameter to this method.
Let us see the html code of a button having a span class and try to identify it.
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
l = driver.find_element_by_id("textemail")
l.send_keys("[email protected]")
#get value entered
s = l.get_attribute('value')
#identify element with span class
m = driver.find_element_by_xpath("//span[@class='input_group_button']")
#verify if element present
b = m.is_displayed()
if b:
print("Element with span class available")
else:
print("Element with span class not available")
#close browser
driver.close() | [
{
"code": null,
"e": 1265,
"s": 1062,
"text": "We can locate elements in span class and not unique id with the help of the Selenium webdriver. We can identify an element having a class attribute with the help of the locator xpath, css or class name."
},
{
"code": null,
"e": 1427,
"s": 1265,
"text": "To locate elements with these locators we have to use the By.xpath, By.xpath or By.cssSelector method. Then pass the locator value as a parameter to this method."
},
{
"code": null,
"e": 1508,
"s": 1427,
"text": "Let us see the html code of a button having a span class and try to identify it."
},
{
"code": null,
"e": 2139,
"s": 1508,
"text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\nl = driver.find_element_by_id(\"textemail\")\nl.send_keys(\"[email protected]\")\n#get value entered\ns = l.get_attribute('value')\n#identify element with span class\nm = driver.find_element_by_xpath(\"//span[@class='input_group_button']\")\n#verify if element present\nb = m.is_displayed()\nif b:\n print(\"Element with span class available\")\nelse:\n print(\"Element with span class not available\")\n#close browser\ndriver.close()"
}
] |
Building Snowpipe on Azure Blob Storage Using Azure Portal Web UI for Snowflake Data Warehouse | by Christopher Tao | Towards Data Science | Snowpipe is a built-in data ingestion mechanism of Snowflake Data Warehouse. It is able to monitor and automatically pick up flat files from cloud storage (e.g. Azure Blob Storage, Amazon S3) and use the “COPY INTO” SQL command to load the data into a Snowflake table.
In the official documentation, you’ll find a nice tutorial:
Automating Snowpipe for Azure Blob Storagehttps://docs.snowflake.net/manuals/user-guide/data-load-snowpipe-auto-azure.html
However, this article uses Azure CLI (command line interface) to build the cloud storage component and the Azure Event Subscription. In my opinion, this is not intuitive enough especially for new users and the people who do not have enough knowledge of Azure. Even though they can build the Snowpipe following these commands, it is still might be agnostics for the overall architecture and data flow. In other words, this tutorial tells you how to build a Snowpipe, but difficult to let you understand.
In this tutorial, I’ll introduce how to build a Snowpipe using the Azure Portal, which is the Web-based UI of Azure, which I believe will give you better intuition about how the Snowpipe works.
To begin with, let’s create a resource group to organise the storage accounts that are going to be built for Snowpipe. On your Azure Portal, navigate to Resource groups and click Add. Then, input the name for this resource group. You may choose a region that is identical/close to your Snowflake region for the best performance.
Then, let’s create the storage account for staging and event queuing messages.
In the official tutorial, there are two storage accounts created, one blob storage for staging the flat files, and another storage account with a storage queue to facilitate the Event subscription.
In fact, I found that actually one Azure Storage Account with both Blob Container and Storage Queue is enough. Let’s create such a storage account.
In the resource group we’ve just created, click the Add button to create a resource. In the Azure Marketplace, choose the Storage category and in the “Featured” list choose Storage Account.
Note that the name of the storage account should be unique globally, so I added the date as the suffix. This is because every storage account has a DNS CName can be accessed (https://<name>.queue.core.windows.net).
Make sure you choose “StorageV2” for the Account kind to have both Blob Container and Storage Queue. Then, click Review + create to validate and create the storage account.
Now we have a storage account. But before we can utilise it, we need to create:
A Blob Container for the staged files that will be loaded by Snowpipe
A Storage Queue as the endpoint of the Event subscription
To create the Blob Container, click the Containers button, then click +Container. Give a name to this container whichever makes sense to you, and then click OK to create it.
We’ve got a Blob Container now. Let’s create the Storage Queue.
Go back to the Storage Account Overview page. Click Queues to create a Storage Queue.
Next, let’s create the Event Grid Subscription for the Blob Container, and set the endpoint to the Storage Queue.
Navigate to the Storage Account -> Containers, click the Events tab.
There should not be any Event Subscriptions there. Click + Event Subscription to create one.
Give a name to the Event Subscription. Choose the default Event Grid Schema. For the Event Types, make sure you selected Blob Created, which is what we want for Snowpipe. Then, choose Storage Queues as the Endpoint Type.
Don’t forget to choose a Storage Queue. Click Select an endpoint link that is under the Storage Queues you’ve just selected, a new blade navigation window should pop up on the right. Firstly, select your subscription, your current active subscription should already be there by default. Click Select Storage Account.
Another blade window popup letting you choose the storage account, so choose the one we’ve created.
In the final blade window, choose the storage queue we created for this, and then click Confirm Selection.
Now, you should see that the storage queue is displaying as follows.
After that, we need to create an Integration in Snowflake. Let’s firstly record some information from Azure that are needed for the integration.
Firstly, note down the URL of the storage queue. Navigate to the Storage Queue, you’ll be able to get the URL along with the Queue name as follows:
Then, go to Azure Active Directory -> Properties to get the Directory ID which will be used for Snowflake to access your Azure Subscription later.
To create an Integration in Snowflake, you’ll need to be an Account Admin. Run the below SQL command.
create notification integration SNOWPIPE_DEMO_EVENT enabled = true type = queue notification_provider = azure_storage_queue azure_storage_queue_primary_uri = '<your_storage_queue_url>' azure_tenant_id = '<your_directory_id>';
Note: It is highly recommended to use ALL UPPER CASES when defining the Integration names, to avoid case sensitivity in some Snowflake scenarios.
Tips: Once done, you can run show integrations; command to retrieve all the Integrations in your Snowflake account;
Now, Snowflake knows where to go to Azure to get the notification (Azure Events), but we still need to let Azure authenticate our Snowflake account. By default, for security purposes, we should never let our Azure Storage Account for staging our data be accessible publicly, of course.
Let’s firstly run the following SQL command in Snowflake:
DESC notification integration SNOWPIPE_DEMO_EVENT;
In the result pane, you’ll see the AZURE_CONSENT_URL property, and the login URL is accessible on the property_value column. Copy and paste it in your browser to log in to your Azure account as you usually do.
Permission granting notice should be given by Azure, click Accept button.
Once done, you should be redirected to Snowflake official website. Now you can close this web page.
Now, go to your Azure Active Directory again, click the Enterprise applications tab.
Scroll to the bottom, you will see the Snowflake application Name.
Click the name will let you go to the details of the Snowflake application integration in details. Record the Name that appears in the Properties for later usage.
Now, we need to grant Snowflake access to the Storage Queue. otherwise, it won’t get the event message.
Navigate to the Storage Account -> Access control (IAM) -> Role assignments. Snowflake is still not there, so we’ll need to add the role assignment.
Click Add button on the top, and then select Add role assignment.
In the pop-up blade window, choose Storage Queue Data Contributor as the role, as we don’t want to grant unnecessary larger permission to it. Then, type in “snowflake” to search in the Select input field, the Snowflake application account name should be retrieved. If you have multiple Snowflake accounts, make sure you select the correct one that you recorded in the above section. Then, click the save button to apply the change.
Now, you can see the Snowflake account in the Role assignments list.
Let’s create a Snowflake stage first. This will be used by the Snowpipe as the data source.
Create a Database:
CREATE DATABASE SNOWPIPE_DEMO;
Let’s use the PUBLIC schema because this is just an experiment.
To create a Snowflake external stage, we need to get the Azure Blob Container URL and SAS (Shared Access Signature). Let’s go to the Storage Account -> Properties to get the URL.
Then, go to the Shared access signature tab to create a SAS token. Here, I would like to change the year the 1 year after, so the token will be valid for one year. You may want to use a different end date time based on your requirements. After that, click Generate SAS and connection string.
The SAS URL should be shown as follows. Please note that this is an URL, the token should be the string that starts from the question mark “?”
The completed SQL command is shown as follows (Please note that this is an example, you will need to replace the url and credentials with yours):
CREATE OR REPLACE STAGE "SNOWPIPE_DEMO"."PUBLIC"."DEMO_STAGE" url = 'azure://snowpipestorage20191214.blob.core.windows.net/snowpipe-source-blob/' credentials = (azure_sas_token= '?sv=2019-02-02&ss=bfqt&srt=sco&sp=rwdlacup&se=2020-12-14T18:44:03Z&st=2019-12-14T10:44:03Z&spr=https&sig=ZPN2qcMw64k44td90gSMzvC7yZuQjnQZZCD2xAUS25Y%3D' );
Let’s test the connection between Snowflake and the Blob Container. Open your text editor and write the following content, and then save the file as emp.csv
1,Chris2,John3,Jade
Upload to the Blob Container.
Then, run the following command in Snowflake. You should be able to see the file in the result pane.
ls @"SNOWPIPE_DEMO"."PUBLIC"."DEMO_STAGE";
Now we reach the final stage, creating the Snowpipe. Let’s firstly create a table as the destination of the Snowpipe.
CREATE OR REPLACE TABLE "SNOWPIPE_DEMO"."PUBLIC"."EMPLOYEE" ( id STRING, name STRING);
Then, create the Snowpipe using the following SQL command
CREATE OR REPLACE pipe "SNOWPIPE_DEMO"."PUBLIC"."DEMO_PIPE" auto_ingest = true integration = 'SNOWPIPE_DEMO_EVENT' as copy into "SNOWPIPE_DEMO"."PUBLIC"."EMPLOYEE" from @"SNOWPIPE_DEMO"."PUBLIC"."DEMO_STAGE" file_format = (type = 'CSV');
Now, you’ll be able to show the pipe that you’ve just created.
SHOW PIPES;
The emp.csv file had been there in the Blob Container before we created the Snowpipe. So, it won’t automatically load the file, since it relies on the “Blob Created” Event to trigger itself, but that event happened before it was created.
We do have an approach to load the existing files in the Blob Container. Using the command below will manually refresh the Snowpipe to let it loading any files existing in the Blob Container but haven’t been loaded.
ALTER PIPE "SNOWPIPE_DEMO"."PUBLIC"."DEMO_PIPE" REFRESH;
Once you run this command, the result pane shows as follows, which means that the loading request has been sent to the emp.csv file:
Now, we can ran SELECT * FROM EMPLOYEE and you’ll see the rows loaded from the file.
Finally, let’s test the Snowpipe by uploading a new file to the Blob Container.
Create the emp_2.csv file as follows, and upload it to the snowpipe-source-blob Blob Container.
4, Alex5, Olivier6, Frank
Wait for a while, retrieve the EMPLOYEE table again, the new records are loaded!
This tutorial has covered how to create a Snowpipe and focusing on “utilising Azure Portal” rather than using Azure CLI like the Snowflake official documentation does.
If you’re interested in what is the best practice of building an automated data pipeline in Snowflake, from the data ingestion to the production databases, please keep an eye on the next post on this topic. It will cover Snowflake Streams and Tasks.
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above) | [
{
"code": null,
"e": 441,
"s": 172,
"text": "Snowpipe is a built-in data ingestion mechanism of Snowflake Data Warehouse. It is able to monitor and automatically pick up flat files from cloud storage (e.g. Azure Blob Storage, Amazon S3) and use the “COPY INTO” SQL command to load the data into a Snowflake table."
},
{
"code": null,
"e": 501,
"s": 441,
"text": "In the official documentation, you’ll find a nice tutorial:"
},
{
"code": null,
"e": 624,
"s": 501,
"text": "Automating Snowpipe for Azure Blob Storagehttps://docs.snowflake.net/manuals/user-guide/data-load-snowpipe-auto-azure.html"
},
{
"code": null,
"e": 1127,
"s": 624,
"text": "However, this article uses Azure CLI (command line interface) to build the cloud storage component and the Azure Event Subscription. In my opinion, this is not intuitive enough especially for new users and the people who do not have enough knowledge of Azure. Even though they can build the Snowpipe following these commands, it is still might be agnostics for the overall architecture and data flow. In other words, this tutorial tells you how to build a Snowpipe, but difficult to let you understand."
},
{
"code": null,
"e": 1321,
"s": 1127,
"text": "In this tutorial, I’ll introduce how to build a Snowpipe using the Azure Portal, which is the Web-based UI of Azure, which I believe will give you better intuition about how the Snowpipe works."
},
{
"code": null,
"e": 1650,
"s": 1321,
"text": "To begin with, let’s create a resource group to organise the storage accounts that are going to be built for Snowpipe. On your Azure Portal, navigate to Resource groups and click Add. Then, input the name for this resource group. You may choose a region that is identical/close to your Snowflake region for the best performance."
},
{
"code": null,
"e": 1729,
"s": 1650,
"text": "Then, let’s create the storage account for staging and event queuing messages."
},
{
"code": null,
"e": 1927,
"s": 1729,
"text": "In the official tutorial, there are two storage accounts created, one blob storage for staging the flat files, and another storage account with a storage queue to facilitate the Event subscription."
},
{
"code": null,
"e": 2075,
"s": 1927,
"text": "In fact, I found that actually one Azure Storage Account with both Blob Container and Storage Queue is enough. Let’s create such a storage account."
},
{
"code": null,
"e": 2265,
"s": 2075,
"text": "In the resource group we’ve just created, click the Add button to create a resource. In the Azure Marketplace, choose the Storage category and in the “Featured” list choose Storage Account."
},
{
"code": null,
"e": 2480,
"s": 2265,
"text": "Note that the name of the storage account should be unique globally, so I added the date as the suffix. This is because every storage account has a DNS CName can be accessed (https://<name>.queue.core.windows.net)."
},
{
"code": null,
"e": 2653,
"s": 2480,
"text": "Make sure you choose “StorageV2” for the Account kind to have both Blob Container and Storage Queue. Then, click Review + create to validate and create the storage account."
},
{
"code": null,
"e": 2733,
"s": 2653,
"text": "Now we have a storage account. But before we can utilise it, we need to create:"
},
{
"code": null,
"e": 2803,
"s": 2733,
"text": "A Blob Container for the staged files that will be loaded by Snowpipe"
},
{
"code": null,
"e": 2861,
"s": 2803,
"text": "A Storage Queue as the endpoint of the Event subscription"
},
{
"code": null,
"e": 3035,
"s": 2861,
"text": "To create the Blob Container, click the Containers button, then click +Container. Give a name to this container whichever makes sense to you, and then click OK to create it."
},
{
"code": null,
"e": 3099,
"s": 3035,
"text": "We’ve got a Blob Container now. Let’s create the Storage Queue."
},
{
"code": null,
"e": 3185,
"s": 3099,
"text": "Go back to the Storage Account Overview page. Click Queues to create a Storage Queue."
},
{
"code": null,
"e": 3299,
"s": 3185,
"text": "Next, let’s create the Event Grid Subscription for the Blob Container, and set the endpoint to the Storage Queue."
},
{
"code": null,
"e": 3368,
"s": 3299,
"text": "Navigate to the Storage Account -> Containers, click the Events tab."
},
{
"code": null,
"e": 3461,
"s": 3368,
"text": "There should not be any Event Subscriptions there. Click + Event Subscription to create one."
},
{
"code": null,
"e": 3682,
"s": 3461,
"text": "Give a name to the Event Subscription. Choose the default Event Grid Schema. For the Event Types, make sure you selected Blob Created, which is what we want for Snowpipe. Then, choose Storage Queues as the Endpoint Type."
},
{
"code": null,
"e": 3999,
"s": 3682,
"text": "Don’t forget to choose a Storage Queue. Click Select an endpoint link that is under the Storage Queues you’ve just selected, a new blade navigation window should pop up on the right. Firstly, select your subscription, your current active subscription should already be there by default. Click Select Storage Account."
},
{
"code": null,
"e": 4099,
"s": 3999,
"text": "Another blade window popup letting you choose the storage account, so choose the one we’ve created."
},
{
"code": null,
"e": 4206,
"s": 4099,
"text": "In the final blade window, choose the storage queue we created for this, and then click Confirm Selection."
},
{
"code": null,
"e": 4275,
"s": 4206,
"text": "Now, you should see that the storage queue is displaying as follows."
},
{
"code": null,
"e": 4420,
"s": 4275,
"text": "After that, we need to create an Integration in Snowflake. Let’s firstly record some information from Azure that are needed for the integration."
},
{
"code": null,
"e": 4568,
"s": 4420,
"text": "Firstly, note down the URL of the storage queue. Navigate to the Storage Queue, you’ll be able to get the URL along with the Queue name as follows:"
},
{
"code": null,
"e": 4715,
"s": 4568,
"text": "Then, go to Azure Active Directory -> Properties to get the Directory ID which will be used for Snowflake to access your Azure Subscription later."
},
{
"code": null,
"e": 4817,
"s": 4715,
"text": "To create an Integration in Snowflake, you’ll need to be an Account Admin. Run the below SQL command."
},
{
"code": null,
"e": 5048,
"s": 4817,
"text": "create notification integration SNOWPIPE_DEMO_EVENT enabled = true type = queue notification_provider = azure_storage_queue azure_storage_queue_primary_uri = '<your_storage_queue_url>' azure_tenant_id = '<your_directory_id>';"
},
{
"code": null,
"e": 5194,
"s": 5048,
"text": "Note: It is highly recommended to use ALL UPPER CASES when defining the Integration names, to avoid case sensitivity in some Snowflake scenarios."
},
{
"code": null,
"e": 5310,
"s": 5194,
"text": "Tips: Once done, you can run show integrations; command to retrieve all the Integrations in your Snowflake account;"
},
{
"code": null,
"e": 5596,
"s": 5310,
"text": "Now, Snowflake knows where to go to Azure to get the notification (Azure Events), but we still need to let Azure authenticate our Snowflake account. By default, for security purposes, we should never let our Azure Storage Account for staging our data be accessible publicly, of course."
},
{
"code": null,
"e": 5654,
"s": 5596,
"text": "Let’s firstly run the following SQL command in Snowflake:"
},
{
"code": null,
"e": 5705,
"s": 5654,
"text": "DESC notification integration SNOWPIPE_DEMO_EVENT;"
},
{
"code": null,
"e": 5915,
"s": 5705,
"text": "In the result pane, you’ll see the AZURE_CONSENT_URL property, and the login URL is accessible on the property_value column. Copy and paste it in your browser to log in to your Azure account as you usually do."
},
{
"code": null,
"e": 5989,
"s": 5915,
"text": "Permission granting notice should be given by Azure, click Accept button."
},
{
"code": null,
"e": 6089,
"s": 5989,
"text": "Once done, you should be redirected to Snowflake official website. Now you can close this web page."
},
{
"code": null,
"e": 6174,
"s": 6089,
"text": "Now, go to your Azure Active Directory again, click the Enterprise applications tab."
},
{
"code": null,
"e": 6241,
"s": 6174,
"text": "Scroll to the bottom, you will see the Snowflake application Name."
},
{
"code": null,
"e": 6404,
"s": 6241,
"text": "Click the name will let you go to the details of the Snowflake application integration in details. Record the Name that appears in the Properties for later usage."
},
{
"code": null,
"e": 6508,
"s": 6404,
"text": "Now, we need to grant Snowflake access to the Storage Queue. otherwise, it won’t get the event message."
},
{
"code": null,
"e": 6657,
"s": 6508,
"text": "Navigate to the Storage Account -> Access control (IAM) -> Role assignments. Snowflake is still not there, so we’ll need to add the role assignment."
},
{
"code": null,
"e": 6723,
"s": 6657,
"text": "Click Add button on the top, and then select Add role assignment."
},
{
"code": null,
"e": 7155,
"s": 6723,
"text": "In the pop-up blade window, choose Storage Queue Data Contributor as the role, as we don’t want to grant unnecessary larger permission to it. Then, type in “snowflake” to search in the Select input field, the Snowflake application account name should be retrieved. If you have multiple Snowflake accounts, make sure you select the correct one that you recorded in the above section. Then, click the save button to apply the change."
},
{
"code": null,
"e": 7224,
"s": 7155,
"text": "Now, you can see the Snowflake account in the Role assignments list."
},
{
"code": null,
"e": 7316,
"s": 7224,
"text": "Let’s create a Snowflake stage first. This will be used by the Snowpipe as the data source."
},
{
"code": null,
"e": 7335,
"s": 7316,
"text": "Create a Database:"
},
{
"code": null,
"e": 7366,
"s": 7335,
"text": "CREATE DATABASE SNOWPIPE_DEMO;"
},
{
"code": null,
"e": 7430,
"s": 7366,
"text": "Let’s use the PUBLIC schema because this is just an experiment."
},
{
"code": null,
"e": 7609,
"s": 7430,
"text": "To create a Snowflake external stage, we need to get the Azure Blob Container URL and SAS (Shared Access Signature). Let’s go to the Storage Account -> Properties to get the URL."
},
{
"code": null,
"e": 7901,
"s": 7609,
"text": "Then, go to the Shared access signature tab to create a SAS token. Here, I would like to change the year the 1 year after, so the token will be valid for one year. You may want to use a different end date time based on your requirements. After that, click Generate SAS and connection string."
},
{
"code": null,
"e": 8044,
"s": 7901,
"text": "The SAS URL should be shown as follows. Please note that this is an URL, the token should be the string that starts from the question mark “?”"
},
{
"code": null,
"e": 8190,
"s": 8044,
"text": "The completed SQL command is shown as follows (Please note that this is an example, you will need to replace the url and credentials with yours):"
},
{
"code": null,
"e": 8531,
"s": 8190,
"text": "CREATE OR REPLACE STAGE \"SNOWPIPE_DEMO\".\"PUBLIC\".\"DEMO_STAGE\" url = 'azure://snowpipestorage20191214.blob.core.windows.net/snowpipe-source-blob/' credentials = (azure_sas_token= '?sv=2019-02-02&ss=bfqt&srt=sco&sp=rwdlacup&se=2020-12-14T18:44:03Z&st=2019-12-14T10:44:03Z&spr=https&sig=ZPN2qcMw64k44td90gSMzvC7yZuQjnQZZCD2xAUS25Y%3D' );"
},
{
"code": null,
"e": 8688,
"s": 8531,
"text": "Let’s test the connection between Snowflake and the Blob Container. Open your text editor and write the following content, and then save the file as emp.csv"
},
{
"code": null,
"e": 8708,
"s": 8688,
"text": "1,Chris2,John3,Jade"
},
{
"code": null,
"e": 8738,
"s": 8708,
"text": "Upload to the Blob Container."
},
{
"code": null,
"e": 8839,
"s": 8738,
"text": "Then, run the following command in Snowflake. You should be able to see the file in the result pane."
},
{
"code": null,
"e": 8882,
"s": 8839,
"text": "ls @\"SNOWPIPE_DEMO\".\"PUBLIC\".\"DEMO_STAGE\";"
},
{
"code": null,
"e": 9000,
"s": 8882,
"text": "Now we reach the final stage, creating the Snowpipe. Let’s firstly create a table as the destination of the Snowpipe."
},
{
"code": null,
"e": 9089,
"s": 9000,
"text": "CREATE OR REPLACE TABLE \"SNOWPIPE_DEMO\".\"PUBLIC\".\"EMPLOYEE\" ( id STRING, name STRING);"
},
{
"code": null,
"e": 9147,
"s": 9089,
"text": "Then, create the Snowpipe using the following SQL command"
},
{
"code": null,
"e": 9391,
"s": 9147,
"text": "CREATE OR REPLACE pipe \"SNOWPIPE_DEMO\".\"PUBLIC\".\"DEMO_PIPE\" auto_ingest = true integration = 'SNOWPIPE_DEMO_EVENT' as copy into \"SNOWPIPE_DEMO\".\"PUBLIC\".\"EMPLOYEE\" from @\"SNOWPIPE_DEMO\".\"PUBLIC\".\"DEMO_STAGE\" file_format = (type = 'CSV');"
},
{
"code": null,
"e": 9454,
"s": 9391,
"text": "Now, you’ll be able to show the pipe that you’ve just created."
},
{
"code": null,
"e": 9466,
"s": 9454,
"text": "SHOW PIPES;"
},
{
"code": null,
"e": 9704,
"s": 9466,
"text": "The emp.csv file had been there in the Blob Container before we created the Snowpipe. So, it won’t automatically load the file, since it relies on the “Blob Created” Event to trigger itself, but that event happened before it was created."
},
{
"code": null,
"e": 9920,
"s": 9704,
"text": "We do have an approach to load the existing files in the Blob Container. Using the command below will manually refresh the Snowpipe to let it loading any files existing in the Blob Container but haven’t been loaded."
},
{
"code": null,
"e": 9977,
"s": 9920,
"text": "ALTER PIPE \"SNOWPIPE_DEMO\".\"PUBLIC\".\"DEMO_PIPE\" REFRESH;"
},
{
"code": null,
"e": 10110,
"s": 9977,
"text": "Once you run this command, the result pane shows as follows, which means that the loading request has been sent to the emp.csv file:"
},
{
"code": null,
"e": 10195,
"s": 10110,
"text": "Now, we can ran SELECT * FROM EMPLOYEE and you’ll see the rows loaded from the file."
},
{
"code": null,
"e": 10275,
"s": 10195,
"text": "Finally, let’s test the Snowpipe by uploading a new file to the Blob Container."
},
{
"code": null,
"e": 10371,
"s": 10275,
"text": "Create the emp_2.csv file as follows, and upload it to the snowpipe-source-blob Blob Container."
},
{
"code": null,
"e": 10397,
"s": 10371,
"text": "4, Alex5, Olivier6, Frank"
},
{
"code": null,
"e": 10478,
"s": 10397,
"text": "Wait for a while, retrieve the EMPLOYEE table again, the new records are loaded!"
},
{
"code": null,
"e": 10646,
"s": 10478,
"text": "This tutorial has covered how to create a Snowpipe and focusing on “utilising Azure Portal” rather than using Azure CLI like the Snowflake official documentation does."
},
{
"code": null,
"e": 10896,
"s": 10646,
"text": "If you’re interested in what is the best practice of building an automated data pipeline in Snowflake, from the data ingestion to the production databases, please keep an eye on the next post on this topic. It will cover Snowflake Streams and Tasks."
},
{
"code": null,
"e": 10907,
"s": 10896,
"text": "medium.com"
}
] |
How to display HTML element with JavaScript? | Use the visibility property in JavaScript to show an element. You can try to run the following code to learn how to work with visibility property:
<!DOCTYPE html>
<html>
<body>
<p id="pid">Demo Text</p>
<button type = "button" onclick = "displayHide()"> Hide </button>
<button type = "button" onclick = "displayShow()"> Show </button>
<script>
function displayHide() {
document.getElementById("pid").style.visibility = "hidden";
}
function displayShow() {
document.getElementById("pid").style.visibility = "visible";
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1209,
"s": 1062,
"text": "Use the visibility property in JavaScript to show an element. You can try to run the following code to learn how to work with visibility property:"
},
{
"code": null,
"e": 1703,
"s": 1209,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <p id=\"pid\">Demo Text</p>\n <button type = \"button\" onclick = \"displayHide()\"> Hide </button>\n <button type = \"button\" onclick = \"displayShow()\"> Show </button>\n <script>\n function displayHide() {\n document.getElementById(\"pid\").style.visibility = \"hidden\";\n }\n function displayShow() {\n document.getElementById(\"pid\").style.visibility = \"visible\";\n }\n </script>\n </body>\n</html>"
}
] |
Angular CLI - ng test Command | This chapter explains the syntax, argument and options of ng test command along with an example.
The syntax for ng test command is as follows −
ng test <project> [options]
ng t <project> [options]
ng test run the unit test cases on angular app code.
The argument for ng test command is as follows −
Options are optional parameters.
Output a code coverage report.
Default: false
A named build target, as specified in the "configurations" section of angular.json. Each named target is accompanied by a configuration of option defaults for that target. Setting this explicitly overrides the "--prod" flag
Aliases: -c
Shows a help message for this command in the console.
Default: false
Globs of files to include, relative to workspace or project root. There are 2 special cases −
when a path to directory is provided, all spec files ending ".spec.@(ts|tsx)" will be included.
when a path to directory is provided, all spec files ending ".spec.@(ts|tsx)" will be included.
when a path to a file is provided, and a matching spec file exists it will be included instead.
when a path to a file is provided, and a matching spec file exists it will be included instead.
Do not use the real path when resolving modules.
Default: false
Output sourcemaps.
Default: true
First move to an angular project updated using ng build command.The link for this chapter is https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm.
Now run the test command.
An example for ng test command is given below −
\>Node\>TutorialsPoint> ng test
...
WARN: ''app-goals' is not a known element:
1. If 'app-goals' is an Angular component, then verify that it is part of this module.
2. If 'app-goals' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.'
Chrome 83.0.4103 (Windows 7.0.0): Executed 0 of 4 SUCCESS (0 secs / 0 secs)
...
AppComponent should render title FAILED
TypeError: Cannot read property 'textContent' of null
at <Jasmine>
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/app.component.spec.ts:33:51)
...
Chrome 83.0.4103 (Windows 7.0.0): Executed 1 of 4 (1 FAILED) (0 secs / 0.203 secs)
...
Chrome 83.0.4103 (Windows 7.0.0): Executed 2 of 4 (1 FAILED) (0 secs / 0.221 secs)
...
Chrome 83.0.4103 (Windows 7.0.0): Executed 4 of 4 (1 FAILED) (0 secs / 0.244 sec
Chrome 83.0.4103 (Windows 7.0.0): Executed 4 of 4 (1 FAILED) (0.282 secs / 0.244
secs)
TOTAL: 1 FAILED, 3 SUCCESS
Now to fix failures update the app.component.spec.ts
app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});
Now run the test command.
An example is given below −
\>Node\>TutorialsPoint> ng test
...
WARN: ''app-goals' is not a known element:
1. If 'app-goals' is an Angular component, then verify that it is part of this m
odule.
2. If 'app-goals' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@
NgModule.schemas' of this component to suppress this message.'
Chrome 83.0.4103 (Windows 7.0.0): Executed 1 of 2 SUCCESS (0 secs / 0.053 secs)
...
Chrome 83.0.4103 (Windows 7.0.0): Executed 2 of 2 SUCCESS (0.097 secs / 0.073 se
cs)
TOTAL: 2 SUCCESS
ng test also opens the browser and displays the test status.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2172,
"s": 2075,
"text": "This chapter explains the syntax, argument and options of ng test command along with an example."
},
{
"code": null,
"e": 2219,
"s": 2172,
"text": "The syntax for ng test command is as follows −"
},
{
"code": null,
"e": 2273,
"s": 2219,
"text": "ng test <project> [options]\nng t <project> [options]\n"
},
{
"code": null,
"e": 2327,
"s": 2273,
"text": "ng test run the unit test cases on angular app code. "
},
{
"code": null,
"e": 2376,
"s": 2327,
"text": "The argument for ng test command is as follows −"
},
{
"code": null,
"e": 2409,
"s": 2376,
"text": "Options are optional parameters."
},
{
"code": null,
"e": 2440,
"s": 2409,
"text": "Output a code coverage report."
},
{
"code": null,
"e": 2455,
"s": 2440,
"text": "Default: false"
},
{
"code": null,
"e": 2679,
"s": 2455,
"text": "A named build target, as specified in the \"configurations\" section of angular.json. Each named target is accompanied by a configuration of option defaults for that target. Setting this explicitly overrides the \"--prod\" flag"
},
{
"code": null,
"e": 2691,
"s": 2679,
"text": "Aliases: -c"
},
{
"code": null,
"e": 2745,
"s": 2691,
"text": "Shows a help message for this command in the console."
},
{
"code": null,
"e": 2760,
"s": 2745,
"text": "Default: false"
},
{
"code": null,
"e": 2854,
"s": 2760,
"text": "Globs of files to include, relative to workspace or project root. There are 2 special cases −"
},
{
"code": null,
"e": 2950,
"s": 2854,
"text": "when a path to directory is provided, all spec files ending \".spec.@(ts|tsx)\" will be included."
},
{
"code": null,
"e": 3046,
"s": 2950,
"text": "when a path to directory is provided, all spec files ending \".spec.@(ts|tsx)\" will be included."
},
{
"code": null,
"e": 3142,
"s": 3046,
"text": "when a path to a file is provided, and a matching spec file exists it will be included instead."
},
{
"code": null,
"e": 3238,
"s": 3142,
"text": "when a path to a file is provided, and a matching spec file exists it will be included instead."
},
{
"code": null,
"e": 3287,
"s": 3238,
"text": "Do not use the real path when resolving modules."
},
{
"code": null,
"e": 3302,
"s": 3287,
"text": "Default: false"
},
{
"code": null,
"e": 3321,
"s": 3302,
"text": "Output sourcemaps."
},
{
"code": null,
"e": 3335,
"s": 3321,
"text": "Default: true"
},
{
"code": null,
"e": 3497,
"s": 3335,
"text": "First move to an angular project updated using ng build command.The link for this chapter is https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm."
},
{
"code": null,
"e": 3523,
"s": 3497,
"text": "Now run the test command."
},
{
"code": null,
"e": 3571,
"s": 3523,
"text": "An example for ng test command is given below −"
},
{
"code": null,
"e": 4572,
"s": 3571,
"text": "\\>Node\\>TutorialsPoint> ng test\n...\nWARN: ''app-goals' is not a known element:\n1. If 'app-goals' is an Angular component, then verify that it is part of this module.\n2. If 'app-goals' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.'\nChrome 83.0.4103 (Windows 7.0.0): Executed 0 of 4 SUCCESS (0 secs / 0 secs)\n...\nAppComponent should render title FAILED\n TypeError: Cannot read property 'textContent' of null\n at <Jasmine>\n at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/app.component.spec.ts:33:51)\n ...\nChrome 83.0.4103 (Windows 7.0.0): Executed 1 of 4 (1 FAILED) (0 secs / 0.203 secs)\n...\nChrome 83.0.4103 (Windows 7.0.0): Executed 2 of 4 (1 FAILED) (0 secs / 0.221 secs)\n...\nChrome 83.0.4103 (Windows 7.0.0): Executed 4 of 4 (1 FAILED) (0 secs / 0.244 sec\nChrome 83.0.4103 (Windows 7.0.0): Executed 4 of 4 (1 FAILED) (0.282 secs / 0.244\n secs)\nTOTAL: 1 FAILED, 3 SUCCESS\n"
},
{
"code": null,
"e": 4625,
"s": 4572,
"text": "Now to fix failures update the app.component.spec.ts"
},
{
"code": null,
"e": 4647,
"s": 4625,
"text": "app.component.spec.ts"
},
{
"code": null,
"e": 5268,
"s": 4647,
"text": "import { TestBed, async } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { AppComponent } from './app.component';\n\ndescribe('AppComponent', () => {\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [\n RouterTestingModule\n ],\n declarations: [\n AppComponent\n ],\n }).compileComponents();\n }));\n\n it('should create the app', () => {\n const fixture = TestBed.createComponent(AppComponent);\n const app = fixture.componentInstance;\n expect(app).toBeTruthy();\n });\n});"
},
{
"code": null,
"e": 5294,
"s": 5268,
"text": "Now run the test command."
},
{
"code": null,
"e": 5322,
"s": 5294,
"text": "An example is given below −"
},
{
"code": null,
"e": 5820,
"s": 5322,
"text": "\\>Node\\>TutorialsPoint> ng test\n...\nWARN: ''app-goals' is not a known element:\n1. If 'app-goals' is an Angular component, then verify that it is part of this m\nodule.\n2. If 'app-goals' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@\nNgModule.schemas' of this component to suppress this message.'\nChrome 83.0.4103 (Windows 7.0.0): Executed 1 of 2 SUCCESS (0 secs / 0.053 secs)\n...\nChrome 83.0.4103 (Windows 7.0.0): Executed 2 of 2 SUCCESS (0.097 secs / 0.073 se\ncs)\nTOTAL: 2 SUCCESS\n"
},
{
"code": null,
"e": 5881,
"s": 5820,
"text": "ng test also opens the browser and displays the test status."
},
{
"code": null,
"e": 5916,
"s": 5881,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5930,
"s": 5916,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5965,
"s": 5930,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5979,
"s": 5965,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6014,
"s": 5979,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6034,
"s": 6014,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6069,
"s": 6034,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6086,
"s": 6069,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6119,
"s": 6086,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6131,
"s": 6119,
"text": " Senol Atac"
},
{
"code": null,
"e": 6166,
"s": 6131,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6178,
"s": 6166,
"text": " Senol Atac"
},
{
"code": null,
"e": 6185,
"s": 6178,
"text": " Print"
},
{
"code": null,
"e": 6196,
"s": 6185,
"text": " Add Notes"
}
] |
How to add a margin to a tkinter window? - GeeksforGeeks | 18 Nov, 2021
In this article, we will see how to add a margin to the Tkinter window.
We will use the frame for adding the margin:
Syntax:
Frame(root, options)
Approach:
Importing the module.
Create the main window (container)
Use frame and frame.pack()
Apply the event Trigger on the widgets.
Without using frame method:
Python3
# importing the modulefrom tkinter import * # main containerroot = Tk() # container contentlabel = Label(root, text='GeeksForGeeks.org!', width=45, height=10) label.pack() root.mainloop()
Output :
Example 1:
By using the frame method of this module. With frame() we have used pack() function to place the content and to create margin.
window.pack(options)
Options are fill, expand or side.
Below is the implementation:
Python3
# importing modulefrom tkinter import * # main containerroot = Tk() # frameframe = Frame(root, relief = 'sunken', bd = 1, bg = 'white')frame.pack(fill = 'both', expand = True, padx = 10, pady = 10) # container contentlabel = Label(frame, text = 'GeeksForGeeks.org!', width = 45, height = 10, bg = "black", fg = "white")label.pack() root.mainloop()
Output :
Example 2: We can also the grid() method of the module to give margin to the container or window.
Syntax :
window.grid(grid_options)
Python3
# importing the modulefrom tkinter import * # container windowroot = Tk() # frameframe = Frame(root) # content of the frameframe.text = Text(root)frame.text.insert('1.0', 'Geeks for Geeks') # to add margin to the frameframe.text.grid(row = 0, column = 1, padx = 20, pady = 20) # simple buttonframe.quitw = Button(root)frame.quitw["text"] = "Logout",frame.quitw["command"] = root.quitframe.quitw.grid(row = 1, column = 1) root.mainloop()
Output :
simranarora5sos
kalrap615
Picked
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 23974,
"s": 23901,
"text": "In this article, we will see how to add a margin to the Tkinter window. "
},
{
"code": null,
"e": 24019,
"s": 23974,
"text": "We will use the frame for adding the margin:"
},
{
"code": null,
"e": 24027,
"s": 24019,
"text": "Syntax:"
},
{
"code": null,
"e": 24048,
"s": 24027,
"text": "Frame(root, options)"
},
{
"code": null,
"e": 24058,
"s": 24048,
"text": "Approach:"
},
{
"code": null,
"e": 24080,
"s": 24058,
"text": "Importing the module."
},
{
"code": null,
"e": 24115,
"s": 24080,
"text": "Create the main window (container)"
},
{
"code": null,
"e": 24142,
"s": 24115,
"text": "Use frame and frame.pack()"
},
{
"code": null,
"e": 24182,
"s": 24142,
"text": "Apply the event Trigger on the widgets."
},
{
"code": null,
"e": 24210,
"s": 24182,
"text": "Without using frame method:"
},
{
"code": null,
"e": 24218,
"s": 24210,
"text": "Python3"
},
{
"code": "# importing the modulefrom tkinter import * # main containerroot = Tk() # container contentlabel = Label(root, text='GeeksForGeeks.org!', width=45, height=10) label.pack() root.mainloop()",
"e": 24419,
"s": 24218,
"text": null
},
{
"code": null,
"e": 24429,
"s": 24419,
"text": "Output : "
},
{
"code": null,
"e": 24441,
"s": 24429,
"text": "Example 1: "
},
{
"code": null,
"e": 24569,
"s": 24441,
"text": "By using the frame method of this module. With frame() we have used pack() function to place the content and to create margin. "
},
{
"code": null,
"e": 24590,
"s": 24569,
"text": "window.pack(options)"
},
{
"code": null,
"e": 24624,
"s": 24590,
"text": "Options are fill, expand or side."
},
{
"code": null,
"e": 24654,
"s": 24624,
"text": "Below is the implementation: "
},
{
"code": null,
"e": 24662,
"s": 24654,
"text": "Python3"
},
{
"code": "# importing modulefrom tkinter import * # main containerroot = Tk() # frameframe = Frame(root, relief = 'sunken', bd = 1, bg = 'white')frame.pack(fill = 'both', expand = True, padx = 10, pady = 10) # container contentlabel = Label(frame, text = 'GeeksForGeeks.org!', width = 45, height = 10, bg = \"black\", fg = \"white\")label.pack() root.mainloop()",
"e": 25059,
"s": 24662,
"text": null
},
{
"code": null,
"e": 25070,
"s": 25059,
"text": "Output : "
},
{
"code": null,
"e": 25168,
"s": 25070,
"text": "Example 2: We can also the grid() method of the module to give margin to the container or window."
},
{
"code": null,
"e": 25179,
"s": 25168,
"text": "Syntax : "
},
{
"code": null,
"e": 25206,
"s": 25179,
"text": "window.grid(grid_options) "
},
{
"code": null,
"e": 25214,
"s": 25206,
"text": "Python3"
},
{
"code": "# importing the modulefrom tkinter import * # container windowroot = Tk() # frameframe = Frame(root) # content of the frameframe.text = Text(root)frame.text.insert('1.0', 'Geeks for Geeks') # to add margin to the frameframe.text.grid(row = 0, column = 1, padx = 20, pady = 20) # simple buttonframe.quitw = Button(root)frame.quitw[\"text\"] = \"Logout\",frame.quitw[\"command\"] = root.quitframe.quitw.grid(row = 1, column = 1) root.mainloop()",
"e": 25666,
"s": 25214,
"text": null
},
{
"code": null,
"e": 25677,
"s": 25666,
"text": "Output : "
},
{
"code": null,
"e": 25695,
"s": 25679,
"text": "simranarora5sos"
},
{
"code": null,
"e": 25705,
"s": 25695,
"text": "kalrap615"
},
{
"code": null,
"e": 25712,
"s": 25705,
"text": "Picked"
},
{
"code": null,
"e": 25727,
"s": 25712,
"text": "Python-tkinter"
},
{
"code": null,
"e": 25734,
"s": 25727,
"text": "Python"
},
{
"code": null,
"e": 25832,
"s": 25734,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25841,
"s": 25832,
"text": "Comments"
},
{
"code": null,
"e": 25854,
"s": 25841,
"text": "Old Comments"
},
{
"code": null,
"e": 25875,
"s": 25854,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 25907,
"s": 25875,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25930,
"s": 25907,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 25952,
"s": 25930,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25979,
"s": 25952,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 25995,
"s": 25979,
"text": "Deque in Python"
},
{
"code": null,
"e": 26037,
"s": 25995,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26093,
"s": 26037,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26138,
"s": 26093,
"text": "Python - Ways to remove duplicates from list"
}
] |
AWS DynamoDB - Read Data from a Table - GeeksforGeeks | 22 Mar, 2021
AWS DynamoDB is a NoSQL managed database that stores semi-structured data i.e. key-value and document data. It stores data in form of an item. An item consists of attributes. Upon table creation in DynamoDB, it only requires a primary key to differentiate between items and no schema is to be defined. Each item can have a different number of attributes.
Example 1:
{
"ArticleID": 1,
"NameofArticle": "DynamoDB"
}
Example 2:
{
"ArticleID": 3,
"NameofArticle": "Cloudwatch",
"Service": "AWS"
}
To read data from a DynamoDB table, there are 3 ways:
get-item – This is used in AWS Command Line Interface (CLI). To retrieve an item you must specify a table name and keys that you want to retrieve.Query – The items in the table can be retrieved by querying on the table. While querying, it by default contains the primary key as a search filter. More attributes can be added to refine search.Scan – It is similar to the query. The only difference is that it doesn’t have any attribute by default for searching. To search an item, you must define an attribute, and its value to find the item.
get-item – This is used in AWS Command Line Interface (CLI). To retrieve an item you must specify a table name and keys that you want to retrieve.
Query – The items in the table can be retrieved by querying on the table. While querying, it by default contains the primary key as a search filter. More attributes can be added to refine search.
Scan – It is similar to the query. The only difference is that it doesn’t have any attribute by default for searching. To search an item, you must define an attribute, and its value to find the item.
Create Table and Items: To read data from a table, the table and data inside the table should exist. In this example, a table named geeksforgeeks has already been created with few items inside it. See the below image:
To read data through Amazon Console we have two ways.
Scan Method: To use the scan method, select Scan from the dropdown. Then in the filter add one attribute. In this example, we want all the articles written by Rohan Chopra. Therefore, add attribute WrittenBy as the filter and enter the value as ‘Rohan Chopra’. Click on start search to get results. See the below image:
Query Method – To use the query method, select Query from the dropdown. By default, we will have our partition key as one search filter. We can add more attributes in the filter to refine our search. In the following image, we see that partition key ArticleID is already present. But we also add one more search filter i.e. Service.
The following image is of the invalid query. The query contains ArticleID=2 and Service=’AWS‘.
We see that the item ArticleID=2 does not have any attribute as Service. Therefore, no records were found.
Cloud-Computing
Picked
Amazon Web Services
DynamoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install Python3 on AWS EC2?
How to Connect to Amazon Linux Instance from Windows Client Operating System using PUTTY?
Amazon S3 - Cross Region Replication
Amazon EC2 - Creating an Elastic Cloud Compute Instance
AWS DynamoDB - PartiQL Insert Statement
How to Mock AWS DynamoDB Services for Unit Testing?
DynamoDB - Local Installation
AWS DynamoDB - Introduction to DynamoDB Accelerator (DAX)
DynamoDB - Data Types
DynamoDB - Using the Console | [
{
"code": null,
"e": 25156,
"s": 25128,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 25512,
"s": 25156,
"text": "AWS DynamoDB is a NoSQL managed database that stores semi-structured data i.e. key-value and document data. It stores data in form of an item. An item consists of attributes. Upon table creation in DynamoDB, it only requires a primary key to differentiate between items and no schema is to be defined. Each item can have a different number of attributes. "
},
{
"code": null,
"e": 25661,
"s": 25512,
"text": "Example 1:\n{\n \"ArticleID\": 1,\n \"NameofArticle\": \"DynamoDB\"\n}\n\nExample 2:\n{\n \"ArticleID\": 3,\n \"NameofArticle\": \"Cloudwatch\",\n \"Service\": \"AWS\"\n}"
},
{
"code": null,
"e": 25715,
"s": 25661,
"text": "To read data from a DynamoDB table, there are 3 ways:"
},
{
"code": null,
"e": 26256,
"s": 25715,
"text": "get-item – This is used in AWS Command Line Interface (CLI). To retrieve an item you must specify a table name and keys that you want to retrieve.Query – The items in the table can be retrieved by querying on the table. While querying, it by default contains the primary key as a search filter. More attributes can be added to refine search.Scan – It is similar to the query. The only difference is that it doesn’t have any attribute by default for searching. To search an item, you must define an attribute, and its value to find the item."
},
{
"code": null,
"e": 26403,
"s": 26256,
"text": "get-item – This is used in AWS Command Line Interface (CLI). To retrieve an item you must specify a table name and keys that you want to retrieve."
},
{
"code": null,
"e": 26599,
"s": 26403,
"text": "Query – The items in the table can be retrieved by querying on the table. While querying, it by default contains the primary key as a search filter. More attributes can be added to refine search."
},
{
"code": null,
"e": 26799,
"s": 26599,
"text": "Scan – It is similar to the query. The only difference is that it doesn’t have any attribute by default for searching. To search an item, you must define an attribute, and its value to find the item."
},
{
"code": null,
"e": 27017,
"s": 26799,
"text": "Create Table and Items: To read data from a table, the table and data inside the table should exist. In this example, a table named geeksforgeeks has already been created with few items inside it. See the below image:"
},
{
"code": null,
"e": 27071,
"s": 27017,
"text": "To read data through Amazon Console we have two ways."
},
{
"code": null,
"e": 27391,
"s": 27071,
"text": "Scan Method: To use the scan method, select Scan from the dropdown. Then in the filter add one attribute. In this example, we want all the articles written by Rohan Chopra. Therefore, add attribute WrittenBy as the filter and enter the value as ‘Rohan Chopra’. Click on start search to get results. See the below image:"
},
{
"code": null,
"e": 27724,
"s": 27391,
"text": "Query Method – To use the query method, select Query from the dropdown. By default, we will have our partition key as one search filter. We can add more attributes in the filter to refine our search. In the following image, we see that partition key ArticleID is already present. But we also add one more search filter i.e. Service."
},
{
"code": null,
"e": 27820,
"s": 27724,
"text": "The following image is of the invalid query. The query contains ArticleID=2 and Service=’AWS‘. "
},
{
"code": null,
"e": 27927,
"s": 27820,
"text": "We see that the item ArticleID=2 does not have any attribute as Service. Therefore, no records were found."
},
{
"code": null,
"e": 27943,
"s": 27927,
"text": "Cloud-Computing"
},
{
"code": null,
"e": 27950,
"s": 27943,
"text": "Picked"
},
{
"code": null,
"e": 27970,
"s": 27950,
"text": "Amazon Web Services"
},
{
"code": null,
"e": 27979,
"s": 27970,
"text": "DynamoDB"
},
{
"code": null,
"e": 28077,
"s": 27979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28086,
"s": 28077,
"text": "Comments"
},
{
"code": null,
"e": 28099,
"s": 28086,
"text": "Old Comments"
},
{
"code": null,
"e": 28134,
"s": 28099,
"text": "How to Install Python3 on AWS EC2?"
},
{
"code": null,
"e": 28224,
"s": 28134,
"text": "How to Connect to Amazon Linux Instance from Windows Client Operating System using PUTTY?"
},
{
"code": null,
"e": 28261,
"s": 28224,
"text": "Amazon S3 - Cross Region Replication"
},
{
"code": null,
"e": 28317,
"s": 28261,
"text": "Amazon EC2 - Creating an Elastic Cloud Compute Instance"
},
{
"code": null,
"e": 28357,
"s": 28317,
"text": "AWS DynamoDB - PartiQL Insert Statement"
},
{
"code": null,
"e": 28409,
"s": 28357,
"text": "How to Mock AWS DynamoDB Services for Unit Testing?"
},
{
"code": null,
"e": 28439,
"s": 28409,
"text": "DynamoDB - Local Installation"
},
{
"code": null,
"e": 28497,
"s": 28439,
"text": "AWS DynamoDB - Introduction to DynamoDB Accelerator (DAX)"
},
{
"code": null,
"e": 28519,
"s": 28497,
"text": "DynamoDB - Data Types"
}
] |
Exploring Brent Oil Prices Data using Python | by Sadrach Pierre, Ph.D. | Towards Data Science | In this post, we will perform some simple exploratory analysis on the Brent Oil Prices dataset. We start by importing the pandas library and reading the data into a pandas data frame:
import pandas as pddf = pd.read_csv("BrentOilPRices.csv")
We can also display the first five rows:
print(df.head())
Next, we can convert the ‘Date’ column into a datetime object and view the first five rows:
df['Date'] = pd.to_datetime(df['Date'])print(df.head())
We can also view the last five rows of data:
print(df.head())
We can see from the data that the prices are from 1987–2019. We can also see that there are 8,216 rows of data. Next, we can plot the prices vs. time using the ‘seaborn’ data visualization package:
import seaborn as snssns.set()plt.title('Brent Oil Prices')sns.lineplot(df['Date'], df['Price'])
We can also look at the distribution of prices:
In the next post we will build a simple regression model to predict future Brent Oil prices. The code from this post is available on GitHub. Thanks for reading. Good luck and happy machine learning! | [
{
"code": null,
"e": 356,
"s": 172,
"text": "In this post, we will perform some simple exploratory analysis on the Brent Oil Prices dataset. We start by importing the pandas library and reading the data into a pandas data frame:"
},
{
"code": null,
"e": 414,
"s": 356,
"text": "import pandas as pddf = pd.read_csv(\"BrentOilPRices.csv\")"
},
{
"code": null,
"e": 455,
"s": 414,
"text": "We can also display the first five rows:"
},
{
"code": null,
"e": 472,
"s": 455,
"text": "print(df.head())"
},
{
"code": null,
"e": 564,
"s": 472,
"text": "Next, we can convert the ‘Date’ column into a datetime object and view the first five rows:"
},
{
"code": null,
"e": 620,
"s": 564,
"text": "df['Date'] = pd.to_datetime(df['Date'])print(df.head())"
},
{
"code": null,
"e": 665,
"s": 620,
"text": "We can also view the last five rows of data:"
},
{
"code": null,
"e": 682,
"s": 665,
"text": "print(df.head())"
},
{
"code": null,
"e": 880,
"s": 682,
"text": "We can see from the data that the prices are from 1987–2019. We can also see that there are 8,216 rows of data. Next, we can plot the prices vs. time using the ‘seaborn’ data visualization package:"
},
{
"code": null,
"e": 977,
"s": 880,
"text": "import seaborn as snssns.set()plt.title('Brent Oil Prices')sns.lineplot(df['Date'], df['Price'])"
},
{
"code": null,
"e": 1025,
"s": 977,
"text": "We can also look at the distribution of prices:"
}
] |
Obj-C Memory Management | Memory management is one of the most important process in any programming language. It is the process by which the memory of objects are allocated when they are required and deallocated when they are no longer required.
Managing object memory is a matter of performance; if an application doesn't free unneeded objects, its memory footprint grows and performance suffers.
Objective-C Memory management techniques can be broadly classified into two types.
"Manual Retain-Release" or MRR
"Automatic Reference Counting" or ARC
In MRR, we explicitly manage memory by keeping track of objects on our own. This is implemented using a model, known as reference counting, that the Foundation class NSObject provides in conjunction with the runtime environment.
The only difference between MRR and ARC is that the retain and release is handled by us manually in former while its automatically taken care of in the latter.
The following figure represents an example of how memory management work in Objective-C.
The memory life cycle of the Class A object is shown in the above figure. As you can see, the retain count is shown below the object, when the retain count of an object becomes 0, the object is freed completely and its memory is deallocated for other objects to use.
Class A object is first created using alloc/init method available in NSObject. Now, the retain count becomes 1.
Now, class B retains the Class A's Object and the retain count of Class A's object becomes 2.
Then, Class C makes a copy of the object. Now, it is created as another instance of Class A with same values for the instance variables. Here, the retain count is 1 and not the retain count of the original object. This is represented by the dotted line in the figure.
The copied object is released by Class C using the release method and the retain count becomes 0 and hence the object is destroyed.
In case of the initial Class A Object, the retain count is 2 and it has to be released twice in order for it to be destroyed. This is done by release statements of Class A and Class B which decrements the retain count to 1 and 0, respectively. Finally, the object is destroyed.
We own any object we create: We create an object using a method whose name begins with "alloc", "new", "copy", or "mutableCopy"
We own any object we create: We create an object using a method whose name begins with "alloc", "new", "copy", or "mutableCopy"
We can take ownership of an object using retain: A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. We use retain in two situations −
In the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value.
To prevent an object from being invalidated as a side-effect of some other operation.
We can take ownership of an object using retain: A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. We use retain in two situations −
In the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value.
In the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value.
To prevent an object from being invalidated as a side-effect of some other operation.
To prevent an object from being invalidated as a side-effect of some other operation.
When we no longer need it, we must relinquish ownership of an object we own: We relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as "releasing" an object.
When we no longer need it, we must relinquish ownership of an object we own: We relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as "releasing" an object.
You must not relinquish ownership of an object you do not own: This is just corollary of the previous policy rules stated explicitly.
You must not relinquish ownership of an object you do not own: This is just corollary of the previous policy rules stated explicitly.
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
- (void)sampleMethod;
@end
@implementation SampleClass
- (void)sampleMethod {
NSLog(@"Hello, World! \n");
}
- (void)dealloc {
NSLog(@"Object deallocated");
[super dealloc];
}
@end
int main() {
/* my first program in Objective-C */
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass sampleMethod];
NSLog(@"Retain Count after initial allocation: %d",
[sampleClass retainCount]);
[sampleClass retain];
NSLog(@"Retain Count after retain: %d", [sampleClass retainCount]);
[sampleClass release];
NSLog(@"Retain Count after release: %d", [sampleClass retainCount]);
[sampleClass release];
NSLog(@"SampleClass dealloc will be called before this");
// Should set the object to nil
sampleClass = nil;
return 0;
}
When we compile the above program, we will get the following output.
2013-09-28 04:39:52.310 demo[8385] Hello, World!
2013-09-28 04:39:52.311 demo[8385] Retain Count after initial allocation: 1
2013-09-28 04:39:52.311 demo[8385] Retain Count after retain: 2
2013-09-28 04:39:52.311 demo[8385] Retain Count after release: 1
2013-09-28 04:39:52.311 demo[8385] Object deallocated
2013-09-28 04:39:52.311 demo[8385] SampleClass dealloc will be called before this
In Automatic Reference Counting or ARC, the system uses the same reference counting system as MRR, but it inserts the appropriate memory management method calls for us at compile-time. We are strongly encouraged to use ARC for new projects. If we use ARC, there is typically no need to understand the underlying implementation described in this document, although it may in some situations be helpful. For more about ARC, see Transitioning to ARC Release Notes.
As mentioned above, in ARC, we need not add release and retain methods since that will be taken care by the compiler. Actually, the underlying process of Objective-C is still the same. It uses the retain and release operations internally making it easier for the developer to code without worrying about these operations, which will reduce both the amount of code written and the possibility of memory leaks.
There was another principle called garbage collection, which is used in Mac OS-X along with MRR, but since its deprecation in OS-X Mountain Lion, it has not been discussed along with MRR. Also, iOS objects never had garbage collection feature. And with ARC, there is no use of garbage collection in OS-X too.
Here is a simple ARC example. Note this won't work on online compiler since it does not support ARC.
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
- (void)sampleMethod;
@end
@implementation SampleClass
- (void)sampleMethod {
NSLog(@"Hello, World! \n");
}
- (void)dealloc {
NSLog(@"Object deallocated");
}
@end
int main() {
/* my first program in Objective-C */
@autoreleasepool {
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass sampleMethod];
sampleClass = nil;
}
return 0;
}
When we compile the above program, we will get the following output.
2013-09-28 04:45:47.310 demo[8385] Hello, World!
2013-09-28 04:45:47.311 demo[8385] Object deallocated
18 Lectures
1 hours
PARTHA MAJUMDAR
6 Lectures
25 mins
Ken Burke
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2780,
"s": 2560,
"text": "Memory management is one of the most important process in any programming language. It is the process by which the memory of objects are allocated when they are required and deallocated when they are no longer required."
},
{
"code": null,
"e": 2932,
"s": 2780,
"text": "Managing object memory is a matter of performance; if an application doesn't free unneeded objects, its memory footprint grows and performance suffers."
},
{
"code": null,
"e": 3015,
"s": 2932,
"text": "Objective-C Memory management techniques can be broadly classified into two types."
},
{
"code": null,
"e": 3046,
"s": 3015,
"text": "\"Manual Retain-Release\" or MRR"
},
{
"code": null,
"e": 3084,
"s": 3046,
"text": "\"Automatic Reference Counting\" or ARC"
},
{
"code": null,
"e": 3313,
"s": 3084,
"text": "In MRR, we explicitly manage memory by keeping track of objects on our own. This is implemented using a model, known as reference counting, that the Foundation class NSObject provides in conjunction with the runtime environment."
},
{
"code": null,
"e": 3473,
"s": 3313,
"text": "The only difference between MRR and ARC is that the retain and release is handled by us manually in former while its automatically taken care of in the latter."
},
{
"code": null,
"e": 3562,
"s": 3473,
"text": "The following figure represents an example of how memory management work in Objective-C."
},
{
"code": null,
"e": 3829,
"s": 3562,
"text": "The memory life cycle of the Class A object is shown in the above figure. As you can see, the retain count is shown below the object, when the retain count of an object becomes 0, the object is freed completely and its memory is deallocated for other objects to use."
},
{
"code": null,
"e": 3941,
"s": 3829,
"text": "Class A object is first created using alloc/init method available in NSObject. Now, the retain count becomes 1."
},
{
"code": null,
"e": 4035,
"s": 3941,
"text": "Now, class B retains the Class A's Object and the retain count of Class A's object becomes 2."
},
{
"code": null,
"e": 4303,
"s": 4035,
"text": "Then, Class C makes a copy of the object. Now, it is created as another instance of Class A with same values for the instance variables. Here, the retain count is 1 and not the retain count of the original object. This is represented by the dotted line in the figure."
},
{
"code": null,
"e": 4435,
"s": 4303,
"text": "The copied object is released by Class C using the release method and the retain count becomes 0 and hence the object is destroyed."
},
{
"code": null,
"e": 4713,
"s": 4435,
"text": "In case of the initial Class A Object, the retain count is 2 and it has to be released twice in order for it to be destroyed. This is done by release statements of Class A and Class B which decrements the retain count to 1 and 0, respectively. Finally, the object is destroyed."
},
{
"code": null,
"e": 4841,
"s": 4713,
"text": "We own any object we create: We create an object using a method whose name begins with \"alloc\", \"new\", \"copy\", or \"mutableCopy\""
},
{
"code": null,
"e": 4969,
"s": 4841,
"text": "We own any object we create: We create an object using a method whose name begins with \"alloc\", \"new\", \"copy\", or \"mutableCopy\""
},
{
"code": null,
"e": 5435,
"s": 4969,
"text": "We can take ownership of an object using retain: A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. We use retain in two situations −\n\nIn the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value.\n To prevent an object from being invalidated as a side-effect of some other operation.\n\n"
},
{
"code": null,
"e": 5679,
"s": 5435,
"text": "We can take ownership of an object using retain: A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. We use retain in two situations −"
},
{
"code": null,
"e": 5811,
"s": 5679,
"text": "In the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value."
},
{
"code": null,
"e": 5943,
"s": 5811,
"text": "In the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value."
},
{
"code": null,
"e": 6030,
"s": 5943,
"text": " To prevent an object from being invalidated as a side-effect of some other operation."
},
{
"code": null,
"e": 6117,
"s": 6030,
"text": " To prevent an object from being invalidated as a side-effect of some other operation."
},
{
"code": null,
"e": 6410,
"s": 6117,
"text": "When we no longer need it, we must relinquish ownership of an object we own: We relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as \"releasing\" an object."
},
{
"code": null,
"e": 6703,
"s": 6410,
"text": "When we no longer need it, we must relinquish ownership of an object we own: We relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as \"releasing\" an object."
},
{
"code": null,
"e": 6837,
"s": 6703,
"text": "You must not relinquish ownership of an object you do not own: This is just corollary of the previous policy rules stated explicitly."
},
{
"code": null,
"e": 6971,
"s": 6837,
"text": "You must not relinquish ownership of an object you do not own: This is just corollary of the previous policy rules stated explicitly."
},
{
"code": null,
"e": 7828,
"s": 6971,
"text": "#import <Foundation/Foundation.h>\n\n@interface SampleClass:NSObject\n- (void)sampleMethod;\n@end\n\n@implementation SampleClass\n- (void)sampleMethod {\n NSLog(@\"Hello, World! \\n\");\n}\n\n- (void)dealloc {\n NSLog(@\"Object deallocated\");\n [super dealloc];\n}\n\n@end\n\nint main() {\n \n /* my first program in Objective-C */\n SampleClass *sampleClass = [[SampleClass alloc]init];\n [sampleClass sampleMethod];\n \n NSLog(@\"Retain Count after initial allocation: %d\", \n [sampleClass retainCount]);\n [sampleClass retain];\n \n NSLog(@\"Retain Count after retain: %d\", [sampleClass retainCount]);\n [sampleClass release];\n NSLog(@\"Retain Count after release: %d\", [sampleClass retainCount]);\n [sampleClass release];\n NSLog(@\"SampleClass dealloc will be called before this\");\n \n // Should set the object to nil\n sampleClass = nil;\n return 0;\n}"
},
{
"code": null,
"e": 7897,
"s": 7828,
"text": "When we compile the above program, we will get the following output."
},
{
"code": null,
"e": 8287,
"s": 7897,
"text": "2013-09-28 04:39:52.310 demo[8385] Hello, World!\n2013-09-28 04:39:52.311 demo[8385] Retain Count after initial allocation: 1\n2013-09-28 04:39:52.311 demo[8385] Retain Count after retain: 2\n2013-09-28 04:39:52.311 demo[8385] Retain Count after release: 1\n2013-09-28 04:39:52.311 demo[8385] Object deallocated\n2013-09-28 04:39:52.311 demo[8385] SampleClass dealloc will be called before this"
},
{
"code": null,
"e": 8749,
"s": 8287,
"text": "In Automatic Reference Counting or ARC, the system uses the same reference counting system as MRR, but it inserts the appropriate memory management method calls for us at compile-time. We are strongly encouraged to use ARC for new projects. If we use ARC, there is typically no need to understand the underlying implementation described in this document, although it may in some situations be helpful. For more about ARC, see Transitioning to ARC Release Notes."
},
{
"code": null,
"e": 9158,
"s": 8749,
"text": "As mentioned above, in ARC, we need not add release and retain methods since that will be taken care by the compiler. Actually, the underlying process of Objective-C is still the same. It uses the retain and release operations internally making it easier for the developer to code without worrying about these operations, which will reduce both the amount of code written and the possibility of memory leaks."
},
{
"code": null,
"e": 9467,
"s": 9158,
"text": "There was another principle called garbage collection, which is used in Mac OS-X along with MRR, but since its deprecation in OS-X Mountain Lion, it has not been discussed along with MRR. Also, iOS objects never had garbage collection feature. And with ARC, there is no use of garbage collection in OS-X too."
},
{
"code": null,
"e": 9568,
"s": 9467,
"text": "Here is a simple ARC example. Note this won't work on online compiler since it does not support ARC."
},
{
"code": null,
"e": 10023,
"s": 9568,
"text": "#import <Foundation/Foundation.h>\n\n@interface SampleClass:NSObject\n- (void)sampleMethod;\n@end\n\n@implementation SampleClass\n- (void)sampleMethod {\n NSLog(@\"Hello, World! \\n\");\n}\n\n- (void)dealloc {\n NSLog(@\"Object deallocated\");\n}\n\n@end\n\nint main() {\n /* my first program in Objective-C */\n @autoreleasepool {\n SampleClass *sampleClass = [[SampleClass alloc]init];\n [sampleClass sampleMethod];\n sampleClass = nil;\n }\n return 0;\n}"
},
{
"code": null,
"e": 10092,
"s": 10023,
"text": "When we compile the above program, we will get the following output."
},
{
"code": null,
"e": 10196,
"s": 10092,
"text": "2013-09-28 04:45:47.310 demo[8385] Hello, World!\n2013-09-28 04:45:47.311 demo[8385] Object deallocated\n"
},
{
"code": null,
"e": 10229,
"s": 10196,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10246,
"s": 10229,
"text": " PARTHA MAJUMDAR"
},
{
"code": null,
"e": 10277,
"s": 10246,
"text": "\n 6 Lectures \n 25 mins\n"
},
{
"code": null,
"e": 10288,
"s": 10277,
"text": " Ken Burke"
},
{
"code": null,
"e": 10295,
"s": 10288,
"text": " Print"
},
{
"code": null,
"e": 10306,
"s": 10295,
"text": " Add Notes"
}
] |
Face Detection, Recognition and Emotion Detection in 8 lines of code! | by Priya Dwivedi | Towards Data Science | Humans have always had the innate ability to recognize and distinguish between faces. Now computers are able to do the same. This opens up tons of applications. Face detection and Recognition can be used to improve access and security like the latest Apple Iphone does (see gif below), allow payments to be processed without physical cards — iphone does this too!, enable criminal identification and allow personalized healthcare and other services. Face detection and recognition is a heavily researched topic and there are tons of resources online. We have tried multiple open source projects to find the ones that are simplest to implement while being accurate. We have also created a pipeline for detection, recognition and emotion understanding on any input image with just 8 lines of code after the images have been loaded! Our code is open sourced on Github.
This blog is divided into 3 parts:
Facial Detection — Ability to detect the location of face in any input image or frame. The output is the bounding box coordinates of the detected facesFacial Recognition — Compare multiple faces together to identify which faces belong to the same person. This is done by comparing face embedding vectorsEmotion Detection — Classifying the emotion on the face as happy, angry, sad, neutral, surprise, disgust or fear
Facial Detection — Ability to detect the location of face in any input image or frame. The output is the bounding box coordinates of the detected faces
Facial Recognition — Compare multiple faces together to identify which faces belong to the same person. This is done by comparing face embedding vectors
Emotion Detection — Classifying the emotion on the face as happy, angry, sad, neutral, surprise, disgust or fear
So let’s get started!
Facial detection is the first part of our pipeline. We have used the python library Face Recognition that we found easy to install and very accurate in detecting faces. This library scans the input image and returns the bounding box coordinates of all detected faces as shown below:
The below snippet shows how to use the face_recognition library for detecting faces.
face_locations = face_recognition.face_locations(image)top, right, bottom, left = face_locations[0]face_image = image[top:bottom, left:right]
Complete instructions for installing face recognition and using it are also on Github
Facial Recognition verifies if two faces are same. The use of facial recognition is huge in security, bio-metrics, entertainment, personal safety, etc. The same python library face_recognition used for face detection can also be used for face recognition. Our testing showed it had good performance. Given two faces match, they can be matched with each other giving the result as True or False. The steps involved in facial recognition are
Find face in an image
Analyze facial feature
Compare features for the 2 input faces
Returns True if matched or else False.
The code snippet that does this is below. We create face encoding vectors for both faces and then use a built in function to compare the distance between the vectors.
encoding_1 = face_recognition.face_encodings(image1)[0]encoding_2 = face_recognition.face_encodings(image1)[0]results = face_recognition.compare_faces([encoding_1], encoding_2,tolerance=0.50)
Lets test the model on two images below:
As shown on the right we have 2 faces of Leonardo Di Caprio with different poses. In the first one the face is also not a frontal shot. When we run the recognition using the code shared above, face recognition is able to understand that the two faces are the same person!
Humans are used to taking in non verbal cues from facial emotions. Now computers are also getting better to reading emotions. So how do we detect emotions in an image? We have used an open source data set — Face Emotion Recognition (FER) from Kaggle and built a CNN to detect emotions. The emotions can be classified into 7 classes — happy, sad, fear, disgust, angry, neutral and surprise.
Model — We built a 6 layered Convolutional Neural Network (CNN) in Keras and use image augmentations to improve model performance. We tried many different models and have open sourced our best implementation at this link.
You can load the pretrained model and run it on an image using only 2 lines of code below:
model = load_model("./emotion_detector_models/model.hdf5")predicted_class = np.argmax(model.predict(face_image)
This blog demos how easy it can be to implement facial detection and recognition models in your applications. Facial detection can the starting point for many customized solutions. I hope you try our open sourced code for yourself.
I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/. If you have a project that we can collaborate on, then please contact me through my website or at [email protected]
You can also see my other writings at: https://medium.com/@priya.dwivedi
References:
Face Recognition Library
FaceNet — For understanding how facial recognition models are built
Emotion Detection Data Set
Good course to understand computer vision applications that we used for emotion detection model | [
{
"code": null,
"e": 1037,
"s": 171,
"text": "Humans have always had the innate ability to recognize and distinguish between faces. Now computers are able to do the same. This opens up tons of applications. Face detection and Recognition can be used to improve access and security like the latest Apple Iphone does (see gif below), allow payments to be processed without physical cards — iphone does this too!, enable criminal identification and allow personalized healthcare and other services. Face detection and recognition is a heavily researched topic and there are tons of resources online. We have tried multiple open source projects to find the ones that are simplest to implement while being accurate. We have also created a pipeline for detection, recognition and emotion understanding on any input image with just 8 lines of code after the images have been loaded! Our code is open sourced on Github."
},
{
"code": null,
"e": 1072,
"s": 1037,
"text": "This blog is divided into 3 parts:"
},
{
"code": null,
"e": 1488,
"s": 1072,
"text": "Facial Detection — Ability to detect the location of face in any input image or frame. The output is the bounding box coordinates of the detected facesFacial Recognition — Compare multiple faces together to identify which faces belong to the same person. This is done by comparing face embedding vectorsEmotion Detection — Classifying the emotion on the face as happy, angry, sad, neutral, surprise, disgust or fear"
},
{
"code": null,
"e": 1640,
"s": 1488,
"text": "Facial Detection — Ability to detect the location of face in any input image or frame. The output is the bounding box coordinates of the detected faces"
},
{
"code": null,
"e": 1793,
"s": 1640,
"text": "Facial Recognition — Compare multiple faces together to identify which faces belong to the same person. This is done by comparing face embedding vectors"
},
{
"code": null,
"e": 1906,
"s": 1793,
"text": "Emotion Detection — Classifying the emotion on the face as happy, angry, sad, neutral, surprise, disgust or fear"
},
{
"code": null,
"e": 1928,
"s": 1906,
"text": "So let’s get started!"
},
{
"code": null,
"e": 2211,
"s": 1928,
"text": "Facial detection is the first part of our pipeline. We have used the python library Face Recognition that we found easy to install and very accurate in detecting faces. This library scans the input image and returns the bounding box coordinates of all detected faces as shown below:"
},
{
"code": null,
"e": 2296,
"s": 2211,
"text": "The below snippet shows how to use the face_recognition library for detecting faces."
},
{
"code": null,
"e": 2438,
"s": 2296,
"text": "face_locations = face_recognition.face_locations(image)top, right, bottom, left = face_locations[0]face_image = image[top:bottom, left:right]"
},
{
"code": null,
"e": 2524,
"s": 2438,
"text": "Complete instructions for installing face recognition and using it are also on Github"
},
{
"code": null,
"e": 2964,
"s": 2524,
"text": "Facial Recognition verifies if two faces are same. The use of facial recognition is huge in security, bio-metrics, entertainment, personal safety, etc. The same python library face_recognition used for face detection can also be used for face recognition. Our testing showed it had good performance. Given two faces match, they can be matched with each other giving the result as True or False. The steps involved in facial recognition are"
},
{
"code": null,
"e": 2986,
"s": 2964,
"text": "Find face in an image"
},
{
"code": null,
"e": 3009,
"s": 2986,
"text": "Analyze facial feature"
},
{
"code": null,
"e": 3048,
"s": 3009,
"text": "Compare features for the 2 input faces"
},
{
"code": null,
"e": 3087,
"s": 3048,
"text": "Returns True if matched or else False."
},
{
"code": null,
"e": 3254,
"s": 3087,
"text": "The code snippet that does this is below. We create face encoding vectors for both faces and then use a built in function to compare the distance between the vectors."
},
{
"code": null,
"e": 3446,
"s": 3254,
"text": "encoding_1 = face_recognition.face_encodings(image1)[0]encoding_2 = face_recognition.face_encodings(image1)[0]results = face_recognition.compare_faces([encoding_1], encoding_2,tolerance=0.50)"
},
{
"code": null,
"e": 3487,
"s": 3446,
"text": "Lets test the model on two images below:"
},
{
"code": null,
"e": 3759,
"s": 3487,
"text": "As shown on the right we have 2 faces of Leonardo Di Caprio with different poses. In the first one the face is also not a frontal shot. When we run the recognition using the code shared above, face recognition is able to understand that the two faces are the same person!"
},
{
"code": null,
"e": 4149,
"s": 3759,
"text": "Humans are used to taking in non verbal cues from facial emotions. Now computers are also getting better to reading emotions. So how do we detect emotions in an image? We have used an open source data set — Face Emotion Recognition (FER) from Kaggle and built a CNN to detect emotions. The emotions can be classified into 7 classes — happy, sad, fear, disgust, angry, neutral and surprise."
},
{
"code": null,
"e": 4371,
"s": 4149,
"text": "Model — We built a 6 layered Convolutional Neural Network (CNN) in Keras and use image augmentations to improve model performance. We tried many different models and have open sourced our best implementation at this link."
},
{
"code": null,
"e": 4462,
"s": 4371,
"text": "You can load the pretrained model and run it on an image using only 2 lines of code below:"
},
{
"code": null,
"e": 4574,
"s": 4462,
"text": "model = load_model(\"./emotion_detector_models/model.hdf5\")predicted_class = np.argmax(model.predict(face_image)"
},
{
"code": null,
"e": 4806,
"s": 4574,
"text": "This blog demos how easy it can be to implement facial detection and recognition models in your applications. Facial detection can the starting point for many customized solutions. I hope you try our open sourced code for yourself."
},
{
"code": null,
"e": 5136,
"s": 4806,
"text": "I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/. If you have a project that we can collaborate on, then please contact me through my website or at [email protected]"
},
{
"code": null,
"e": 5209,
"s": 5136,
"text": "You can also see my other writings at: https://medium.com/@priya.dwivedi"
},
{
"code": null,
"e": 5221,
"s": 5209,
"text": "References:"
},
{
"code": null,
"e": 5246,
"s": 5221,
"text": "Face Recognition Library"
},
{
"code": null,
"e": 5314,
"s": 5246,
"text": "FaceNet — For understanding how facial recognition models are built"
},
{
"code": null,
"e": 5341,
"s": 5314,
"text": "Emotion Detection Data Set"
}
] |
Serving TensorFlow models with TF Serving | by Álvaro Bartolomé | Towards Data Science | TensorFlow Serving is a flexible, high-performance serving system for machine learning models, designed for production environments. TensorFlow Serving makes it easy to deploy new algorithms and experiments, while keeping the same server architecture and APIs. TensorFlow Serving provides out-of-the-box integration with TensorFlow models, but can be easily extended to serve other types of models and data.
Currently there are a lot of different solutions to serve ML models in production with the growth that MLOps is having nowadays as the standard procedure to work with ML models during all their lifecycle. Maybe the most popular one is TensorFlow Serving developed by TensorFlow so as to server their models in production environments.
This post is a guide on how to train, save, serve and use TensorFlow ML models in production environments. Along the GitHub repository linked to this post we will prepare and train a custom CNN model for image classification of The Simpsons Characters Data dataset, that will be later deployed using TensorFlow Serving.
So as to get a better understanding on all the process that is presented in this post, as a personal recommendation, you should read it while you check the resources available in the repository, as well as trying to reproduce it with the same or with a different TensorFlow model, as “practice makes the master”.
github.com
First of all you need to make sure that you have all the requirements installed, but before proceeding you need to know that TF-Serving is just available for Ubuntu, which means that, in order to use it you will either need a Ubuntu VM or just Docker installed in your OS so as to run a Docker container which deploys TF-Serving.
Warning! ⚠️ In case you don’t have Ubuntu, but still want to deploy TF-Serving via Docker, you don’t need to install it with APT-GET as you will not be able to, you just need to run the Dockerfile (go to the section Docker).
So, from your Ubuntu VM you need to install tensorflow-model-server, but before being able to install it you need to add the TF-Serving distribution URI as a package source as it follows:
echo "deb [arch=amd64] http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal" | sudo tee /etc/apt/sources.list.d/tensorflow-serving.list && \curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | sudo apt-key add -
And then you will be able to install tensorflow-model-server using APT-GET as it follows:
apt-get update && apt-get install tensorflow-model-server
Finally, for the client side you need to install the Python package tensorflow-serving-api, which is useful towards using the gRPC API; and, tensorflow. Note that the versions of both packages should match.
pip install tensorflow-serving-api==2.4.1pip install tensorflow==2.4.1
If you have any problems regarding the TensorFlow installation, visit Installation | TensorFlow.
The dataset that is going to be used to train the image classification model is “The Simpsons Characters Data”, which is a big Kaggle dataset that contains RGB images of some of the main The Simpsons characters including Homer, Marge, Bart, Lisa, Maggie, Barney, and much more.
The original dataset contains 42 classes of The Simpsons characters, with an unbalanced number of samples per class, and a total of 20,935 training images and 990 test images in JPG format, and the images in different sizes, but as all of them are small, we will be resizing them to 64x64px when training the model.
Anyway, we will create a custom slice of the original dataset keeping just the training set, and using a random 80/20 train-test split and removing the classes with less than 50 images. So on, we will be have 32 classes, with 13,210 training images, 3,286 validation images, and 4,142 testing images.
Once the data has been explored, we are going to proceed with the definition of the ML model, that in this case will be a CNN (Convolutional Neural Network) as we are facing an image classification problem.
The created model architecture consists on an initial Conv2D layer (that also indicates the input_shape of the net), which is a 2D convolutional layer that produces 16 filters as output of windows of 3x3 convolutions, followed by a MaxPooling2D in order to downsample the Tensor resulting from the previous convolutional layer. Usually, you will find this layer after two consecutive convolutions, but for the sake of simplicity, here we will be downsampling the data after each convolution, as this is a simple CNN with a relatively small dataset (less than 20k images).
Then we will include another combination of Conv2D and MaxPooling2D layers as increasing the number of convolutional filters means that we will provide more data to the CNN as it is capturing more combinations of pixel values from the input image Tensor.
After applying the convolutional operations, we will include a Flatten layer in order to transform the image Tensor into a 1D Tensor which prepares the data that goes through the CNN so as to include a few fully connected layers after it.
Finally, we will include some Dense fully connected layers so as to assign the final weights of the net, and some Dropout layers to avoid overfitting during the training phase. You also need to take into consideration that the latest Dense layer contains as much units as the total labels to predict, which in this case is the number of The Simpsons Characters available in the training set.
The trained model has been named SimpsonsNet (this name will be used later while serving the model as its identifier) and its architecture looks like:
Finally, once trained we will need to dump the model in SavedModel format, which is the universal serialization format for the TensorFlow models. This format provides a language-neutral format to save ML models that is recoverable and hermetic. It enables higher-level systems and tools to produce, consume and transform TensorFlow models.
The resulting model’s directory should more or less look like the following:
assets/assets.extra/variables/ variables.data-?????-of-????? variables.indexsaved_model.pb
More information regarding the SavedModel format at TensorFlow SavedModel.
Finally, as a personal recommendation you should check/keep an eye on the following courses:
🔥 Laurence Moroney’s TensorFlow Proffesional Certificate (previously Specialization) at Coursera for learning the basics of TensorFlow as you playaround with some common Deep Learning scenarios like CNNs, Time Series and NLP. So feel free to check it at Coursera | TensorFlow in Practice, and the course’s resources in GitHub at dlaicourse.
⭐ Daniel Bourke’s TensorFlow Zero to Mastery course he is currently developing and it will be completely free including a lot of resources. So feel free to check it in GitHub at tensorflow-deep-learning.
Once the model has been saved using SavedModel format, it is pretty straight forward to get TF-Serving working, if the installation succeeded. Unlike TorchServe, serving ML models in TF-Serving is simpler as you just need to have tensorflow-model-server installed and the ML model in the specified format.
tensorflow_model_server --port=8500 --rest_api_port=8501 \ --model_name=simpsonsnet \ --model_base_path=/home/saved_models/simpsonsnet
Now, even though the command is clear and self-explanatory, a more detailed explanation on the flags used is presented:
— port: this is the port to listen on for the gRPC API, the default value is 8500; but it's a common practice to still define this flag's value so as to always know the configuration of the deployed TF-Serving Server.
— rest_api_port: this is the REST API port, which is set to zero by default, which means that the REST API will not be deployed/exposed unless you manually set a port. There's no default value, it just needs to be different than the gRPC port, so we will set it to 8501 (the next port).
— model_name: this is the name of the ML model to serve, which is the one that will be exposed in the endpoint.
— model_base_path: this is the base path where the ML model that is going to be served is placed in. Note that his is the absolute path, do not use relative paths.
More information about the TF-Serving CLI available at Train and serve a TensorFlow model with TensorFlow Serving and you can also check tensorflow_model_server --help.
Once TF-Serving has been successfully deployed, you can send a sample HTTP GET request to the Model Status REST API available at http://localhost:8501/v1/models/simpsonsnet; that returns the basic information of the served ML model.
curl http://localhost:8501/v1/models/simpsonsnet
That should output something similar to the following JSON response if everything succeeded:
Note: there is not a way to gracefully shutdown server, as stated in this issue.
To shutdown the server you have two alternatives:
Getting the PID of tensorflow_model_server and killing that process:
ps aux | grep -i "tensorflow_model_server"kill -9 PID
Getting the running Docker Container ID and stopping/killing it:
docker ps # Retrieve the CONTAINER_IDdocker kill CONTAINER_ID
None of those is the recommended way of shutting down a server, as you are supposed to have a proper way to shut it down, but, currently those are the possibilities. If you have more information about this issue or a cleaner way to do this, please let me know!
In order to reproduce the TF-Serving deployment in an Ubuntu Docker image, you can use the following set of commands:
docker build -t ubuntu-tfserving:latest deployment/docker run --rm --name tfserving_docker -p8500:8500 -p8501:8501 -d ubuntu-tfserving:latest
Note: make sure that you use the -d flag in docker run so that the container runs in the background and does not block your terminal.
For more information regarding the Docker deployment, you should check TensorFlow’s explanation and notes available at TF-Serving with Docker, as it also explains how to use their Docker image (instead of a clear Ubuntu one) and some tips regarding the production deployment of the models using TF-Serving.
Along this section we will see how to interact with the deployed APIs (REST and gRPC) via Python, so as to send sample requests to classify images from The Simpsons Characters.
Regarding the REST requests to the deployed TF-Serving Prediction API you need to install the requirements as it follows:
pip install tensorflow==2.4.1pip install requests==2.25.1
And then use the following script which will send a sample The Simpsons image to be classified using the deployed model:
Now, regarding the gRPC requests to the deployed TF-Serving Prediction API you need to install the requirements as it follows:
pip install tensorflow==2.4.1pip install tensorflow-serving-api==2.4.1pip install grpcio==1.35.0
And then use the following script which will send a sample The Simpsons image to be classified using the deployed model:
To sum up, serving models with TensorFlow Serving is pretty easy thanks to the Keras SavedModel format in which the TensorFlow ML models is being dumped. TF-Serving is actively maintained by TensorFlow, which means that its usage is recommended for the LTS (Long Time Support) they provide.
Both the consistency and the ease to deploy ML models, makes TF-Serving a tool to consider in order to serve TensorFlow’s models in production environments. As the model deployment is a critical part in the MLOps lifecycle, the current ML serving solutions are a must-known if you work with the main Deep Learning frameworks (TensorFlow and PyTorch) as their serving solutions, TensorFlow Serving and TorchServe, respectively, make the ML model serving easy and scalable.
So you so highly take this into consideration when serving your ML models in production environments! ⚡
Credits for “The Simpsons Characters Dataset” to Alexandre Attia for creating it, as well as the Kaggle community that made it possible, as they included a lot of images to the original dataset (from 20 characters to up to 42, but we just used 32).
You can contact me either via Twitter or via GitHub. Or just go to AllMyLinks where you can find all my links.
🌟 Additionally you can follow me at GitHub to support me so that I keep on developing open source content! 🌟 | [
{
"code": null,
"e": 580,
"s": 172,
"text": "TensorFlow Serving is a flexible, high-performance serving system for machine learning models, designed for production environments. TensorFlow Serving makes it easy to deploy new algorithms and experiments, while keeping the same server architecture and APIs. TensorFlow Serving provides out-of-the-box integration with TensorFlow models, but can be easily extended to serve other types of models and data."
},
{
"code": null,
"e": 915,
"s": 580,
"text": "Currently there are a lot of different solutions to serve ML models in production with the growth that MLOps is having nowadays as the standard procedure to work with ML models during all their lifecycle. Maybe the most popular one is TensorFlow Serving developed by TensorFlow so as to server their models in production environments."
},
{
"code": null,
"e": 1235,
"s": 915,
"text": "This post is a guide on how to train, save, serve and use TensorFlow ML models in production environments. Along the GitHub repository linked to this post we will prepare and train a custom CNN model for image classification of The Simpsons Characters Data dataset, that will be later deployed using TensorFlow Serving."
},
{
"code": null,
"e": 1548,
"s": 1235,
"text": "So as to get a better understanding on all the process that is presented in this post, as a personal recommendation, you should read it while you check the resources available in the repository, as well as trying to reproduce it with the same or with a different TensorFlow model, as “practice makes the master”."
},
{
"code": null,
"e": 1559,
"s": 1548,
"text": "github.com"
},
{
"code": null,
"e": 1889,
"s": 1559,
"text": "First of all you need to make sure that you have all the requirements installed, but before proceeding you need to know that TF-Serving is just available for Ubuntu, which means that, in order to use it you will either need a Ubuntu VM or just Docker installed in your OS so as to run a Docker container which deploys TF-Serving."
},
{
"code": null,
"e": 2114,
"s": 1889,
"text": "Warning! ⚠️ In case you don’t have Ubuntu, but still want to deploy TF-Serving via Docker, you don’t need to install it with APT-GET as you will not be able to, you just need to run the Dockerfile (go to the section Docker)."
},
{
"code": null,
"e": 2302,
"s": 2114,
"text": "So, from your Ubuntu VM you need to install tensorflow-model-server, but before being able to install it you need to add the TF-Serving distribution URI as a package source as it follows:"
},
{
"code": null,
"e": 2622,
"s": 2302,
"text": "echo \"deb [arch=amd64] http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal\" | sudo tee /etc/apt/sources.list.d/tensorflow-serving.list && \\curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | sudo apt-key add -"
},
{
"code": null,
"e": 2712,
"s": 2622,
"text": "And then you will be able to install tensorflow-model-server using APT-GET as it follows:"
},
{
"code": null,
"e": 2770,
"s": 2712,
"text": "apt-get update && apt-get install tensorflow-model-server"
},
{
"code": null,
"e": 2977,
"s": 2770,
"text": "Finally, for the client side you need to install the Python package tensorflow-serving-api, which is useful towards using the gRPC API; and, tensorflow. Note that the versions of both packages should match."
},
{
"code": null,
"e": 3048,
"s": 2977,
"text": "pip install tensorflow-serving-api==2.4.1pip install tensorflow==2.4.1"
},
{
"code": null,
"e": 3145,
"s": 3048,
"text": "If you have any problems regarding the TensorFlow installation, visit Installation | TensorFlow."
},
{
"code": null,
"e": 3423,
"s": 3145,
"text": "The dataset that is going to be used to train the image classification model is “The Simpsons Characters Data”, which is a big Kaggle dataset that contains RGB images of some of the main The Simpsons characters including Homer, Marge, Bart, Lisa, Maggie, Barney, and much more."
},
{
"code": null,
"e": 3739,
"s": 3423,
"text": "The original dataset contains 42 classes of The Simpsons characters, with an unbalanced number of samples per class, and a total of 20,935 training images and 990 test images in JPG format, and the images in different sizes, but as all of them are small, we will be resizing them to 64x64px when training the model."
},
{
"code": null,
"e": 4040,
"s": 3739,
"text": "Anyway, we will create a custom slice of the original dataset keeping just the training set, and using a random 80/20 train-test split and removing the classes with less than 50 images. So on, we will be have 32 classes, with 13,210 training images, 3,286 validation images, and 4,142 testing images."
},
{
"code": null,
"e": 4247,
"s": 4040,
"text": "Once the data has been explored, we are going to proceed with the definition of the ML model, that in this case will be a CNN (Convolutional Neural Network) as we are facing an image classification problem."
},
{
"code": null,
"e": 4819,
"s": 4247,
"text": "The created model architecture consists on an initial Conv2D layer (that also indicates the input_shape of the net), which is a 2D convolutional layer that produces 16 filters as output of windows of 3x3 convolutions, followed by a MaxPooling2D in order to downsample the Tensor resulting from the previous convolutional layer. Usually, you will find this layer after two consecutive convolutions, but for the sake of simplicity, here we will be downsampling the data after each convolution, as this is a simple CNN with a relatively small dataset (less than 20k images)."
},
{
"code": null,
"e": 5074,
"s": 4819,
"text": "Then we will include another combination of Conv2D and MaxPooling2D layers as increasing the number of convolutional filters means that we will provide more data to the CNN as it is capturing more combinations of pixel values from the input image Tensor."
},
{
"code": null,
"e": 5313,
"s": 5074,
"text": "After applying the convolutional operations, we will include a Flatten layer in order to transform the image Tensor into a 1D Tensor which prepares the data that goes through the CNN so as to include a few fully connected layers after it."
},
{
"code": null,
"e": 5705,
"s": 5313,
"text": "Finally, we will include some Dense fully connected layers so as to assign the final weights of the net, and some Dropout layers to avoid overfitting during the training phase. You also need to take into consideration that the latest Dense layer contains as much units as the total labels to predict, which in this case is the number of The Simpsons Characters available in the training set."
},
{
"code": null,
"e": 5856,
"s": 5705,
"text": "The trained model has been named SimpsonsNet (this name will be used later while serving the model as its identifier) and its architecture looks like:"
},
{
"code": null,
"e": 6196,
"s": 5856,
"text": "Finally, once trained we will need to dump the model in SavedModel format, which is the universal serialization format for the TensorFlow models. This format provides a language-neutral format to save ML models that is recoverable and hermetic. It enables higher-level systems and tools to produce, consume and transform TensorFlow models."
},
{
"code": null,
"e": 6273,
"s": 6196,
"text": "The resulting model’s directory should more or less look like the following:"
},
{
"code": null,
"e": 6370,
"s": 6273,
"text": "assets/assets.extra/variables/ variables.data-?????-of-????? variables.indexsaved_model.pb"
},
{
"code": null,
"e": 6445,
"s": 6370,
"text": "More information regarding the SavedModel format at TensorFlow SavedModel."
},
{
"code": null,
"e": 6538,
"s": 6445,
"text": "Finally, as a personal recommendation you should check/keep an eye on the following courses:"
},
{
"code": null,
"e": 6879,
"s": 6538,
"text": "🔥 Laurence Moroney’s TensorFlow Proffesional Certificate (previously Specialization) at Coursera for learning the basics of TensorFlow as you playaround with some common Deep Learning scenarios like CNNs, Time Series and NLP. So feel free to check it at Coursera | TensorFlow in Practice, and the course’s resources in GitHub at dlaicourse."
},
{
"code": null,
"e": 7083,
"s": 6879,
"text": "⭐ Daniel Bourke’s TensorFlow Zero to Mastery course he is currently developing and it will be completely free including a lot of resources. So feel free to check it in GitHub at tensorflow-deep-learning."
},
{
"code": null,
"e": 7389,
"s": 7083,
"text": "Once the model has been saved using SavedModel format, it is pretty straight forward to get TF-Serving working, if the installation succeeded. Unlike TorchServe, serving ML models in TF-Serving is simpler as you just need to have tensorflow-model-server installed and the ML model in the specified format."
},
{
"code": null,
"e": 7570,
"s": 7389,
"text": "tensorflow_model_server --port=8500 --rest_api_port=8501 \\ --model_name=simpsonsnet \\ --model_base_path=/home/saved_models/simpsonsnet"
},
{
"code": null,
"e": 7690,
"s": 7570,
"text": "Now, even though the command is clear and self-explanatory, a more detailed explanation on the flags used is presented:"
},
{
"code": null,
"e": 7908,
"s": 7690,
"text": "— port: this is the port to listen on for the gRPC API, the default value is 8500; but it's a common practice to still define this flag's value so as to always know the configuration of the deployed TF-Serving Server."
},
{
"code": null,
"e": 8195,
"s": 7908,
"text": "— rest_api_port: this is the REST API port, which is set to zero by default, which means that the REST API will not be deployed/exposed unless you manually set a port. There's no default value, it just needs to be different than the gRPC port, so we will set it to 8501 (the next port)."
},
{
"code": null,
"e": 8307,
"s": 8195,
"text": "— model_name: this is the name of the ML model to serve, which is the one that will be exposed in the endpoint."
},
{
"code": null,
"e": 8471,
"s": 8307,
"text": "— model_base_path: this is the base path where the ML model that is going to be served is placed in. Note that his is the absolute path, do not use relative paths."
},
{
"code": null,
"e": 8640,
"s": 8471,
"text": "More information about the TF-Serving CLI available at Train and serve a TensorFlow model with TensorFlow Serving and you can also check tensorflow_model_server --help."
},
{
"code": null,
"e": 8873,
"s": 8640,
"text": "Once TF-Serving has been successfully deployed, you can send a sample HTTP GET request to the Model Status REST API available at http://localhost:8501/v1/models/simpsonsnet; that returns the basic information of the served ML model."
},
{
"code": null,
"e": 8922,
"s": 8873,
"text": "curl http://localhost:8501/v1/models/simpsonsnet"
},
{
"code": null,
"e": 9015,
"s": 8922,
"text": "That should output something similar to the following JSON response if everything succeeded:"
},
{
"code": null,
"e": 9096,
"s": 9015,
"text": "Note: there is not a way to gracefully shutdown server, as stated in this issue."
},
{
"code": null,
"e": 9146,
"s": 9096,
"text": "To shutdown the server you have two alternatives:"
},
{
"code": null,
"e": 9215,
"s": 9146,
"text": "Getting the PID of tensorflow_model_server and killing that process:"
},
{
"code": null,
"e": 9269,
"s": 9215,
"text": "ps aux | grep -i \"tensorflow_model_server\"kill -9 PID"
},
{
"code": null,
"e": 9334,
"s": 9269,
"text": "Getting the running Docker Container ID and stopping/killing it:"
},
{
"code": null,
"e": 9396,
"s": 9334,
"text": "docker ps # Retrieve the CONTAINER_IDdocker kill CONTAINER_ID"
},
{
"code": null,
"e": 9657,
"s": 9396,
"text": "None of those is the recommended way of shutting down a server, as you are supposed to have a proper way to shut it down, but, currently those are the possibilities. If you have more information about this issue or a cleaner way to do this, please let me know!"
},
{
"code": null,
"e": 9775,
"s": 9657,
"text": "In order to reproduce the TF-Serving deployment in an Ubuntu Docker image, you can use the following set of commands:"
},
{
"code": null,
"e": 9917,
"s": 9775,
"text": "docker build -t ubuntu-tfserving:latest deployment/docker run --rm --name tfserving_docker -p8500:8500 -p8501:8501 -d ubuntu-tfserving:latest"
},
{
"code": null,
"e": 10051,
"s": 9917,
"text": "Note: make sure that you use the -d flag in docker run so that the container runs in the background and does not block your terminal."
},
{
"code": null,
"e": 10358,
"s": 10051,
"text": "For more information regarding the Docker deployment, you should check TensorFlow’s explanation and notes available at TF-Serving with Docker, as it also explains how to use their Docker image (instead of a clear Ubuntu one) and some tips regarding the production deployment of the models using TF-Serving."
},
{
"code": null,
"e": 10535,
"s": 10358,
"text": "Along this section we will see how to interact with the deployed APIs (REST and gRPC) via Python, so as to send sample requests to classify images from The Simpsons Characters."
},
{
"code": null,
"e": 10657,
"s": 10535,
"text": "Regarding the REST requests to the deployed TF-Serving Prediction API you need to install the requirements as it follows:"
},
{
"code": null,
"e": 10715,
"s": 10657,
"text": "pip install tensorflow==2.4.1pip install requests==2.25.1"
},
{
"code": null,
"e": 10836,
"s": 10715,
"text": "And then use the following script which will send a sample The Simpsons image to be classified using the deployed model:"
},
{
"code": null,
"e": 10963,
"s": 10836,
"text": "Now, regarding the gRPC requests to the deployed TF-Serving Prediction API you need to install the requirements as it follows:"
},
{
"code": null,
"e": 11060,
"s": 10963,
"text": "pip install tensorflow==2.4.1pip install tensorflow-serving-api==2.4.1pip install grpcio==1.35.0"
},
{
"code": null,
"e": 11181,
"s": 11060,
"text": "And then use the following script which will send a sample The Simpsons image to be classified using the deployed model:"
},
{
"code": null,
"e": 11472,
"s": 11181,
"text": "To sum up, serving models with TensorFlow Serving is pretty easy thanks to the Keras SavedModel format in which the TensorFlow ML models is being dumped. TF-Serving is actively maintained by TensorFlow, which means that its usage is recommended for the LTS (Long Time Support) they provide."
},
{
"code": null,
"e": 11944,
"s": 11472,
"text": "Both the consistency and the ease to deploy ML models, makes TF-Serving a tool to consider in order to serve TensorFlow’s models in production environments. As the model deployment is a critical part in the MLOps lifecycle, the current ML serving solutions are a must-known if you work with the main Deep Learning frameworks (TensorFlow and PyTorch) as their serving solutions, TensorFlow Serving and TorchServe, respectively, make the ML model serving easy and scalable."
},
{
"code": null,
"e": 12048,
"s": 11944,
"text": "So you so highly take this into consideration when serving your ML models in production environments! ⚡"
},
{
"code": null,
"e": 12297,
"s": 12048,
"text": "Credits for “The Simpsons Characters Dataset” to Alexandre Attia for creating it, as well as the Kaggle community that made it possible, as they included a lot of images to the original dataset (from 20 characters to up to 42, but we just used 32)."
},
{
"code": null,
"e": 12408,
"s": 12297,
"text": "You can contact me either via Twitter or via GitHub. Or just go to AllMyLinks where you can find all my links."
}
] |
Lodash _.strContains() Method - GeeksforGeeks | 30 Sep, 2020
The Lodash _.strContains() method checks whether the given string contains the searched string or not and returns the corresponding boolean value.
Syntax:
_.strContains( string, searched_str);
Parameters: This method accepts two parameters as mentioned above and described below:
String: This method takes String in which search string is to be searched.
Searched_str: This method takes a string to be searched.
Return Value: This method returns a boolean value.
Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib –save.
Example 1:
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib'); var bool = _.strContains("GeeksforGeeks", "Geeks"); console.log("The String contains the " + "searched String : ", bool);
Output:
The String contains the searched String : true
Example 2:
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib'); var bool = _.strContains("abc", "d"); console.log("The String contains the " + "searched String : ", bool);
Output:
The String contains the searched String : false
Example 3:
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib'); var bool = _.strContains("abc", "a"); console.log("The String contains the " + "searched String : ", bool);
Output:
The String contains the searched String : true
JavaScript-Lodash
JavaScript
Web Technologies
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
How to create a link in JavaScript ?
How to Show Images on Click using HTML ?
Remove elements from a JavaScript Array
How to remove an HTML element using JavaScript ?
Express.js express.Router() Function
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 ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 25056,
"s": 24909,
"text": "The Lodash _.strContains() method checks whether the given string contains the searched string or not and returns the corresponding boolean value."
},
{
"code": null,
"e": 25064,
"s": 25056,
"text": "Syntax:"
},
{
"code": null,
"e": 25103,
"s": 25064,
"text": "_.strContains( string, searched_str);\n"
},
{
"code": null,
"e": 25190,
"s": 25103,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25265,
"s": 25190,
"text": "String: This method takes String in which search string is to be searched."
},
{
"code": null,
"e": 25322,
"s": 25265,
"text": "Searched_str: This method takes a string to be searched."
},
{
"code": null,
"e": 25373,
"s": 25322,
"text": "Return Value: This method returns a boolean value."
},
{
"code": null,
"e": 25569,
"s": 25373,
"text": "Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib –save."
},
{
"code": null,
"e": 25580,
"s": 25569,
"text": "Example 1:"
},
{
"code": null,
"e": 25591,
"s": 25580,
"text": "Javascript"
},
{
"code": "// Defining lodash contrib variable var _ = require('lodash-contrib'); var bool = _.strContains(\"GeeksforGeeks\", \"Geeks\"); console.log(\"The String contains the \" + \"searched String : \", bool);",
"e": 25794,
"s": 25591,
"text": null
},
{
"code": null,
"e": 25802,
"s": 25794,
"text": "Output:"
},
{
"code": null,
"e": 25850,
"s": 25802,
"text": "The String contains the searched String : true\n"
},
{
"code": null,
"e": 25861,
"s": 25850,
"text": "Example 2:"
},
{
"code": null,
"e": 25872,
"s": 25861,
"text": "Javascript"
},
{
"code": "// Defining lodash contrib variable var _ = require('lodash-contrib'); var bool = _.strContains(\"abc\", \"d\"); console.log(\"The String contains the \" + \"searched String : \", bool);",
"e": 26061,
"s": 25872,
"text": null
},
{
"code": null,
"e": 26069,
"s": 26061,
"text": "Output:"
},
{
"code": null,
"e": 26118,
"s": 26069,
"text": "The String contains the searched String : false\n"
},
{
"code": null,
"e": 26129,
"s": 26118,
"text": "Example 3:"
},
{
"code": null,
"e": 26140,
"s": 26129,
"text": "Javascript"
},
{
"code": "// Defining lodash contrib variable var _ = require('lodash-contrib'); var bool = _.strContains(\"abc\", \"a\"); console.log(\"The String contains the \" + \"searched String : \", bool);",
"e": 26329,
"s": 26140,
"text": null
},
{
"code": null,
"e": 26337,
"s": 26329,
"text": "Output:"
},
{
"code": null,
"e": 26385,
"s": 26337,
"text": "The String contains the searched String : true\n"
},
{
"code": null,
"e": 26403,
"s": 26385,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 26414,
"s": 26403,
"text": "JavaScript"
},
{
"code": null,
"e": 26431,
"s": 26414,
"text": "Web Technologies"
},
{
"code": null,
"e": 26529,
"s": 26431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26538,
"s": 26529,
"text": "Comments"
},
{
"code": null,
"e": 26551,
"s": 26538,
"text": "Old Comments"
},
{
"code": null,
"e": 26612,
"s": 26551,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26649,
"s": 26612,
"text": "How to create a link in JavaScript ?"
},
{
"code": null,
"e": 26690,
"s": 26649,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 26730,
"s": 26690,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26779,
"s": 26730,
"text": "How to remove an HTML element using JavaScript ?"
},
{
"code": null,
"e": 26816,
"s": 26779,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26849,
"s": 26816,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26911,
"s": 26849,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26954,
"s": 26911,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Viewing & Clipping | The primary use of clipping in computer graphics is to remove objects, lines, or line segments that are outside the viewing pane. The viewing transformation is insensitive to the position of points relative to the viewing volume − especially those points behind the viewer − and it is necessary to remove these points before generating the view.
Clipping a point from a given window is very easy. Consider the following figure, where the rectangle indicates the window. Point clipping tells us whether the given point X,Y is within the given window or not; and decides whether we will use the minimum and maximum coordinates of the window.
The X-coordinate of the given point is inside the window, if X lies in between Wx1 ≤ X ≤ Wx2. Same way, Y coordinate of the given point is inside the window, if Y lies in between Wy1 ≤ Y ≤ Wy2.
The concept of line clipping is same as point clipping. In line clipping, we will cut the portion of line which is outside of window and keep only the portion that is inside the window.
This algorithm uses the clipping window as shown in the following figure. The minimum coordinate for the clipping region is (XWmin,YWmin) and the maximum coordinate for the clipping region is (XWmax,YWmax).
We will use 4-bits to divide the entire region. These 4 bits represent the Top, Bottom, Right, and Left of the region as shown in the following figure. Here, the TOP and LEFT bit is set to 1 because it is the TOP-LEFT corner.
There are 3 possibilities for the line −
Line can be completely inside the window Thislineshouldbeaccepted.
Line can be completely inside the window Thislineshouldbeaccepted.
Line can be completely outside of the window Thislinewillbecompletelyremovedfromtheregion.
Line can be completely outside of the window Thislinewillbecompletelyremovedfromtheregion.
Line can be partially inside the window Wewillfindintersectionpointanddrawonlythatportionoflinethatisinsideregion.
Line can be partially inside the window Wewillfindintersectionpointanddrawonlythatportionoflinethatisinsideregion.
Step 1 − Assign a region code for each endpoints.
Step 2 − If both endpoints have a region code 0000 then accept this line.
Step 3 − Else, perform the logical ANDoperation for both region codes.
Step 3.1 − If the result is not 0000, then reject the line.
Step 3.2 − Else you need clipping.
Step 3.2.1 − Choose an endpoint of the line that is outside the window.
Step 3.2.2 − Find the intersection point at the window boundary baseonregioncode.
Step 3.2.3 − Replace endpoint with the intersection point and update the region code.
Step 3.2.4 − Repeat step 2 until we find a clipped line either trivially accepted or trivially rejected.
Step 4 − Repeat step 1 for other lines.
This algorithm is more efficient than Cohen-Sutherland algorithm. It employs parametric line representation and simple dot products.
Parametric equation of line is −
P0P1:P(t) = P0 + t(P1 - P0)
Let Ni be the outward normal edge Ei. Now pick any arbitrary point PEi on edge Ei then the dot product Ni.[Pt – PEi] determines whether the point Pt is “inside the clip edge” or “outside” the clip edge or “on” the clip edge.
The point Pt is inside if Ni.[Pt – PEi] < 0
The point Pt is outside if Ni.[Pt – PEi] > 0
The point Pt is on the edge if Ni.[Pt – PEi] = 0 Intersectionpoint
Ni.[Pt – PEi] = 0
Ni.[ P0 + t(P1 - P0) – PEi] = 0 ReplacingP(t with P0 + t(P1 - P0))
Ni.[P0 – PEi] + Ni.t[P1 - P0] = 0
Ni.[P0 – PEi] + Ni∙tD = 0 (substituting D for [P1 - P0])
Ni.[P0 – PEi] = - Ni∙tD
The equation for t becomes,
t=Ni.[Po−PEi]−Ni.D
It is valid for the following conditions −
Ni ≠ 0 errorcannothappen
D ≠ 0 (P1 ≠ P0)
Ni∙D ≠ 0 (P0P1 not parallel to Ei)
A polygon can also be clipped by specifying the clipping window. Sutherland Hodgeman polygon clipping algorithm is used for polygon clipping. In this algorithm, all the vertices of the polygon are clipped against each edge of the clipping window.
First the polygon is clipped against the left edge of the polygon window to get new vertices of the polygon. These new vertices are used to clip the polygon against right edge, top edge, bottom edge, of the clipping window as shown in the following figure.
While processing an edge of a polygon with clipping window, an intersection point is found if edge is not completely inside clipping window and the a partial edge from the intersection point to the outside edge is clipped. The following figures show left, right, top and bottom edge clippings −
Various techniques are used to provide text clipping in a computer graphics. It depends on the methods used to generate characters and the requirements of a particular application. There are three methods for text clipping which are listed below −
All or none string clipping
All or none character clipping
Text clipping
The following figure shows all or none string clipping −
In all or none string clipping method, either we keep the entire string or we reject entire string based on the clipping window. As shown in the above figure, STRING2 is entirely inside the clipping window so we keep it and STRING1 being only partially inside the window, we reject.
The following figure shows all or none character clipping −
This clipping method is based on characters rather than entire string. In this method if the string is entirely inside the clipping window, then we keep it. If it is partially outside the window, then −
You reject only the portion of the string being outside
You reject only the portion of the string being outside
If the character is on the boundary of the clipping window, then we discard that entire character and keep the rest string.
If the character is on the boundary of the clipping window, then we discard that entire character and keep the rest string.
The following figure shows text clipping −
This clipping method is based on characters rather than the entire string. In this method if the string is entirely inside the clipping window, then we keep it. If it is partially outside the window, then
You reject only the portion of string being outside.
You reject only the portion of string being outside.
If the character is on the boundary of the clipping window, then we discard only that portion of character that is outside of the clipping window.
If the character is on the boundary of the clipping window, then we discard only that portion of character that is outside of the clipping window.
A bitmap is a collection of pixels that describes an image. It is a type of computer graphics that the computer uses to store and display pictures. In this type of graphics, images are stored bit by bit and hence it is named Bit-map graphics. For better understanding let us consider the following example where we draw a smiley face using bit-map graphics.
Now we will see how this smiley face is stored bit by bit in computer graphics.
By observing the original smiley face closely, we can see that there are two blue lines which are represented as B1, B2 and E1, E2 in the above figure.
In the same way, the smiley is represented using the combination bits of A4, B5, C6, D6, E5, and F4 respectively.
The main disadvantages of bitmap graphics are −
We cannot resize the bitmap image. If you try to resize, the pixels get blurred.
We cannot resize the bitmap image. If you try to resize, the pixels get blurred.
Colored bitmaps can be very large.
Colored bitmaps can be very large.
107 Lectures
13.5 hours
Arnab Chakraborty
106 Lectures
8 hours
Arnab Chakraborty
99 Lectures
6 hours
Arnab Chakraborty
46 Lectures
2.5 hours
Shweta
70 Lectures
9 hours
Abhilash Nelson
52 Lectures
7 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2265,
"s": 1919,
"text": "The primary use of clipping in computer graphics is to remove objects, lines, or line segments that are outside the viewing pane. The viewing transformation is insensitive to the position of points relative to the viewing volume − especially those points behind the viewer − and it is necessary to remove these points before generating the view."
},
{
"code": null,
"e": 2559,
"s": 2265,
"text": "Clipping a point from a given window is very easy. Consider the following figure, where the rectangle indicates the window. Point clipping tells us whether the given point X,Y is within the given window or not; and decides whether we will use the minimum and maximum coordinates of the window."
},
{
"code": null,
"e": 2753,
"s": 2559,
"text": "The X-coordinate of the given point is inside the window, if X lies in between Wx1 ≤ X ≤ Wx2. Same way, Y coordinate of the given point is inside the window, if Y lies in between Wy1 ≤ Y ≤ Wy2."
},
{
"code": null,
"e": 2939,
"s": 2753,
"text": "The concept of line clipping is same as point clipping. In line clipping, we will cut the portion of line which is outside of window and keep only the portion that is inside the window."
},
{
"code": null,
"e": 3146,
"s": 2939,
"text": "This algorithm uses the clipping window as shown in the following figure. The minimum coordinate for the clipping region is (XWmin,YWmin) and the maximum coordinate for the clipping region is (XWmax,YWmax)."
},
{
"code": null,
"e": 3372,
"s": 3146,
"text": "We will use 4-bits to divide the entire region. These 4 bits represent the Top, Bottom, Right, and Left of the region as shown in the following figure. Here, the TOP and LEFT bit is set to 1 because it is the TOP-LEFT corner."
},
{
"code": null,
"e": 3413,
"s": 3372,
"text": "There are 3 possibilities for the line −"
},
{
"code": null,
"e": 3480,
"s": 3413,
"text": "Line can be completely inside the window Thislineshouldbeaccepted."
},
{
"code": null,
"e": 3547,
"s": 3480,
"text": "Line can be completely inside the window Thislineshouldbeaccepted."
},
{
"code": null,
"e": 3638,
"s": 3547,
"text": "Line can be completely outside of the window Thislinewillbecompletelyremovedfromtheregion."
},
{
"code": null,
"e": 3729,
"s": 3638,
"text": "Line can be completely outside of the window Thislinewillbecompletelyremovedfromtheregion."
},
{
"code": null,
"e": 3844,
"s": 3729,
"text": "Line can be partially inside the window Wewillfindintersectionpointanddrawonlythatportionoflinethatisinsideregion."
},
{
"code": null,
"e": 3959,
"s": 3844,
"text": "Line can be partially inside the window Wewillfindintersectionpointanddrawonlythatportionoflinethatisinsideregion."
},
{
"code": null,
"e": 4009,
"s": 3959,
"text": "Step 1 − Assign a region code for each endpoints."
},
{
"code": null,
"e": 4083,
"s": 4009,
"text": "Step 2 − If both endpoints have a region code 0000 then accept this line."
},
{
"code": null,
"e": 4154,
"s": 4083,
"text": "Step 3 − Else, perform the logical ANDoperation for both region codes."
},
{
"code": null,
"e": 4214,
"s": 4154,
"text": "Step 3.1 − If the result is not 0000, then reject the line."
},
{
"code": null,
"e": 4249,
"s": 4214,
"text": "Step 3.2 − Else you need clipping."
},
{
"code": null,
"e": 4321,
"s": 4249,
"text": "Step 3.2.1 − Choose an endpoint of the line that is outside the window."
},
{
"code": null,
"e": 4403,
"s": 4321,
"text": "Step 3.2.2 − Find the intersection point at the window boundary baseonregioncode."
},
{
"code": null,
"e": 4489,
"s": 4403,
"text": "Step 3.2.3 − Replace endpoint with the intersection point and update the region code."
},
{
"code": null,
"e": 4594,
"s": 4489,
"text": "Step 3.2.4 − Repeat step 2 until we find a clipped line either trivially accepted or trivially rejected."
},
{
"code": null,
"e": 4634,
"s": 4594,
"text": "Step 4 − Repeat step 1 for other lines."
},
{
"code": null,
"e": 4767,
"s": 4634,
"text": "This algorithm is more efficient than Cohen-Sutherland algorithm. It employs parametric line representation and simple dot products."
},
{
"code": null,
"e": 4800,
"s": 4767,
"text": "Parametric equation of line is −"
},
{
"code": null,
"e": 4829,
"s": 4800,
"text": "P0P1:P(t) = P0 + t(P1 - P0)\n"
},
{
"code": null,
"e": 5054,
"s": 4829,
"text": "Let Ni be the outward normal edge Ei. Now pick any arbitrary point PEi on edge Ei then the dot product Ni.[Pt – PEi] determines whether the point Pt is “inside the clip edge” or “outside” the clip edge or “on” the clip edge."
},
{
"code": null,
"e": 5098,
"s": 5054,
"text": "The point Pt is inside if Ni.[Pt – PEi] < 0"
},
{
"code": null,
"e": 5143,
"s": 5098,
"text": "The point Pt is outside if Ni.[Pt – PEi] > 0"
},
{
"code": null,
"e": 5210,
"s": 5143,
"text": "The point Pt is on the edge if Ni.[Pt – PEi] = 0 Intersectionpoint"
},
{
"code": null,
"e": 5228,
"s": 5210,
"text": "Ni.[Pt – PEi] = 0"
},
{
"code": null,
"e": 5295,
"s": 5228,
"text": "Ni.[ P0 + t(P1 - P0) – PEi] = 0 ReplacingP(t with P0 + t(P1 - P0))"
},
{
"code": null,
"e": 5329,
"s": 5295,
"text": "Ni.[P0 – PEi] + Ni.t[P1 - P0] = 0"
},
{
"code": null,
"e": 5386,
"s": 5329,
"text": "Ni.[P0 – PEi] + Ni∙tD = 0 (substituting D for [P1 - P0])"
},
{
"code": null,
"e": 5410,
"s": 5386,
"text": "Ni.[P0 – PEi] = - Ni∙tD"
},
{
"code": null,
"e": 5438,
"s": 5410,
"text": "The equation for t becomes,"
},
{
"code": null,
"e": 5457,
"s": 5438,
"text": "t=Ni.[Po−PEi]−Ni.D"
},
{
"code": null,
"e": 5500,
"s": 5457,
"text": "It is valid for the following conditions −"
},
{
"code": null,
"e": 5526,
"s": 5500,
"text": "Ni ≠ 0 errorcannothappen"
},
{
"code": null,
"e": 5544,
"s": 5526,
"text": "D ≠ 0 (P1 ≠ P0)"
},
{
"code": null,
"e": 5580,
"s": 5544,
"text": "Ni∙D ≠ 0 (P0P1 not parallel to Ei)"
},
{
"code": null,
"e": 5827,
"s": 5580,
"text": "A polygon can also be clipped by specifying the clipping window. Sutherland Hodgeman polygon clipping algorithm is used for polygon clipping. In this algorithm, all the vertices of the polygon are clipped against each edge of the clipping window."
},
{
"code": null,
"e": 6084,
"s": 5827,
"text": "First the polygon is clipped against the left edge of the polygon window to get new vertices of the polygon. These new vertices are used to clip the polygon against right edge, top edge, bottom edge, of the clipping window as shown in the following figure."
},
{
"code": null,
"e": 6379,
"s": 6084,
"text": "While processing an edge of a polygon with clipping window, an intersection point is found if edge is not completely inside clipping window and the a partial edge from the intersection point to the outside edge is clipped. The following figures show left, right, top and bottom edge clippings −"
},
{
"code": null,
"e": 6627,
"s": 6379,
"text": "Various techniques are used to provide text clipping in a computer graphics. It depends on the methods used to generate characters and the requirements of a particular application. There are three methods for text clipping which are listed below −"
},
{
"code": null,
"e": 6655,
"s": 6627,
"text": "All or none string clipping"
},
{
"code": null,
"e": 6686,
"s": 6655,
"text": "All or none character clipping"
},
{
"code": null,
"e": 6700,
"s": 6686,
"text": "Text clipping"
},
{
"code": null,
"e": 6757,
"s": 6700,
"text": "The following figure shows all or none string clipping −"
},
{
"code": null,
"e": 7040,
"s": 6757,
"text": "In all or none string clipping method, either we keep the entire string or we reject entire string based on the clipping window. As shown in the above figure, STRING2 is entirely inside the clipping window so we keep it and STRING1 being only partially inside the window, we reject."
},
{
"code": null,
"e": 7100,
"s": 7040,
"text": "The following figure shows all or none character clipping −"
},
{
"code": null,
"e": 7303,
"s": 7100,
"text": "This clipping method is based on characters rather than entire string. In this method if the string is entirely inside the clipping window, then we keep it. If it is partially outside the window, then −"
},
{
"code": null,
"e": 7359,
"s": 7303,
"text": "You reject only the portion of the string being outside"
},
{
"code": null,
"e": 7415,
"s": 7359,
"text": "You reject only the portion of the string being outside"
},
{
"code": null,
"e": 7539,
"s": 7415,
"text": "If the character is on the boundary of the clipping window, then we discard that entire character and keep the rest string."
},
{
"code": null,
"e": 7663,
"s": 7539,
"text": "If the character is on the boundary of the clipping window, then we discard that entire character and keep the rest string."
},
{
"code": null,
"e": 7706,
"s": 7663,
"text": "The following figure shows text clipping −"
},
{
"code": null,
"e": 7911,
"s": 7706,
"text": "This clipping method is based on characters rather than the entire string. In this method if the string is entirely inside the clipping window, then we keep it. If it is partially outside the window, then"
},
{
"code": null,
"e": 7964,
"s": 7911,
"text": "You reject only the portion of string being outside."
},
{
"code": null,
"e": 8017,
"s": 7964,
"text": "You reject only the portion of string being outside."
},
{
"code": null,
"e": 8164,
"s": 8017,
"text": "If the character is on the boundary of the clipping window, then we discard only that portion of character that is outside of the clipping window."
},
{
"code": null,
"e": 8311,
"s": 8164,
"text": "If the character is on the boundary of the clipping window, then we discard only that portion of character that is outside of the clipping window."
},
{
"code": null,
"e": 8669,
"s": 8311,
"text": "A bitmap is a collection of pixels that describes an image. It is a type of computer graphics that the computer uses to store and display pictures. In this type of graphics, images are stored bit by bit and hence it is named Bit-map graphics. For better understanding let us consider the following example where we draw a smiley face using bit-map graphics."
},
{
"code": null,
"e": 8749,
"s": 8669,
"text": "Now we will see how this smiley face is stored bit by bit in computer graphics."
},
{
"code": null,
"e": 8901,
"s": 8749,
"text": "By observing the original smiley face closely, we can see that there are two blue lines which are represented as B1, B2 and E1, E2 in the above figure."
},
{
"code": null,
"e": 9015,
"s": 8901,
"text": "In the same way, the smiley is represented using the combination bits of A4, B5, C6, D6, E5, and F4 respectively."
},
{
"code": null,
"e": 9063,
"s": 9015,
"text": "The main disadvantages of bitmap graphics are −"
},
{
"code": null,
"e": 9144,
"s": 9063,
"text": "We cannot resize the bitmap image. If you try to resize, the pixels get blurred."
},
{
"code": null,
"e": 9225,
"s": 9144,
"text": "We cannot resize the bitmap image. If you try to resize, the pixels get blurred."
},
{
"code": null,
"e": 9260,
"s": 9225,
"text": "Colored bitmaps can be very large."
},
{
"code": null,
"e": 9295,
"s": 9260,
"text": "Colored bitmaps can be very large."
},
{
"code": null,
"e": 9332,
"s": 9295,
"text": "\n 107 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 9351,
"s": 9332,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9385,
"s": 9351,
"text": "\n 106 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 9404,
"s": 9385,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9437,
"s": 9404,
"text": "\n 99 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9456,
"s": 9437,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9491,
"s": 9456,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9499,
"s": 9491,
"text": " Shweta"
},
{
"code": null,
"e": 9532,
"s": 9499,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9549,
"s": 9532,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9582,
"s": 9549,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9604,
"s": 9582,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 9611,
"s": 9604,
"text": " Print"
},
{
"code": null,
"e": 9622,
"s": 9611,
"text": " Add Notes"
}
] |
Power BI Functions — (List.Contains, List.ContainsAny, List.ContainsAll) | by Peter Hui | Towards Data Science | ...usefully tools for your data journey.
This article will introduce you to the Contains functions with lists. It’s a great function to use in Power Query. There are little nuances for each but I hope this article will help you get started.
Lists in Power Query are written with {} brackets. They can be {1,2,3} or even {1, “a”,123}. If you like to experiment, you can go to Power Query >Create a Blank Query > Advanced Editor > Replace the source information with > Source = {1,”hello”,123}.
It’s important to remember this — columns in Power query can be wrapped in {[Column A]} to return a list so you can use list functions. You can also refer to Table[Column A] to return a list as well.
There are differences in both though — creating a new column using { [ID] } in the data set below returns a single value per “cell”. While using #”Previous Step”[ID] returns an entire list nested in a “cell”.
Before you get too deep into it, check out how to build a Power BI data model in this article. Models in Power BI are a little different than Access and SQL databases.
If you want to know how to apply functions in Power BI — here is a good article.
Now back to it, why are these list functions helpful at all? It’s helpful for situations when you want to put a list through various columns in your data set to check for conditions.
Sure, you can probably use a conditional column ribbon on Power Query, but it will be very tedious to list out all the particular items you wish to check.
You can also probably do various joins with supporting tables but it will also be tedious to clean up after. You can write if statements, but what if your list is quite big?
Let’s go through the functions together.
List.ContainsAny — Here is the breakdown of the function.
Find out if the list {1, 2, 3, 4, 5} contains 3 or 4.
List.ContainsAny({1, 2, 3, 4, 5}, {3, 4})
Returns TRUE — since any 3 or 4 are in the list from {1,2,3,4,5}
List.ContainsAny({"A", "B", "C", "D", "E"}, {"F", "G"})
Returns FALSE — “F” or “G” are not in the list of {“A”, “B”, “C”, “D”, “E”}
List.Contains — here is the breakdown of the function.
Find if the list {1, 2, 3, 4, 5} contains 3. Here the function will be
List.Contains({1, 2, 3, 4, 5}, 3)
Returns TRUE
However, you may need to be careful about the item you watch to check against. There isn’t a {} for the item you want to check. The last value being compared against is expects a value and not a list so the below returns false.
List.Contains({1, 2, 3, 4, 5}, {3})
Returns FALSE.
Now instead of a single value — List.ContainsAll will return True if it is able to match ALL the items on the list against the list you want to compare against.
List.ContainsAll({1, 2, 3, 4, 5}, {4, 5})
Returns TRUE— both 4 and 5 are on the list.
Since this function requires a list to match and because of the row by row lay out in Power Query, you will need to nest this list first for this to work. (More on this below)
Let’s walk through an example.
I have a table here in power query and I will use the add columns feature to add in additional columns to use our contain functions.
Let’s add the first column to use List.Contains using the add columns button.
The result will be this column here.
Let’s create our first column. I want to check if the Store_Number 1 is anywhere in the column.
Here the column indicates that there is a store number 1 in that column of store number.
I also want to check for if there is a store number 1 and also, any reviews contains the word “Great”.
Final column, I want to check if all the Review criteria I have — {“Great”,”Good”,”Meh”} — are represented in the column.
This particular one — List.ContainsAll is a little bit different than the others.
If you are doing a custom column just like the others, it wouldn’t work because of the row context in Power Query.
Intuitively if you tried doing —
List.ContainsAll({[Reviews]},{“Great”,”Good”,”Meh”})
Will actually return FALSE, even though the items you have listed here are all represented in the column.
The issue here is the row — if you just refer to the column, Power Query takes the “cell” of the column and checks it against the list of {“Great”,”Good”,”Meh”} and returns FALSE. That particular “cell” does not contain all the items of that list so it return FALSE.
When we had used List.ContainsAny, List.Contains, they returned the right value because even if it is doing a check by each value it will still get us what we want. The difference here is we want the entire column to be nested in a “cell” before comparing to the list.
This is why we need to write.
List.ContainsAll( #PreviousStep[Reviews],{“Great”, ”Good”, “Meh”} )
Here it is referring the entire column as a list — to check against another list.
The result will return TRUE
As a bonus, these two functions are very helpful as well — List.AnyTrue and List.AllTrue.
They are very much like the others as well and you can add in other conditions instead of just checking for membership.
The great part about these functions — you can string them together with the and, or operators and create checks on your data without having to revert to joins and multiple nested statements.
TL:DR? Here is a summary for all of them —
List.Contains — Remember to exclude the {} for the search item.
List.ContainsAll — Remember to use the previous step [ column name] for the search list.
List.ContainsAny — Easiest to use. I’ve always had to use this particular one.
List.AnyTrue, List.AllTrue — You can add in conditions to them. Whole condition statement needs to be wrapped in {}
Have fun trying some of these functions in Power Query! Stay safe! | [
{
"code": null,
"e": 213,
"s": 172,
"text": "...usefully tools for your data journey."
},
{
"code": null,
"e": 413,
"s": 213,
"text": "This article will introduce you to the Contains functions with lists. It’s a great function to use in Power Query. There are little nuances for each but I hope this article will help you get started."
},
{
"code": null,
"e": 665,
"s": 413,
"text": "Lists in Power Query are written with {} brackets. They can be {1,2,3} or even {1, “a”,123}. If you like to experiment, you can go to Power Query >Create a Blank Query > Advanced Editor > Replace the source information with > Source = {1,”hello”,123}."
},
{
"code": null,
"e": 865,
"s": 665,
"text": "It’s important to remember this — columns in Power query can be wrapped in {[Column A]} to return a list so you can use list functions. You can also refer to Table[Column A] to return a list as well."
},
{
"code": null,
"e": 1074,
"s": 865,
"text": "There are differences in both though — creating a new column using { [ID] } in the data set below returns a single value per “cell”. While using #”Previous Step”[ID] returns an entire list nested in a “cell”."
},
{
"code": null,
"e": 1242,
"s": 1074,
"text": "Before you get too deep into it, check out how to build a Power BI data model in this article. Models in Power BI are a little different than Access and SQL databases."
},
{
"code": null,
"e": 1323,
"s": 1242,
"text": "If you want to know how to apply functions in Power BI — here is a good article."
},
{
"code": null,
"e": 1506,
"s": 1323,
"text": "Now back to it, why are these list functions helpful at all? It’s helpful for situations when you want to put a list through various columns in your data set to check for conditions."
},
{
"code": null,
"e": 1661,
"s": 1506,
"text": "Sure, you can probably use a conditional column ribbon on Power Query, but it will be very tedious to list out all the particular items you wish to check."
},
{
"code": null,
"e": 1835,
"s": 1661,
"text": "You can also probably do various joins with supporting tables but it will also be tedious to clean up after. You can write if statements, but what if your list is quite big?"
},
{
"code": null,
"e": 1876,
"s": 1835,
"text": "Let’s go through the functions together."
},
{
"code": null,
"e": 1934,
"s": 1876,
"text": "List.ContainsAny — Here is the breakdown of the function."
},
{
"code": null,
"e": 1988,
"s": 1934,
"text": "Find out if the list {1, 2, 3, 4, 5} contains 3 or 4."
},
{
"code": null,
"e": 2030,
"s": 1988,
"text": "List.ContainsAny({1, 2, 3, 4, 5}, {3, 4})"
},
{
"code": null,
"e": 2095,
"s": 2030,
"text": "Returns TRUE — since any 3 or 4 are in the list from {1,2,3,4,5}"
},
{
"code": null,
"e": 2151,
"s": 2095,
"text": "List.ContainsAny({\"A\", \"B\", \"C\", \"D\", \"E\"}, {\"F\", \"G\"})"
},
{
"code": null,
"e": 2227,
"s": 2151,
"text": "Returns FALSE — “F” or “G” are not in the list of {“A”, “B”, “C”, “D”, “E”}"
},
{
"code": null,
"e": 2282,
"s": 2227,
"text": "List.Contains — here is the breakdown of the function."
},
{
"code": null,
"e": 2353,
"s": 2282,
"text": "Find if the list {1, 2, 3, 4, 5} contains 3. Here the function will be"
},
{
"code": null,
"e": 2387,
"s": 2353,
"text": "List.Contains({1, 2, 3, 4, 5}, 3)"
},
{
"code": null,
"e": 2400,
"s": 2387,
"text": "Returns TRUE"
},
{
"code": null,
"e": 2628,
"s": 2400,
"text": "However, you may need to be careful about the item you watch to check against. There isn’t a {} for the item you want to check. The last value being compared against is expects a value and not a list so the below returns false."
},
{
"code": null,
"e": 2664,
"s": 2628,
"text": "List.Contains({1, 2, 3, 4, 5}, {3})"
},
{
"code": null,
"e": 2679,
"s": 2664,
"text": "Returns FALSE."
},
{
"code": null,
"e": 2840,
"s": 2679,
"text": "Now instead of a single value — List.ContainsAll will return True if it is able to match ALL the items on the list against the list you want to compare against."
},
{
"code": null,
"e": 2882,
"s": 2840,
"text": "List.ContainsAll({1, 2, 3, 4, 5}, {4, 5})"
},
{
"code": null,
"e": 2926,
"s": 2882,
"text": "Returns TRUE— both 4 and 5 are on the list."
},
{
"code": null,
"e": 3102,
"s": 2926,
"text": "Since this function requires a list to match and because of the row by row lay out in Power Query, you will need to nest this list first for this to work. (More on this below)"
},
{
"code": null,
"e": 3133,
"s": 3102,
"text": "Let’s walk through an example."
},
{
"code": null,
"e": 3266,
"s": 3133,
"text": "I have a table here in power query and I will use the add columns feature to add in additional columns to use our contain functions."
},
{
"code": null,
"e": 3344,
"s": 3266,
"text": "Let’s add the first column to use List.Contains using the add columns button."
},
{
"code": null,
"e": 3381,
"s": 3344,
"text": "The result will be this column here."
},
{
"code": null,
"e": 3477,
"s": 3381,
"text": "Let’s create our first column. I want to check if the Store_Number 1 is anywhere in the column."
},
{
"code": null,
"e": 3566,
"s": 3477,
"text": "Here the column indicates that there is a store number 1 in that column of store number."
},
{
"code": null,
"e": 3669,
"s": 3566,
"text": "I also want to check for if there is a store number 1 and also, any reviews contains the word “Great”."
},
{
"code": null,
"e": 3791,
"s": 3669,
"text": "Final column, I want to check if all the Review criteria I have — {“Great”,”Good”,”Meh”} — are represented in the column."
},
{
"code": null,
"e": 3873,
"s": 3791,
"text": "This particular one — List.ContainsAll is a little bit different than the others."
},
{
"code": null,
"e": 3988,
"s": 3873,
"text": "If you are doing a custom column just like the others, it wouldn’t work because of the row context in Power Query."
},
{
"code": null,
"e": 4021,
"s": 3988,
"text": "Intuitively if you tried doing —"
},
{
"code": null,
"e": 4074,
"s": 4021,
"text": "List.ContainsAll({[Reviews]},{“Great”,”Good”,”Meh”})"
},
{
"code": null,
"e": 4180,
"s": 4074,
"text": "Will actually return FALSE, even though the items you have listed here are all represented in the column."
},
{
"code": null,
"e": 4447,
"s": 4180,
"text": "The issue here is the row — if you just refer to the column, Power Query takes the “cell” of the column and checks it against the list of {“Great”,”Good”,”Meh”} and returns FALSE. That particular “cell” does not contain all the items of that list so it return FALSE."
},
{
"code": null,
"e": 4716,
"s": 4447,
"text": "When we had used List.ContainsAny, List.Contains, they returned the right value because even if it is doing a check by each value it will still get us what we want. The difference here is we want the entire column to be nested in a “cell” before comparing to the list."
},
{
"code": null,
"e": 4746,
"s": 4716,
"text": "This is why we need to write."
},
{
"code": null,
"e": 4814,
"s": 4746,
"text": "List.ContainsAll( #PreviousStep[Reviews],{“Great”, ”Good”, “Meh”} )"
},
{
"code": null,
"e": 4896,
"s": 4814,
"text": "Here it is referring the entire column as a list — to check against another list."
},
{
"code": null,
"e": 4924,
"s": 4896,
"text": "The result will return TRUE"
},
{
"code": null,
"e": 5014,
"s": 4924,
"text": "As a bonus, these two functions are very helpful as well — List.AnyTrue and List.AllTrue."
},
{
"code": null,
"e": 5134,
"s": 5014,
"text": "They are very much like the others as well and you can add in other conditions instead of just checking for membership."
},
{
"code": null,
"e": 5326,
"s": 5134,
"text": "The great part about these functions — you can string them together with the and, or operators and create checks on your data without having to revert to joins and multiple nested statements."
},
{
"code": null,
"e": 5369,
"s": 5326,
"text": "TL:DR? Here is a summary for all of them —"
},
{
"code": null,
"e": 5433,
"s": 5369,
"text": "List.Contains — Remember to exclude the {} for the search item."
},
{
"code": null,
"e": 5522,
"s": 5433,
"text": "List.ContainsAll — Remember to use the previous step [ column name] for the search list."
},
{
"code": null,
"e": 5601,
"s": 5522,
"text": "List.ContainsAny — Easiest to use. I’ve always had to use this particular one."
},
{
"code": null,
"e": 5717,
"s": 5601,
"text": "List.AnyTrue, List.AllTrue — You can add in conditions to them. Whole condition statement needs to be wrapped in {}"
}
] |
Java BeanUtils - Basic Property Access | You can access the basic properties by using the following ways:
Simple Property
Simple Property
Indexed Property
Indexed Property
Mapped Property
Mapped Property
You can get and set the simple property values by using the below API signatures:
PropertyUtils.getSimpleProperty(Object, String)
PropertyUtils.getSimpleProperty(Object, String)
PropertyUtils.SetSimpleProperty(Object, String, Object)
PropertyUtils.SetSimpleProperty(Object, String, Object)
Parameters:
Object: It is a bean object that specifies the bean property to be extracted.
Object: It is a bean object that specifies the bean property to be extracted.
String: It is a string name that specifies the name of the property to be extracted.
String: It is a string name that specifies the name of the property to be extracted.
You can use two options for creating indexed properties; first option is building the subscript into property name and second option is defining the subscript in a separate argument to call the method.
The indexed properties can be get and set by using the below methods:
PropertyUtils.getIndexedProperty(Object, String)
PropertyUtils.getIndexedProperty(Object, String)
PropertyUtils.getIndexedProperty(Object, String, int)
PropertyUtils.getIndexedProperty(Object, String, int)
PropertyUtils.setIndexedProperty(Object, String, Object)
PropertyUtils.setIndexedProperty(Object, String, Object)
PropertyUtils.setIndexedProperty(Object, String, int, Object)
PropertyUtils.setIndexedProperty(Object, String, int, Object)
Parameters:
Object: It is a bean object that specifies the bean property to be extracted.
Object: It is a bean object that specifies the bean property to be extracted.
String: It is a string name that specifies the name of the property to be extracted.
String: It is a string name that specifies the name of the property to be extracted.
int: It sets an index of the property value.
int: It sets an index of the property value.
Object: It specifies the value for an indexed property element.
Object: It specifies the value for an indexed property element.
You can get and set the mapped property values by using the below API signatures. If you have any extra argument, then it can be written within parentheses as ("(" and ")") instead of using square brackets.
PropertyUtils.getMappedProperty(Object, String)
PropertyUtils.getMappedProperty(Object, String)
PropertyUtils.getMappedProperty(Object, String, String)
PropertyUtils.getMappedProperty(Object, String, String)
PropertyUtils.setMappedProperty(Object, String, Object)
PropertyUtils.setMappedProperty(Object, String, Object)
PropertyUtils.setMappedProperty(Object, String, String, Object)
PropertyUtils.setMappedProperty(Object, String, String, Object)
Parameters:
Object: It is a bean object that specifies the bean property to be extracted.
Object: It is a bean object that specifies the bean property to be extracted.
String: It is a name of the property value that should be set for Mapped property.
String: It is a name of the property value that should be set for Mapped property.
String: It defines the key of the property value to be set.
String: It defines the key of the property value to be set.
Object: It specifies the value of property to be set.
Object: It specifies the value of property to be set.
The below example demonstrates use of above properties in the beanUtils:
import org.apache.commons.beanutils.PropertyUtils;
import java.util.ArrayList;
import java.util.List;
public class BeanUtilsPropertyDemo{
public static void main(String args[]){
try{
// Creating the bean and allows to access getter and setter properties
MyBean myBean = new MyBean();
// Setting the properties on the myBean
PropertyUtils.setSimpleProperty(myBean, "stringProp", "Hello!This is a string");
PropertyUtils.setSimpleProperty(myBean, "floatProp", new Float(25.20));
// Getting the simple properties
System.out.println("String Property: " + PropertyUtils.getSimpleProperty(myBean, "stringProp"));
System.out.println("Float Property: " + PropertyUtils.getSimpleProperty(myBean, "floatProp"));
// Here we will create a list for the indexed property
List list = new ArrayList();
list.add("String value 0");
list.add("String value 1");
myBean.setListProp(list);
// get and set this indexed property
PropertyUtils.setIndexedProperty(myBean, "listProp[1]", "This is new string value 1");
System.out.println("List Property[1]: " + PropertyUtils.getIndexedProperty(myBean, "listProp[1]"));
}catch(Exception e){
System.out.println(e);
}
}
}
Now we will create one more class called MyBean.java for the bean class:
import java.util.ArrayList;
import java.util.List;
public class MyBean {
private String stringProp;
private float floatProp;
//indexed property
@SuppressWarnings("rawtypes")
private List listProp = new ArrayList();
public void setStringProp(String stringProp) { this.stringProp = stringProp; }
public String getStringProp() { return this.stringProp; }
public void setFloatProp(float floatProp) { this.floatProp = floatProp; }
public float getFloatProp() { return this.floatProp; }
public void setListProp(List<?> listProp) { this.listProp = listProp; }
public List<?> getListProp() { return this.listProp; }
}
Let's carry out the following steps to see how above code works:
Save the above first code as BeanUtilsPropertyDemo.java.
Save the above first code as BeanUtilsPropertyDemo.java.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.
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": 2221,
"s": 2156,
"text": "You can access the basic properties by using the following ways:"
},
{
"code": null,
"e": 2237,
"s": 2221,
"text": "Simple Property"
},
{
"code": null,
"e": 2253,
"s": 2237,
"text": "Simple Property"
},
{
"code": null,
"e": 2270,
"s": 2253,
"text": "Indexed Property"
},
{
"code": null,
"e": 2287,
"s": 2270,
"text": "Indexed Property"
},
{
"code": null,
"e": 2303,
"s": 2287,
"text": "Mapped Property"
},
{
"code": null,
"e": 2319,
"s": 2303,
"text": "Mapped Property"
},
{
"code": null,
"e": 2401,
"s": 2319,
"text": "You can get and set the simple property values by using the below API signatures:"
},
{
"code": null,
"e": 2449,
"s": 2401,
"text": "PropertyUtils.getSimpleProperty(Object, String)"
},
{
"code": null,
"e": 2497,
"s": 2449,
"text": "PropertyUtils.getSimpleProperty(Object, String)"
},
{
"code": null,
"e": 2553,
"s": 2497,
"text": "PropertyUtils.SetSimpleProperty(Object, String, Object)"
},
{
"code": null,
"e": 2609,
"s": 2553,
"text": "PropertyUtils.SetSimpleProperty(Object, String, Object)"
},
{
"code": null,
"e": 2621,
"s": 2609,
"text": "Parameters:"
},
{
"code": null,
"e": 2699,
"s": 2621,
"text": "Object: It is a bean object that specifies the bean property to be extracted."
},
{
"code": null,
"e": 2777,
"s": 2699,
"text": "Object: It is a bean object that specifies the bean property to be extracted."
},
{
"code": null,
"e": 2862,
"s": 2777,
"text": "String: It is a string name that specifies the name of the property to be extracted."
},
{
"code": null,
"e": 2947,
"s": 2862,
"text": "String: It is a string name that specifies the name of the property to be extracted."
},
{
"code": null,
"e": 3149,
"s": 2947,
"text": "You can use two options for creating indexed properties; first option is building the subscript into property name and second option is defining the subscript in a separate argument to call the method."
},
{
"code": null,
"e": 3219,
"s": 3149,
"text": "The indexed properties can be get and set by using the below methods:"
},
{
"code": null,
"e": 3268,
"s": 3219,
"text": "PropertyUtils.getIndexedProperty(Object, String)"
},
{
"code": null,
"e": 3317,
"s": 3268,
"text": "PropertyUtils.getIndexedProperty(Object, String)"
},
{
"code": null,
"e": 3371,
"s": 3317,
"text": "PropertyUtils.getIndexedProperty(Object, String, int)"
},
{
"code": null,
"e": 3425,
"s": 3371,
"text": "PropertyUtils.getIndexedProperty(Object, String, int)"
},
{
"code": null,
"e": 3482,
"s": 3425,
"text": "PropertyUtils.setIndexedProperty(Object, String, Object)"
},
{
"code": null,
"e": 3539,
"s": 3482,
"text": "PropertyUtils.setIndexedProperty(Object, String, Object)"
},
{
"code": null,
"e": 3601,
"s": 3539,
"text": "PropertyUtils.setIndexedProperty(Object, String, int, Object)"
},
{
"code": null,
"e": 3663,
"s": 3601,
"text": "PropertyUtils.setIndexedProperty(Object, String, int, Object)"
},
{
"code": null,
"e": 3675,
"s": 3663,
"text": "Parameters:"
},
{
"code": null,
"e": 3753,
"s": 3675,
"text": "Object: It is a bean object that specifies the bean property to be extracted."
},
{
"code": null,
"e": 3831,
"s": 3753,
"text": "Object: It is a bean object that specifies the bean property to be extracted."
},
{
"code": null,
"e": 3916,
"s": 3831,
"text": "String: It is a string name that specifies the name of the property to be extracted."
},
{
"code": null,
"e": 4001,
"s": 3916,
"text": "String: It is a string name that specifies the name of the property to be extracted."
},
{
"code": null,
"e": 4046,
"s": 4001,
"text": "int: It sets an index of the property value."
},
{
"code": null,
"e": 4091,
"s": 4046,
"text": "int: It sets an index of the property value."
},
{
"code": null,
"e": 4155,
"s": 4091,
"text": "Object: It specifies the value for an indexed property element."
},
{
"code": null,
"e": 4219,
"s": 4155,
"text": "Object: It specifies the value for an indexed property element."
},
{
"code": null,
"e": 4426,
"s": 4219,
"text": "You can get and set the mapped property values by using the below API signatures. If you have any extra argument, then it can be written within parentheses as (\"(\" and \")\") instead of using square brackets."
},
{
"code": null,
"e": 4474,
"s": 4426,
"text": "PropertyUtils.getMappedProperty(Object, String)"
},
{
"code": null,
"e": 4522,
"s": 4474,
"text": "PropertyUtils.getMappedProperty(Object, String)"
},
{
"code": null,
"e": 4578,
"s": 4522,
"text": "PropertyUtils.getMappedProperty(Object, String, String)"
},
{
"code": null,
"e": 4634,
"s": 4578,
"text": "PropertyUtils.getMappedProperty(Object, String, String)"
},
{
"code": null,
"e": 4690,
"s": 4634,
"text": "PropertyUtils.setMappedProperty(Object, String, Object)"
},
{
"code": null,
"e": 4746,
"s": 4690,
"text": "PropertyUtils.setMappedProperty(Object, String, Object)"
},
{
"code": null,
"e": 4810,
"s": 4746,
"text": "PropertyUtils.setMappedProperty(Object, String, String, Object)"
},
{
"code": null,
"e": 4874,
"s": 4810,
"text": "PropertyUtils.setMappedProperty(Object, String, String, Object)"
},
{
"code": null,
"e": 4886,
"s": 4874,
"text": "Parameters:"
},
{
"code": null,
"e": 4964,
"s": 4886,
"text": "Object: It is a bean object that specifies the bean property to be extracted."
},
{
"code": null,
"e": 5042,
"s": 4964,
"text": "Object: It is a bean object that specifies the bean property to be extracted."
},
{
"code": null,
"e": 5125,
"s": 5042,
"text": "String: It is a name of the property value that should be set for Mapped property."
},
{
"code": null,
"e": 5208,
"s": 5125,
"text": "String: It is a name of the property value that should be set for Mapped property."
},
{
"code": null,
"e": 5268,
"s": 5208,
"text": "String: It defines the key of the property value to be set."
},
{
"code": null,
"e": 5328,
"s": 5268,
"text": "String: It defines the key of the property value to be set."
},
{
"code": null,
"e": 5382,
"s": 5328,
"text": "Object: It specifies the value of property to be set."
},
{
"code": null,
"e": 5436,
"s": 5382,
"text": "Object: It specifies the value of property to be set."
},
{
"code": null,
"e": 5509,
"s": 5436,
"text": "The below example demonstrates use of above properties in the beanUtils:"
},
{
"code": null,
"e": 6778,
"s": 5509,
"text": "import org.apache.commons.beanutils.PropertyUtils;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class BeanUtilsPropertyDemo{\n public static void main(String args[]){\n\n try{\n // Creating the bean and allows to access getter and setter properties\n MyBean myBean = new MyBean();\n\n // Setting the properties on the myBean\n PropertyUtils.setSimpleProperty(myBean, \"stringProp\", \"Hello!This is a string\");\n PropertyUtils.setSimpleProperty(myBean, \"floatProp\", new Float(25.20));\n\n // Getting the simple properties\n System.out.println(\"String Property: \" + PropertyUtils.getSimpleProperty(myBean, \"stringProp\"));\n\n System.out.println(\"Float Property: \" + PropertyUtils.getSimpleProperty(myBean, \"floatProp\"));\n\n // Here we will create a list for the indexed property\n List list = new ArrayList();\n list.add(\"String value 0\");\n list.add(\"String value 1\");\n\n myBean.setListProp(list);\n\n // get and set this indexed property\n PropertyUtils.setIndexedProperty(myBean, \"listProp[1]\", \"This is new string value 1\");\n\n System.out.println(\"List Property[1]: \" + PropertyUtils.getIndexedProperty(myBean, \"listProp[1]\"));\n\n }catch(Exception e){\n System.out.println(e);\n }\n }\n}"
},
{
"code": null,
"e": 6851,
"s": 6778,
"text": "Now we will create one more class called MyBean.java for the bean class:"
},
{
"code": null,
"e": 7500,
"s": 6851,
"text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class MyBean {\n private String stringProp;\n private float floatProp;\n\n //indexed property\n @SuppressWarnings(\"rawtypes\")\n private List listProp = new ArrayList();\n\n public void setStringProp(String stringProp) { this.stringProp = stringProp; }\n public String getStringProp() { return this.stringProp; }\n\n public void setFloatProp(float floatProp) { this.floatProp = floatProp; }\n public float getFloatProp() { return this.floatProp; }\n\n public void setListProp(List<?> listProp) { this.listProp = listProp; }\n public List<?> getListProp() { return this.listProp; }\n\t}"
},
{
"code": null,
"e": 7565,
"s": 7500,
"text": "Let's carry out the following steps to see how above code works:"
},
{
"code": null,
"e": 7622,
"s": 7565,
"text": "Save the above first code as BeanUtilsPropertyDemo.java."
},
{
"code": null,
"e": 7679,
"s": 7622,
"text": "Save the above first code as BeanUtilsPropertyDemo.java."
},
{
"code": null,
"e": 7765,
"s": 7679,
"text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed."
},
{
"code": null,
"e": 7851,
"s": 7765,
"text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed."
},
{
"code": null,
"e": 7884,
"s": 7851,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7900,
"s": 7884,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7933,
"s": 7900,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7949,
"s": 7933,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7984,
"s": 7949,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7998,
"s": 7984,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8032,
"s": 7998,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8046,
"s": 8032,
"text": " Tushar Kale"
},
{
"code": null,
"e": 8083,
"s": 8046,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8098,
"s": 8083,
"text": " Monica Mittal"
},
{
"code": null,
"e": 8131,
"s": 8098,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8150,
"s": 8131,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8157,
"s": 8150,
"text": " Print"
},
{
"code": null,
"e": 8168,
"s": 8157,
"text": " Add Notes"
}
] |
One Potential Cause of Overfitting That I Never Noticed Before | by Yufeng | Towards Data Science | “Why is my tuned model still overfitting?”
“Did you use cross-validation?”
“Of course yes.”
“What model did you use and what are the hyperparameters you tuned?”
“Random Forest regressor and I tuned tree number and maximum feature numbers per tree.”
“I need to check your code.”
This was the dialogue between my wife and me when she was doing a mini-project.
Honestly, based on her description, I couldn’t think of anywhere wrong in the procedure. However, after my checking her code line by line, I found the issue that caused the overfitting problem and I have never thought of before.
Let’s dissect her code together.
This is the block of code that tuned the model in the training dataset and it is also where the problem happened.
def train_pipeline_rf(X,y): # X are factors # y is output # impute missing X by median X_prepared = pre_pipeline.fit_transform(X) # set cross-validation tscv = TimeSeriesSplit(n_splits=10) data_split = tscv.split(X_prepared) # hyper-parameter space param_grid_RF = { 'n_estimators' : [10,20,50,100,200,500,1000], 'max_features' : [0.6,0.8,"auto","sqrt"] } # build random forest model rf_model = RandomForestRegressor(random_state=42,n_jobs=-1) # gridsearch for the best hyper-parameter gs_rf = GridSearchCV(rf_model, param_grid=param_grid_RF, cv=data_split, scoring='neg_mean_squared_error', n_jobs=-1) # fit dataset gs_rf.fit(X_prepared, y) return gs_rf
The pre_pipeline in the code is a pipeline for missing value imputation and feature scaling, both of which are essential steps in data pre-processing. Here is what it looks like:
pre_pipeline = Pipeline([ ('imputer', SimpleImputer(strategy="median")), ('std_scaler', StandardScaler()), ])
The imputer she used here is to replace the NA values by the column median, and the scaler is the standard scaler which normalizes the columns as:
z = (x — u) / s
where u is the mean and s is the standard deviation of the column [1]. Some other imputers and scalers in the sklearn package can also be used. But this part is not related to the overfitting problem.
# set cross-validation tscv = TimeSeriesSplit(n_splits=10) data_split = tscv.split(X_prepared)
Here she used a method specifically designed for time-series data, TimeSeriesSplit.
Usually, people use k-fold cross-validation to randomly split the training data or stratified k-fold cross-validation to preserve the percentage of samples for each class [2]. But these two methods are not suitable for time-series data because they don’t keep the raw order of the data points.
This step is pretty standard and cannot be related to the overfitting problem.
# hyper-parameter space param_grid_RF = { 'n_estimators' : [10,20,50,100,200,500,1000], 'max_features' : [0.6,0.8,"auto","sqrt"] } # build random forest model rf_model = RandomForestRegressor(random_state=42,n_jobs=-1)
As for hyperparameter tuning, a set of candidates should be given, which are usually defined as a dictionary format in sklearn package. The names of the hyperparameters are from the model to build, for example, RandomForestRegressor in my wife’s code.
The so-called “tuning-hyperparameter” step is to select the best hyperparameter combination from your given candidates that outperforms other combinations of hyperparameters in the cross-validation procedure.
It is the part that resulted in the overfitting problem.
If we refer to the manual page of Random Forest Regressor in sklearn, we can see a long list of parameters in the function RandomForestRegressor (not listed here, please refer to the webpage if interested).
However, in the code above, only n_estimators and max_features were passed to the function during the tuning process, which resulted in that all the other parameters took the default values.
One of the parameters in the function is called max_depth, which is the maximum depth of the tree in your random forest model. The default value of it is “None”, which means that the decision tree will go as deep as that each leave is pure or all leaves have at most m samples, where m is defined by min_samples_split (default = 2).
This setting significantly increased the complexity of the trained model. And based on the tradeoff between bias and variance, the model trained in the code above had low bias and high variance. Of course, it finally led to the overfitting problem.
I solved the problem by adding max_depth to the hyperparameter space.
# hyper-parameter space param_grid_RF = { 'n_estimators' : [10,20,50,100,200,500,1000], 'max_features' : [0.6,0.8,"auto","sqrt"], 'max_depth' : [4,5,6] }
Actually, there are some other parameters that can affect the complexity of the model in RandomForestRegressor, but it is not recommended to put all of them into the hyperparameter space.
The extra hyperparameter in the code above already increased the computation cost by three folds. So, it’s not worth increasing the running time exponentially to just tune more parameters.
Instead, you can set some of them in the model initiation like this.
# hyper-parameter space param_grid_RF = { 'n_estimators' : [10,20,50,100,200,500,1000] }# build random forest model rf_model = RandomForestRegressor(random_state=42,n_jobs=-1,max_features=0.6,max_depth=5)
In the code above, the only tuned hyperparameter is n_estimators, and max_features, as well as max_depth, are fixed during the training process. The tuned or fixed parameters do not have to be like that.
The rationale of the setting is to reduce the computational cost when you already have some idea on the selection of some hyperparameters.
Yes, my wife’s problem has been solved. To be honest, however, I could not have found it until I went over all the default parameters in the package. That’s why I want to share this experience with you so that you can be more careful about the default parameters in your machine learning model training processes.
Overfitting is one of the most common problems in data science, which mostly comes from the high complexity of the model and the lack of data points.
To avoid it, it’s better to take full control of the packages you use.
Hope this piece of advice can help you.
https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScalerhttps://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.htmlhttps://en.wikipedia.org/wiki/Random_forest
https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler
https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html
https://en.wikipedia.org/wiki/Random_forest
I would like to thank Antonio Carlos for pointing out this issue in my original post. He also suggested a nice post “Pre-Process Data with Pipeline to Prevent Data Leakage during Cross-Validation.” to the topic. I really appreciate that.
It is related to the pre-processing part of the pipeline. It shouldn’t have been done on the entire training dataset, but on each iteration of the Cross-Validation step because the overall normalization of the training data will cause leakage between the train and validation dataset in the CV step.
So, I put the corrected code with a corresponding revision as below:
def train_pipeline_rf(X,y): # X are factors # y is output # set cross-validation tscv = TimeSeriesSplit(n_splits=10) data_split = tscv.split(X) # build a pipeline of pre-processing and random forest model my_pipe = Pipeline([ ('imputer', SimpleImputer(strategy="median")), ('std_scaler', StandardScaler()), ('rf_model', RandomForestRegressor(random_state=42,n_jobs=-1)) ]) # hyper-parameter space param_grid_RF = { 'rf_model__n_estimators' : [10,20,50,100,200,500,1000], 'rf_model__max_features' : [0.6,0.8,"auto","sqrt"], 'rf_model__max_depth' : [4,5,6] } # gridsearch for the best hyper-parameter within the pipeline. gs_rf = GridSearchCV(my_pipe, param_grid=param_grid_RF, cv=data_split, scoring='neg_mean_squared_error', n_jobs=-1) # fit dataset gs_rf.fit(X, y) return gs_rf | [
{
"code": null,
"e": 215,
"s": 172,
"text": "“Why is my tuned model still overfitting?”"
},
{
"code": null,
"e": 247,
"s": 215,
"text": "“Did you use cross-validation?”"
},
{
"code": null,
"e": 264,
"s": 247,
"text": "“Of course yes.”"
},
{
"code": null,
"e": 333,
"s": 264,
"text": "“What model did you use and what are the hyperparameters you tuned?”"
},
{
"code": null,
"e": 421,
"s": 333,
"text": "“Random Forest regressor and I tuned tree number and maximum feature numbers per tree.”"
},
{
"code": null,
"e": 450,
"s": 421,
"text": "“I need to check your code.”"
},
{
"code": null,
"e": 530,
"s": 450,
"text": "This was the dialogue between my wife and me when she was doing a mini-project."
},
{
"code": null,
"e": 759,
"s": 530,
"text": "Honestly, based on her description, I couldn’t think of anywhere wrong in the procedure. However, after my checking her code line by line, I found the issue that caused the overfitting problem and I have never thought of before."
},
{
"code": null,
"e": 792,
"s": 759,
"text": "Let’s dissect her code together."
},
{
"code": null,
"e": 906,
"s": 792,
"text": "This is the block of code that tuned the model in the training dataset and it is also where the problem happened."
},
{
"code": null,
"e": 1626,
"s": 906,
"text": "def train_pipeline_rf(X,y): # X are factors # y is output # impute missing X by median X_prepared = pre_pipeline.fit_transform(X) # set cross-validation tscv = TimeSeriesSplit(n_splits=10) data_split = tscv.split(X_prepared) # hyper-parameter space param_grid_RF = { 'n_estimators' : [10,20,50,100,200,500,1000], 'max_features' : [0.6,0.8,\"auto\",\"sqrt\"] } # build random forest model rf_model = RandomForestRegressor(random_state=42,n_jobs=-1) # gridsearch for the best hyper-parameter gs_rf = GridSearchCV(rf_model, param_grid=param_grid_RF, cv=data_split, scoring='neg_mean_squared_error', n_jobs=-1) # fit dataset gs_rf.fit(X_prepared, y) return gs_rf"
},
{
"code": null,
"e": 1805,
"s": 1626,
"text": "The pre_pipeline in the code is a pipeline for missing value imputation and feature scaling, both of which are essential steps in data pre-processing. Here is what it looks like:"
},
{
"code": null,
"e": 1932,
"s": 1805,
"text": "pre_pipeline = Pipeline([ ('imputer', SimpleImputer(strategy=\"median\")), ('std_scaler', StandardScaler()), ])"
},
{
"code": null,
"e": 2079,
"s": 1932,
"text": "The imputer she used here is to replace the NA values by the column median, and the scaler is the standard scaler which normalizes the columns as:"
},
{
"code": null,
"e": 2095,
"s": 2079,
"text": "z = (x — u) / s"
},
{
"code": null,
"e": 2296,
"s": 2095,
"text": "where u is the mean and s is the standard deviation of the column [1]. Some other imputers and scalers in the sklearn package can also be used. But this part is not related to the overfitting problem."
},
{
"code": null,
"e": 2401,
"s": 2296,
"text": " # set cross-validation tscv = TimeSeriesSplit(n_splits=10) data_split = tscv.split(X_prepared)"
},
{
"code": null,
"e": 2485,
"s": 2401,
"text": "Here she used a method specifically designed for time-series data, TimeSeriesSplit."
},
{
"code": null,
"e": 2779,
"s": 2485,
"text": "Usually, people use k-fold cross-validation to randomly split the training data or stratified k-fold cross-validation to preserve the percentage of samples for each class [2]. But these two methods are not suitable for time-series data because they don’t keep the raw order of the data points."
},
{
"code": null,
"e": 2858,
"s": 2779,
"text": "This step is pretty standard and cannot be related to the overfitting problem."
},
{
"code": null,
"e": 3107,
"s": 2858,
"text": " # hyper-parameter space param_grid_RF = { 'n_estimators' : [10,20,50,100,200,500,1000], 'max_features' : [0.6,0.8,\"auto\",\"sqrt\"] } # build random forest model rf_model = RandomForestRegressor(random_state=42,n_jobs=-1)"
},
{
"code": null,
"e": 3359,
"s": 3107,
"text": "As for hyperparameter tuning, a set of candidates should be given, which are usually defined as a dictionary format in sklearn package. The names of the hyperparameters are from the model to build, for example, RandomForestRegressor in my wife’s code."
},
{
"code": null,
"e": 3568,
"s": 3359,
"text": "The so-called “tuning-hyperparameter” step is to select the best hyperparameter combination from your given candidates that outperforms other combinations of hyperparameters in the cross-validation procedure."
},
{
"code": null,
"e": 3625,
"s": 3568,
"text": "It is the part that resulted in the overfitting problem."
},
{
"code": null,
"e": 3832,
"s": 3625,
"text": "If we refer to the manual page of Random Forest Regressor in sklearn, we can see a long list of parameters in the function RandomForestRegressor (not listed here, please refer to the webpage if interested)."
},
{
"code": null,
"e": 4023,
"s": 3832,
"text": "However, in the code above, only n_estimators and max_features were passed to the function during the tuning process, which resulted in that all the other parameters took the default values."
},
{
"code": null,
"e": 4356,
"s": 4023,
"text": "One of the parameters in the function is called max_depth, which is the maximum depth of the tree in your random forest model. The default value of it is “None”, which means that the decision tree will go as deep as that each leave is pure or all leaves have at most m samples, where m is defined by min_samples_split (default = 2)."
},
{
"code": null,
"e": 4605,
"s": 4356,
"text": "This setting significantly increased the complexity of the trained model. And based on the tradeoff between bias and variance, the model trained in the code above had low bias and high variance. Of course, it finally led to the overfitting problem."
},
{
"code": null,
"e": 4675,
"s": 4605,
"text": "I solved the problem by adding max_depth to the hyperparameter space."
},
{
"code": null,
"e": 4860,
"s": 4675,
"text": " # hyper-parameter space param_grid_RF = { 'n_estimators' : [10,20,50,100,200,500,1000], 'max_features' : [0.6,0.8,\"auto\",\"sqrt\"], 'max_depth' : [4,5,6] }"
},
{
"code": null,
"e": 5048,
"s": 4860,
"text": "Actually, there are some other parameters that can affect the complexity of the model in RandomForestRegressor, but it is not recommended to put all of them into the hyperparameter space."
},
{
"code": null,
"e": 5237,
"s": 5048,
"text": "The extra hyperparameter in the code above already increased the computation cost by three folds. So, it’s not worth increasing the running time exponentially to just tune more parameters."
},
{
"code": null,
"e": 5306,
"s": 5237,
"text": "Instead, you can set some of them in the model initiation like this."
},
{
"code": null,
"e": 5527,
"s": 5306,
"text": "# hyper-parameter space param_grid_RF = { 'n_estimators' : [10,20,50,100,200,500,1000] }# build random forest model rf_model = RandomForestRegressor(random_state=42,n_jobs=-1,max_features=0.6,max_depth=5)"
},
{
"code": null,
"e": 5731,
"s": 5527,
"text": "In the code above, the only tuned hyperparameter is n_estimators, and max_features, as well as max_depth, are fixed during the training process. The tuned or fixed parameters do not have to be like that."
},
{
"code": null,
"e": 5870,
"s": 5731,
"text": "The rationale of the setting is to reduce the computational cost when you already have some idea on the selection of some hyperparameters."
},
{
"code": null,
"e": 6184,
"s": 5870,
"text": "Yes, my wife’s problem has been solved. To be honest, however, I could not have found it until I went over all the default parameters in the package. That’s why I want to share this experience with you so that you can be more careful about the default parameters in your machine learning model training processes."
},
{
"code": null,
"e": 6334,
"s": 6184,
"text": "Overfitting is one of the most common problems in data science, which mostly comes from the high complexity of the model and the lack of data points."
},
{
"code": null,
"e": 6405,
"s": 6334,
"text": "To avoid it, it’s better to take full control of the packages you use."
},
{
"code": null,
"e": 6445,
"s": 6405,
"text": "Hope this piece of advice can help you."
},
{
"code": null,
"e": 6711,
"s": 6445,
"text": "https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScalerhttps://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.htmlhttps://en.wikipedia.org/wiki/Random_forest"
},
{
"code": null,
"e": 6840,
"s": 6711,
"text": "https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler"
},
{
"code": null,
"e": 6935,
"s": 6840,
"text": "https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html"
},
{
"code": null,
"e": 6979,
"s": 6935,
"text": "https://en.wikipedia.org/wiki/Random_forest"
},
{
"code": null,
"e": 7217,
"s": 6979,
"text": "I would like to thank Antonio Carlos for pointing out this issue in my original post. He also suggested a nice post “Pre-Process Data with Pipeline to Prevent Data Leakage during Cross-Validation.” to the topic. I really appreciate that."
},
{
"code": null,
"e": 7517,
"s": 7217,
"text": "It is related to the pre-processing part of the pipeline. It shouldn’t have been done on the entire training dataset, but on each iteration of the Cross-Validation step because the overall normalization of the training data will cause leakage between the train and validation dataset in the CV step."
},
{
"code": null,
"e": 7586,
"s": 7517,
"text": "So, I put the corrected code with a corresponding revision as below:"
}
] |
numpy.delete() in Python - GeeksforGeeks | 28 Mar, 2022
The numpy.delete() function returns a new array with the deletion of sub-arrays along with the mentioned axis.
Syntax:
numpy.delete(array, object, axis = None)
Parameters :
array : [array_like]Input array.
object : [int, array of ints]Sub-array to delete
axis : Axis along which we want to delete sub-arrays. By default, it object is applied to
flattened array
Return :
An array with sub-array being deleted as per the mentioned object along a given axis.
Code 1 : Deletion from 1D array
Python
# Python Program illustrating# numpy.delete() import numpy as geek #Working on 1Darr = geek.arange(5)print("arr : \n", arr)print("Shape : ", arr.shape) # deletion from 1D array object = 2a = geek.delete(arr, object)print("\ndeleteing {} from array : \n {}".format(object,a))print("Shape : ", a.shape) object = [1, 2]b = geek.delete(arr, object)print("\ndeleteing {} from array : \n {}".format(object,a))print("Shape : ", a.shape)
Output :
arr :
[0 1 2 3 4]
Shape : (5,)
deleteing arr 2 times :
[0 1 3 4]
Shape : (4,)
deleteing arr 3 times :
[0 3 4]
Shape : (4,)
Code 2 :
Python
# Python Program illustrating# numpy.delete() import numpy as geek #Working on 1Darr = geek.arange(12).reshape(3, 4)print("arr : \n", arr)print("Shape : ", arr.shape) # deletion from 2D arraya = geek.delete(arr, 1, 0)''' [[ 0 1 2 3] [ 4 5 6 7] -> deleted [ 8 9 10 11]]'''print("\ndeleteing arr 2 times : \n", a)print("Shape : ", a.shape) # deletion from 2D arraya = geek.delete(arr, 1, 1)''' [[ 0 1* 2 3] [ 4 5* 6 7] [ 8 9* 10 11]] ^ Deletion'''print("\ndeleteing arr 2 times : \n", a)print("Shape : ", a.shape)
Output :
arr :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Shape : (3, 4)
deleteing arr 2 times :
[[ 0 1 2 3]
[ 8 9 10 11]]
Shape : (2, 4)
deleteing arr 2 times :
[[ 0 2 3]
[ 4 6 7]
[ 8 10 11]]
Shape : (3, 3)
deleteing arr 3 times :
[ 0 3 4 5 6 7 8 9 10 11]
Shape : (3, 3)
Code 3: Deletion performed using Boolean Mask
Python
# Python Program illustrating# numpy.delete() import numpy as geek arr = geek.arange(5)print("Original array : ", arr)mask = geek.ones(len(arr), dtype=bool) # Equivalent to np.delete(arr, [0,2,4], axis=0)mask[[0,2]] = Falseprint("\nMask set as : ", mask)result = arr[mask,...]print("\nDeletion Using a Boolean Mask : ", result)
Output :
Original array : [0 1 2 3 4]
Mask set as : [False True False True True]
Deletion Using a Boolean Mask : [1 3 4]
References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.htmlNote : These codes won’t run on online IDE’s. Please run them on your systems to explore the working . This article is contributed by Mohit Gupta_OMG . 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.
aryen1713045
kothavvsaakash
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 24266,
"s": 24238,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 24379,
"s": 24266,
"text": "The numpy.delete() function returns a new array with the deletion of sub-arrays along with the mentioned axis. "
},
{
"code": null,
"e": 24387,
"s": 24379,
"text": "Syntax:"
},
{
"code": null,
"e": 24428,
"s": 24387,
"text": "numpy.delete(array, object, axis = None)"
},
{
"code": null,
"e": 24442,
"s": 24428,
"text": "Parameters : "
},
{
"code": null,
"e": 24655,
"s": 24442,
"text": "array : [array_like]Input array. \nobject : [int, array of ints]Sub-array to delete\naxis : Axis along which we want to delete sub-arrays. By default, it object is applied to \n flattened array"
},
{
"code": null,
"e": 24665,
"s": 24655,
"text": "Return : "
},
{
"code": null,
"e": 24752,
"s": 24665,
"text": "An array with sub-array being deleted as per the mentioned object along a given axis. "
},
{
"code": null,
"e": 24786,
"s": 24752,
"text": "Code 1 : Deletion from 1D array "
},
{
"code": null,
"e": 24793,
"s": 24786,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.delete() import numpy as geek #Working on 1Darr = geek.arange(5)print(\"arr : \\n\", arr)print(\"Shape : \", arr.shape) # deletion from 1D array object = 2a = geek.delete(arr, object)print(\"\\ndeleteing {} from array : \\n {}\".format(object,a))print(\"Shape : \", a.shape) object = [1, 2]b = geek.delete(arr, object)print(\"\\ndeleteing {} from array : \\n {}\".format(object,a))print(\"Shape : \", a.shape)",
"e": 25223,
"s": 24793,
"text": null
},
{
"code": null,
"e": 25234,
"s": 25223,
"text": "Output : "
},
{
"code": null,
"e": 25368,
"s": 25234,
"text": "arr : \n [0 1 2 3 4]\nShape : (5,)\n\ndeleteing arr 2 times : \n [0 1 3 4]\nShape : (4,)\n\ndeleteing arr 3 times : \n [0 3 4]\nShape : (4,)"
},
{
"code": null,
"e": 25379,
"s": 25368,
"text": "Code 2 : "
},
{
"code": null,
"e": 25386,
"s": 25379,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.delete() import numpy as geek #Working on 1Darr = geek.arange(12).reshape(3, 4)print(\"arr : \\n\", arr)print(\"Shape : \", arr.shape) # deletion from 2D arraya = geek.delete(arr, 1, 0)''' [[ 0 1 2 3] [ 4 5 6 7] -> deleted [ 8 9 10 11]]'''print(\"\\ndeleteing arr 2 times : \\n\", a)print(\"Shape : \", a.shape) # deletion from 2D arraya = geek.delete(arr, 1, 1)''' [[ 0 1* 2 3] [ 4 5* 6 7] [ 8 9* 10 11]] ^ Deletion'''print(\"\\ndeleteing arr 2 times : \\n\", a)print(\"Shape : \", a.shape)",
"e": 25984,
"s": 25386,
"text": null
},
{
"code": null,
"e": 25995,
"s": 25984,
"text": "Output : "
},
{
"code": null,
"e": 26294,
"s": 25995,
"text": "arr : \n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\nShape : (3, 4)\n\ndeleteing arr 2 times : \n [[ 0 1 2 3]\n [ 8 9 10 11]]\nShape : (2, 4)\n\ndeleteing arr 2 times : \n [[ 0 2 3]\n [ 4 6 7]\n [ 8 10 11]]\nShape : (3, 3)\n\ndeleteing arr 3 times : \n [ 0 3 4 5 6 7 8 9 10 11]\nShape : (3, 3)"
},
{
"code": null,
"e": 26342,
"s": 26294,
"text": "Code 3: Deletion performed using Boolean Mask "
},
{
"code": null,
"e": 26349,
"s": 26342,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.delete() import numpy as geek arr = geek.arange(5)print(\"Original array : \", arr)mask = geek.ones(len(arr), dtype=bool) # Equivalent to np.delete(arr, [0,2,4], axis=0)mask[[0,2]] = Falseprint(\"\\nMask set as : \", mask)result = arr[mask,...]print(\"\\nDeletion Using a Boolean Mask : \", result)",
"e": 26677,
"s": 26349,
"text": null
},
{
"code": null,
"e": 26688,
"s": 26677,
"text": "Output : "
},
{
"code": null,
"e": 26808,
"s": 26688,
"text": "Original array : [0 1 2 3 4]\n\nMask set as : [False True False True True]\n\nDeletion Using a Boolean Mask : [1 3 4]"
},
{
"code": null,
"e": 27419,
"s": 26808,
"text": "References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.htmlNote : These codes won’t run on online IDE’s. Please run them on your systems to explore the working . This article is contributed by Mohit Gupta_OMG . 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": 27432,
"s": 27419,
"text": "aryen1713045"
},
{
"code": null,
"e": 27447,
"s": 27432,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 27478,
"s": 27447,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 27491,
"s": 27478,
"text": "Python-numpy"
},
{
"code": null,
"e": 27498,
"s": 27491,
"text": "Python"
},
{
"code": null,
"e": 27596,
"s": 27498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27605,
"s": 27596,
"text": "Comments"
},
{
"code": null,
"e": 27618,
"s": 27605,
"text": "Old Comments"
},
{
"code": null,
"e": 27636,
"s": 27618,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27668,
"s": 27636,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27703,
"s": 27668,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27745,
"s": 27703,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27788,
"s": 27745,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27825,
"s": 27788,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27851,
"s": 27825,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27895,
"s": 27851,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27924,
"s": 27895,
"text": "*args and **kwargs in Python"
}
] |
Split a number into 3 parts such that none of the parts is divisible by 3 | 24 Jun, 2022
You are given a number ‘N’. Your task is to split this number into 3 positive integers x, y, and z, such that their sum is equal to ‘N’ and none of the 3 integers is a multiple of 3. Given that N>=2.
Examples:
Input : N = 10 Output : x = 1, y = 2, z = 7 Note that x + y + z = N and x, y & z are not divisible by N.Input : 18 Output :x = 1, y = 1, z = 16
Approach: To split N into 3 numbers we split N as
If N is divisible by 3, then the numbers x, y, z can be 1, 1, and N-2, respectively. All x, y, and z are not divisible by 3. And (1)+(1)+(N-2)=N .If N is not divisible by 3 then N-3 will also not be divisible by 3. Therefore, we can have x=1, y=2, and z=N-3.Also, (1)+(2)+(N-3)=N .
If N is divisible by 3, then the numbers x, y, z can be 1, 1, and N-2, respectively. All x, y, and z are not divisible by 3. And (1)+(1)+(N-2)=N .
If N is not divisible by 3 then N-3 will also not be divisible by 3. Therefore, we can have x=1, y=2, and z=N-3.Also, (1)+(2)+(N-3)=N .
C++
Java
Python3
C#
PHP
Javascript
// CPP program to split a number into three parts such// than none of them is divisible by 3.#include <iostream>using namespace std; void printThreeParts(int N){ // Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) cout << " x = 1, y = 1, z = " << N - 2 << endl; // Otherwise, print x = 1, y = 2 and z = N - 3 else cout << " x = 1, y = 2, z = " << N - 3 << endl;} // Driver codeint main(){ int N = 10; printThreeParts(N); return 0;}
// Java program to split a number into three parts such// than none of them is divisible by 3.import java.util.*; class solution{ static void printThreeParts(int N){ // Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) System.out.println("x = 1, y = 1, z = "+ (N-2)); // Otherwise, print x = 1, y = 2 and z = N - 3 else System.out.println(" x = 1, y = 2, z = "+ (N-3));} // Driver codepublic static void main(String args[]){ int N = 10; printThreeParts(N); }}
# Python3 program to split a number into three parts such# than none of them is divisible by 3. def printThreeParts(N) : # Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) : print(" x = 1, y = 1, z = ",N - 2) # Otherwise, print x = 1, y = 2 and z = N - 3 else : print(" x = 1, y = 2, z = ",N - 3) # Driver codeif __name__ == "__main__" : N = 10 printThreeParts(N) # This code is contributed by Ryuga
// C# program to split a number into three parts such// than none of them is divisible by 3.using System; public class GFG{ static void printThreeParts(int N){ // Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) Console.WriteLine(" x = 1, y = 1, z = "+(N - 2)); // Otherwise, print x = 1, y = 2 and z = N - 3 else Console.WriteLine(" x = 1, y = 2, z = "+(N - 3));} // Driver code static public void Main (){ int N = 10; printThreeParts(N); }// This code is contributed by ajit.}
<?php// PHP program to split a number into// three parts such than none of them// is divisible by 3.function printThreeParts($N){ // Print x = 1, y = 1 and z = N - 2 if ($N % 3 == 0) echo " x = 1, y = 1, z = " . ($N - 2) . "\n"; // Otherwise, print x = 1, // y = 2 and z = N - 3 else echo " x = 1, y = 2, z = " . ($N - 3) . "\n";} // Driver code$N = 10;printThreeParts($N); // This code is contributed by ita_c?>
<script> // javascript program to split a number into three parts such// than none of them is divisible by 3. function printThreeParts(N){ // Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) document.write("x = 1, y = 1, z = "+ (N-2)); // Otherwise, print x = 1, y = 2 and z = N - 3 else document.write(" x = 1, y = 2, z = "+ (N-3));} // Driver code var N = 10;printThreeParts(N); // This code contributed by Princi Singh </script>
x = 1, y = 2, z = 7
Time Complexity: O(1), since there is no loop or recursion.
Auxiliary Space: O(1), since no extra space has been taken.
ankthon
ukasp
Mithun Kumar
SURENDRA_GANGWAR
jit_t
nidhi_biet
princi singh
rohitkumarsinghcna
Kirti_Mangal
souravmahato348
divisibility
programming-puzzle
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 253,
"s": 52,
"text": "You are given a number ‘N’. Your task is to split this number into 3 positive integers x, y, and z, such that their sum is equal to ‘N’ and none of the 3 integers is a multiple of 3. Given that N>=2. "
},
{
"code": null,
"e": 265,
"s": 253,
"text": "Examples: "
},
{
"code": null,
"e": 411,
"s": 265,
"text": "Input : N = 10 Output : x = 1, y = 2, z = 7 Note that x + y + z = N and x, y & z are not divisible by N.Input : 18 Output :x = 1, y = 1, z = 16 "
},
{
"code": null,
"e": 462,
"s": 411,
"text": "Approach: To split N into 3 numbers we split N as "
},
{
"code": null,
"e": 745,
"s": 462,
"text": "If N is divisible by 3, then the numbers x, y, z can be 1, 1, and N-2, respectively. All x, y, and z are not divisible by 3. And (1)+(1)+(N-2)=N .If N is not divisible by 3 then N-3 will also not be divisible by 3. Therefore, we can have x=1, y=2, and z=N-3.Also, (1)+(2)+(N-3)=N . "
},
{
"code": null,
"e": 892,
"s": 745,
"text": "If N is divisible by 3, then the numbers x, y, z can be 1, 1, and N-2, respectively. All x, y, and z are not divisible by 3. And (1)+(1)+(N-2)=N ."
},
{
"code": null,
"e": 1029,
"s": 892,
"text": "If N is not divisible by 3 then N-3 will also not be divisible by 3. Therefore, we can have x=1, y=2, and z=N-3.Also, (1)+(2)+(N-3)=N . "
},
{
"code": null,
"e": 1033,
"s": 1029,
"text": "C++"
},
{
"code": null,
"e": 1038,
"s": 1033,
"text": "Java"
},
{
"code": null,
"e": 1046,
"s": 1038,
"text": "Python3"
},
{
"code": null,
"e": 1049,
"s": 1046,
"text": "C#"
},
{
"code": null,
"e": 1053,
"s": 1049,
"text": "PHP"
},
{
"code": null,
"e": 1064,
"s": 1053,
"text": "Javascript"
},
{
"code": "// CPP program to split a number into three parts such// than none of them is divisible by 3.#include <iostream>using namespace std; void printThreeParts(int N){ // Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) cout << \" x = 1, y = 1, z = \" << N - 2 << endl; // Otherwise, print x = 1, y = 2 and z = N - 3 else cout << \" x = 1, y = 2, z = \" << N - 3 << endl;} // Driver codeint main(){ int N = 10; printThreeParts(N); return 0;}",
"e": 1532,
"s": 1064,
"text": null
},
{
"code": "// Java program to split a number into three parts such// than none of them is divisible by 3.import java.util.*; class solution{ static void printThreeParts(int N){ // Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) System.out.println(\"x = 1, y = 1, z = \"+ (N-2)); // Otherwise, print x = 1, y = 2 and z = N - 3 else System.out.println(\" x = 1, y = 2, z = \"+ (N-3));} // Driver codepublic static void main(String args[]){ int N = 10; printThreeParts(N); }}",
"e": 2037,
"s": 1532,
"text": null
},
{
"code": "# Python3 program to split a number into three parts such# than none of them is divisible by 3. def printThreeParts(N) : # Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) : print(\" x = 1, y = 1, z = \",N - 2) # Otherwise, print x = 1, y = 2 and z = N - 3 else : print(\" x = 1, y = 2, z = \",N - 3) # Driver codeif __name__ == \"__main__\" : N = 10 printThreeParts(N) # This code is contributed by Ryuga",
"e": 2475,
"s": 2037,
"text": null
},
{
"code": "// C# program to split a number into three parts such// than none of them is divisible by 3.using System; public class GFG{ static void printThreeParts(int N){ // Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) Console.WriteLine(\" x = 1, y = 1, z = \"+(N - 2)); // Otherwise, print x = 1, y = 2 and z = N - 3 else Console.WriteLine(\" x = 1, y = 2, z = \"+(N - 3));} // Driver code static public void Main (){ int N = 10; printThreeParts(N); }// This code is contributed by ajit.}",
"e": 2998,
"s": 2475,
"text": null
},
{
"code": "<?php// PHP program to split a number into// three parts such than none of them// is divisible by 3.function printThreeParts($N){ // Print x = 1, y = 1 and z = N - 2 if ($N % 3 == 0) echo \" x = 1, y = 1, z = \" . ($N - 2) . \"\\n\"; // Otherwise, print x = 1, // y = 2 and z = N - 3 else echo \" x = 1, y = 2, z = \" . ($N - 3) . \"\\n\";} // Driver code$N = 10;printThreeParts($N); // This code is contributed by ita_c?>",
"e": 3479,
"s": 2998,
"text": null
},
{
"code": "<script> // javascript program to split a number into three parts such// than none of them is divisible by 3. function printThreeParts(N){ // Print x = 1, y = 1 and z = N - 2 if (N % 3 == 0) document.write(\"x = 1, y = 1, z = \"+ (N-2)); // Otherwise, print x = 1, y = 2 and z = N - 3 else document.write(\" x = 1, y = 2, z = \"+ (N-3));} // Driver code var N = 10;printThreeParts(N); // This code contributed by Princi Singh </script>",
"e": 3948,
"s": 3479,
"text": null
},
{
"code": null,
"e": 3968,
"s": 3948,
"text": "x = 1, y = 2, z = 7"
},
{
"code": null,
"e": 4030,
"s": 3970,
"text": "Time Complexity: O(1), since there is no loop or recursion."
},
{
"code": null,
"e": 4090,
"s": 4030,
"text": "Auxiliary Space: O(1), since no extra space has been taken."
},
{
"code": null,
"e": 4098,
"s": 4090,
"text": "ankthon"
},
{
"code": null,
"e": 4104,
"s": 4098,
"text": "ukasp"
},
{
"code": null,
"e": 4117,
"s": 4104,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 4134,
"s": 4117,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 4140,
"s": 4134,
"text": "jit_t"
},
{
"code": null,
"e": 4151,
"s": 4140,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4164,
"s": 4151,
"text": "princi singh"
},
{
"code": null,
"e": 4183,
"s": 4164,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 4196,
"s": 4183,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 4212,
"s": 4196,
"text": "souravmahato348"
},
{
"code": null,
"e": 4225,
"s": 4212,
"text": "divisibility"
},
{
"code": null,
"e": 4244,
"s": 4225,
"text": "programming-puzzle"
},
{
"code": null,
"e": 4257,
"s": 4244,
"text": "Mathematical"
},
{
"code": null,
"e": 4270,
"s": 4257,
"text": "Mathematical"
},
{
"code": null,
"e": 4368,
"s": 4270,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4392,
"s": 4368,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 4413,
"s": 4392,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4435,
"s": 4413,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 4449,
"s": 4435,
"text": "Prime Numbers"
},
{
"code": null,
"e": 4491,
"s": 4449,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 4528,
"s": 4491,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 4581,
"s": 4528,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 4613,
"s": 4581,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 4654,
"s": 4613,
"text": "Program for Decimal to Binary Conversion"
}
] |
Variation of Pressure With Depth | 21 Jul, 2021
It’s reasonable to assume that the deeper a person travels into a liquid or gas, the higher the pressure exerted on him by the surrounding fluid. The reason for the increasing pressure is that the deeper a person goes into a fluid, the more fluid he has over top of him, and therefore the more weight he has.
Pressure: The ratio of the force applied to the surface area over which the force is applied is known as the pressure. The pressure imposed by liquids is known as hydrostatic pressure. The SI unit of pressure is Pascal.
Solid things do not change form when pressure is applied, which is obviously not the case with fluids. In a closed container, fluid pressure can be generated by gravity, acceleration, or forces. The fluid acts equally in all directions since it has no set form. When you fill a bottle with water, the weight of the water acts evenly on both sides of the bottle.
The force is always exerted perpendicular to the container’s surface. This may be seen in a balloon. As you fill the balloon with air, you’ll note that it grows evenly, with no one side inflating more than the other. Liquids in a container also show this behaviour.
The hydrostatic pressure is the pressure exerted by a fluid in equilibrium owing to gravity at any given period. When a downward force is applied, hydrostatic pressure is proportional to the depth measured from the surface as the weight of the fluid increases.
Fluids exert equal pressure in all directions. Another intriguing event occurs as a result of this rule. When we examine the layer of water on top of a bottle, the pressure it exerts acts on the edges of the container, the air surface on top, and the layer of water at the bottom. The pressure imposed by the top layer on the bottom increases as we go down the bottle from top to bottom.
The fluid at bottom of the container receives higher pressure than the fluid above it as a result of this process.
Take a look at the figure below for an example of a container. The weight of fluid inside it is supported by its bottom. Let’s see how much pressure the weight of liquids exerts on the bottom. The weight of fluid ‘mg’ divided by the area ‘A’ equals the pressure.
Weight of the fluid, W = m g
Mass of the fluid is equal to product of volume and density of substance, i.e., m = ρ V
Volume of the fluid is equal to the dimension of the container, i.e., V = A h
Combine the last two equations for mass.
m = ρ A h
Therefore, weight of the fluid, W = ρ A h g
The pressure exerted on the bottom of the container is given as:
P = W ⁄ A
P = (ρ A h g) ⁄ A
P = ρ h g
where,
ρ is the density of fluid
A is the surface area of container
h is the height upto the fluid is filled in container
V is the volume of fluid
m is the mass of fluid
g is the acceleration due to gravity
W is the weight of fluid
P is the pressure exerted on the bottom of the container.
This is the pressure created by a fluid’s weight. Beyond the specific conditions under which it is derived here, the equation has generic validity. The surrounding fluid would exert this pressure even if the container was not there, keeping the fluid static. This equation remains true to deep depths for liquids that are practically incompressible. This equation may be used for gases that are very compressible as long as the density variations are minimal across the depth covered.
Problem 1: Define the relationship between the pressure and height of the liquid column.
Answer:
The pressure exerted by a liquid depends on the height of the liquid column.
Pressure can be written as P = ρ g h where h is height and ρ is density. The formula shows the direct relation between the pressure and height of the column.
Therefore, as the height increases, pressure will also increase .
Problem 2: Calculate the force exerted by water on the base of a tank of area 3 m2 when filled with water up to a height of 2 m. (Density of water is 1000 kg m−3 and g = 10 m s−2).
Solution:
Given:
Area of base of tank, A = 3 m2
Height of the tank filled with water, h = 2 m
Density of the fluid, ρ = 1000 kg m−3
The formula of the pressure is given as:
P = ρ g h
= (1000 × 10 × 2) N m−2
= 20000 N m−2
The force exerted by the water,
F = P A
= (20000 × 3) N
= 60000 N
Hence, the force exerted by the water is 60000 N.
Problem 3: Why the dam of the water reservoir is thick at the bottom?
Answer:
The dam of a water reservoir is thick at the bottom because the pressure of water is highest at the maximum depth, and the dam must be strong at the bottom to withstand this maximum pressure.
Problem 4: What is hydrostatic pressure?
Answer:
The hydrostatic pressure is the pressure exerted by a fluid in equilibrium owing to gravity at any given period. When a downward force is applied, hydrostatic pressure is proportional to the depth measured from the surface as the weight of the fluid increases.
Problem 5: What is the pressure acting on the water at a depth of 2 m at 4°C?
Solution:
Given:
The depth of water column, h = 2 m
The density of water at 4°C, ρ = 1000 kg ⁄ m3
The formula of the pressure is given as:
P = ρgh
= (1000 × 9.81 × 1) Pa
= 9810 Pa.
Hence, the pressure acting on the water at a depth of 2 m is 9810 Pa.
Picked
Class 11
School Learning
School Physics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Geometric Series
Steps in Formation of a Company
Importance of Chemistry in Everyday Life
Introduction to Boolean Logic
Nature and Types of Services
How to Align Text in HTML?
Libraries in Python
Geometric Series
Generations of Computers - Computer Fundamentals
What are Different Output Devices? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 361,
"s": 52,
"text": "It’s reasonable to assume that the deeper a person travels into a liquid or gas, the higher the pressure exerted on him by the surrounding fluid. The reason for the increasing pressure is that the deeper a person goes into a fluid, the more fluid he has over top of him, and therefore the more weight he has."
},
{
"code": null,
"e": 581,
"s": 361,
"text": "Pressure: The ratio of the force applied to the surface area over which the force is applied is known as the pressure. The pressure imposed by liquids is known as hydrostatic pressure. The SI unit of pressure is Pascal."
},
{
"code": null,
"e": 943,
"s": 581,
"text": "Solid things do not change form when pressure is applied, which is obviously not the case with fluids. In a closed container, fluid pressure can be generated by gravity, acceleration, or forces. The fluid acts equally in all directions since it has no set form. When you fill a bottle with water, the weight of the water acts evenly on both sides of the bottle."
},
{
"code": null,
"e": 1209,
"s": 943,
"text": "The force is always exerted perpendicular to the container’s surface. This may be seen in a balloon. As you fill the balloon with air, you’ll note that it grows evenly, with no one side inflating more than the other. Liquids in a container also show this behaviour."
},
{
"code": null,
"e": 1470,
"s": 1209,
"text": "The hydrostatic pressure is the pressure exerted by a fluid in equilibrium owing to gravity at any given period. When a downward force is applied, hydrostatic pressure is proportional to the depth measured from the surface as the weight of the fluid increases."
},
{
"code": null,
"e": 1858,
"s": 1470,
"text": "Fluids exert equal pressure in all directions. Another intriguing event occurs as a result of this rule. When we examine the layer of water on top of a bottle, the pressure it exerts acts on the edges of the container, the air surface on top, and the layer of water at the bottom. The pressure imposed by the top layer on the bottom increases as we go down the bottle from top to bottom."
},
{
"code": null,
"e": 1973,
"s": 1858,
"text": "The fluid at bottom of the container receives higher pressure than the fluid above it as a result of this process."
},
{
"code": null,
"e": 2236,
"s": 1973,
"text": "Take a look at the figure below for an example of a container. The weight of fluid inside it is supported by its bottom. Let’s see how much pressure the weight of liquids exerts on the bottom. The weight of fluid ‘mg’ divided by the area ‘A’ equals the pressure."
},
{
"code": null,
"e": 2265,
"s": 2236,
"text": "Weight of the fluid, W = m g"
},
{
"code": null,
"e": 2353,
"s": 2265,
"text": "Mass of the fluid is equal to product of volume and density of substance, i.e., m = ρ V"
},
{
"code": null,
"e": 2431,
"s": 2353,
"text": "Volume of the fluid is equal to the dimension of the container, i.e., V = A h"
},
{
"code": null,
"e": 2472,
"s": 2431,
"text": "Combine the last two equations for mass."
},
{
"code": null,
"e": 2482,
"s": 2472,
"text": "m = ρ A h"
},
{
"code": null,
"e": 2526,
"s": 2482,
"text": "Therefore, weight of the fluid, W = ρ A h g"
},
{
"code": null,
"e": 2591,
"s": 2526,
"text": "The pressure exerted on the bottom of the container is given as:"
},
{
"code": null,
"e": 2601,
"s": 2591,
"text": "P = W ⁄ A"
},
{
"code": null,
"e": 2619,
"s": 2601,
"text": "P = (ρ A h g) ⁄ A"
},
{
"code": null,
"e": 2629,
"s": 2619,
"text": "P = ρ h g"
},
{
"code": null,
"e": 2636,
"s": 2629,
"text": "where,"
},
{
"code": null,
"e": 2662,
"s": 2636,
"text": "ρ is the density of fluid"
},
{
"code": null,
"e": 2697,
"s": 2662,
"text": "A is the surface area of container"
},
{
"code": null,
"e": 2751,
"s": 2697,
"text": "h is the height upto the fluid is filled in container"
},
{
"code": null,
"e": 2776,
"s": 2751,
"text": "V is the volume of fluid"
},
{
"code": null,
"e": 2799,
"s": 2776,
"text": "m is the mass of fluid"
},
{
"code": null,
"e": 2836,
"s": 2799,
"text": "g is the acceleration due to gravity"
},
{
"code": null,
"e": 2861,
"s": 2836,
"text": "W is the weight of fluid"
},
{
"code": null,
"e": 2919,
"s": 2861,
"text": "P is the pressure exerted on the bottom of the container."
},
{
"code": null,
"e": 3404,
"s": 2919,
"text": "This is the pressure created by a fluid’s weight. Beyond the specific conditions under which it is derived here, the equation has generic validity. The surrounding fluid would exert this pressure even if the container was not there, keeping the fluid static. This equation remains true to deep depths for liquids that are practically incompressible. This equation may be used for gases that are very compressible as long as the density variations are minimal across the depth covered."
},
{
"code": null,
"e": 3493,
"s": 3404,
"text": "Problem 1: Define the relationship between the pressure and height of the liquid column."
},
{
"code": null,
"e": 3501,
"s": 3493,
"text": "Answer:"
},
{
"code": null,
"e": 3578,
"s": 3501,
"text": "The pressure exerted by a liquid depends on the height of the liquid column."
},
{
"code": null,
"e": 3737,
"s": 3578,
"text": "Pressure can be written as P = ρ g h where h is height and ρ is density. The formula shows the direct relation between the pressure and height of the column. "
},
{
"code": null,
"e": 3803,
"s": 3737,
"text": "Therefore, as the height increases, pressure will also increase ."
},
{
"code": null,
"e": 3984,
"s": 3803,
"text": "Problem 2: Calculate the force exerted by water on the base of a tank of area 3 m2 when filled with water up to a height of 2 m. (Density of water is 1000 kg m−3 and g = 10 m s−2)."
},
{
"code": null,
"e": 3994,
"s": 3984,
"text": "Solution:"
},
{
"code": null,
"e": 4001,
"s": 3994,
"text": "Given:"
},
{
"code": null,
"e": 4032,
"s": 4001,
"text": "Area of base of tank, A = 3 m2"
},
{
"code": null,
"e": 4078,
"s": 4032,
"text": "Height of the tank filled with water, h = 2 m"
},
{
"code": null,
"e": 4116,
"s": 4078,
"text": "Density of the fluid, ρ = 1000 kg m−3"
},
{
"code": null,
"e": 4157,
"s": 4116,
"text": "The formula of the pressure is given as:"
},
{
"code": null,
"e": 4167,
"s": 4157,
"text": "P = ρ g h"
},
{
"code": null,
"e": 4191,
"s": 4167,
"text": "= (1000 × 10 × 2) N m−2"
},
{
"code": null,
"e": 4205,
"s": 4191,
"text": "= 20000 N m−2"
},
{
"code": null,
"e": 4237,
"s": 4205,
"text": "The force exerted by the water,"
},
{
"code": null,
"e": 4245,
"s": 4237,
"text": "F = P A"
},
{
"code": null,
"e": 4261,
"s": 4245,
"text": "= (20000 × 3) N"
},
{
"code": null,
"e": 4271,
"s": 4261,
"text": "= 60000 N"
},
{
"code": null,
"e": 4321,
"s": 4271,
"text": "Hence, the force exerted by the water is 60000 N."
},
{
"code": null,
"e": 4391,
"s": 4321,
"text": "Problem 3: Why the dam of the water reservoir is thick at the bottom?"
},
{
"code": null,
"e": 4399,
"s": 4391,
"text": "Answer:"
},
{
"code": null,
"e": 4591,
"s": 4399,
"text": "The dam of a water reservoir is thick at the bottom because the pressure of water is highest at the maximum depth, and the dam must be strong at the bottom to withstand this maximum pressure."
},
{
"code": null,
"e": 4632,
"s": 4591,
"text": "Problem 4: What is hydrostatic pressure?"
},
{
"code": null,
"e": 4640,
"s": 4632,
"text": "Answer:"
},
{
"code": null,
"e": 4901,
"s": 4640,
"text": "The hydrostatic pressure is the pressure exerted by a fluid in equilibrium owing to gravity at any given period. When a downward force is applied, hydrostatic pressure is proportional to the depth measured from the surface as the weight of the fluid increases."
},
{
"code": null,
"e": 4979,
"s": 4901,
"text": "Problem 5: What is the pressure acting on the water at a depth of 2 m at 4°C?"
},
{
"code": null,
"e": 4989,
"s": 4979,
"text": "Solution:"
},
{
"code": null,
"e": 4996,
"s": 4989,
"text": "Given:"
},
{
"code": null,
"e": 5031,
"s": 4996,
"text": "The depth of water column, h = 2 m"
},
{
"code": null,
"e": 5077,
"s": 5031,
"text": "The density of water at 4°C, ρ = 1000 kg ⁄ m3"
},
{
"code": null,
"e": 5118,
"s": 5077,
"text": "The formula of the pressure is given as:"
},
{
"code": null,
"e": 5126,
"s": 5118,
"text": "P = ρgh"
},
{
"code": null,
"e": 5149,
"s": 5126,
"text": "= (1000 × 9.81 × 1) Pa"
},
{
"code": null,
"e": 5160,
"s": 5149,
"text": "= 9810 Pa."
},
{
"code": null,
"e": 5230,
"s": 5160,
"text": "Hence, the pressure acting on the water at a depth of 2 m is 9810 Pa."
},
{
"code": null,
"e": 5237,
"s": 5230,
"text": "Picked"
},
{
"code": null,
"e": 5246,
"s": 5237,
"text": "Class 11"
},
{
"code": null,
"e": 5262,
"s": 5246,
"text": "School Learning"
},
{
"code": null,
"e": 5277,
"s": 5262,
"text": "School Physics"
},
{
"code": null,
"e": 5375,
"s": 5277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5392,
"s": 5375,
"text": "Geometric Series"
},
{
"code": null,
"e": 5424,
"s": 5392,
"text": "Steps in Formation of a Company"
},
{
"code": null,
"e": 5465,
"s": 5424,
"text": "Importance of Chemistry in Everyday Life"
},
{
"code": null,
"e": 5495,
"s": 5465,
"text": "Introduction to Boolean Logic"
},
{
"code": null,
"e": 5524,
"s": 5495,
"text": "Nature and Types of Services"
},
{
"code": null,
"e": 5551,
"s": 5524,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 5571,
"s": 5551,
"text": "Libraries in Python"
},
{
"code": null,
"e": 5588,
"s": 5571,
"text": "Geometric Series"
},
{
"code": null,
"e": 5637,
"s": 5588,
"text": "Generations of Computers - Computer Fundamentals"
}
] |
How to check version of python modules? | When you install Python, you also get the Python package manager, pip. You can use pip to get the versions of python modules. If you want to list all installed Python modules with their version numbers, use the following command:
$ 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
...
To individually find the version number you can grep on this output on *NIX machines. For example:
$ pip freeze | grep PyMySQL
PyMySQL==0.7.11
On windows, you can use findstr instead of grep. For example:
PS C:\> pip freeze | findstr PyMySql
PyMySQL==0.7.11
If you want to know the version of a module within a Python script, you can use the __version__ attribute of the module to get it. Note that not all modules come with a __version__ attribute. For example,
>>> import pylint
>>> pylint.__version__
'1.7.1' | [
{
"code": null,
"e": 1417,
"s": 1187,
"text": "When you install Python, you also get the Python package manager, pip. You can use pip to get the versions of python modules. If you want to list all installed Python modules with their version numbers, use the following command:"
},
{
"code": null,
"e": 1430,
"s": 1417,
"text": "$ pip freeze"
},
{
"code": null,
"e": 1455,
"s": 1430,
"text": "You will get the output:"
},
{
"code": null,
"e": 1570,
"s": 1455,
"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": 1669,
"s": 1570,
"text": "To individually find the version number you can grep on this output on *NIX machines. For example:"
},
{
"code": null,
"e": 1713,
"s": 1669,
"text": "$ pip freeze | grep PyMySQL\nPyMySQL==0.7.11"
},
{
"code": null,
"e": 1775,
"s": 1713,
"text": "On windows, you can use findstr instead of grep. For example:"
},
{
"code": null,
"e": 1828,
"s": 1775,
"text": "PS C:\\> pip freeze | findstr PyMySql\nPyMySQL==0.7.11"
},
{
"code": null,
"e": 2033,
"s": 1828,
"text": "If you want to know the version of a module within a Python script, you can use the __version__ attribute of the module to get it. Note that not all modules come with a __version__ attribute. For example,"
},
{
"code": null,
"e": 2082,
"s": 2033,
"text": ">>> import pylint\n>>> pylint.__version__\n'1.7.1'"
}
] |
Node.js crypto.createCipheriv() Method | 17 Nov, 2021
The crypto.createCipheriv() method is an inbuilt application programming interface of the crypto module which is used to create a Cipher object, with the stated algorithm, key and initialization vector (iv).Syntax:
crypto.createCipheriv( algorithm, key, iv, options )
Parameters: This method accept four parameters as mentioned above and described below:
algorithm: It is a string type value that dependent on OpenSSL. The examples are aes192, aes256, etc.
key: It is the raw key which is used by the algorithm and iv. It holds the string, Buffer, TypedArray or DataView. The key can be a KeyObject optionally of type secret.
iv: It is an initialization vector that must be uncertain and very unique. However, an ideal iv will be cryptographically random. It don’t need to be secret. It can holds string, Buffer, TypedArray, or DataView type data. If cipher doesn’t requires iv then it can be null.
options: It is an optional parameter that is used to control stream behavior. It is optional except when a cipher is used in CCM or OCB mode(e.g. ‘aes-128-ccm’). In that case, the authTagLength option is required which defines the length(bytes) of the authentication tag whereas, in GCM mode, the authTagLength option is not needed but it can be used to set the length of the authentication tag that will be returned by the getAuthTag() method and the default value is 16 bytes.
Return Value: It returns Cipher object.Below examples illustrate the use of crypto.createCipheriv() method in Node.js:Example 1:
javascript
// Node.js program to demonstrate the // crypto.createCipheriv() method // Includes crypto moduleconst crypto = require('crypto'); // Defining algorithmconst algorithm = 'aes-256-cbc'; // Defining keyconst key = crypto.randomBytes(32); // Defining ivconst iv = crypto.randomBytes(16); // An encrypt functionfunction encrypt(text) { // Creating Cipheriv with its parameter let cipher = crypto.createCipheriv( 'aes-256-cbc', Buffer.from(key), iv); // Updating text let encrypted = cipher.update(text); // Using concatenation encrypted = Buffer.concat([encrypted, cipher.final()]); // Returning iv and encrypted data return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };} // Displays outputvar output = encrypt("GeeksforGeeks");console.log(output);
Output:
{ iv: 'fb1f4b0a7daaada6cae678df32fad0f0',
encryptedData: '41aad2618892aa3d1850d336ad15b50e' }
Example 2:
javascript
// Node.js program to demonstrate the // crypto.createCipheriv() method // Includes crypto moduleconst crypto = require('crypto'); // Defining algorithmconst algorithm = 'aes-192-cbc'; // Defining passwordconst password = 'bncaskdbvasbvlaslslasfhj'; // Defining keyconst key = crypto.scryptSync(password, 'GfG', 24); // Defininf ivconst iv = Buffer.alloc(16, 0); // Creating cipherconst cipher = crypto.createCipheriv(algorithm, key, iv); // Declaring encryptedlet encrypted = ''; // Reading datacipher.on('readable', () => { let chunk; while (null !== (chunk = cipher.read())) { encrypted += chunk.toString('base64'); }}); // Handling end eventcipher.on('end', () => {console.log(encrypted);}); // Writing datacipher.write('CS-Portal');cipher.end();console.log("done");
Output:
done
MfHwhG/WPv+TIbG/qM78qA==
Reference: https://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options
surinderdawra388
Node.js-crypto-module
Node.js
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": "\n17 Nov, 2021"
},
{
"code": null,
"e": 244,
"s": 28,
"text": "The crypto.createCipheriv() method is an inbuilt application programming interface of the crypto module which is used to create a Cipher object, with the stated algorithm, key and initialization vector (iv).Syntax: "
},
{
"code": null,
"e": 297,
"s": 244,
"text": "crypto.createCipheriv( algorithm, key, iv, options )"
},
{
"code": null,
"e": 386,
"s": 297,
"text": "Parameters: This method accept four parameters as mentioned above and described below: "
},
{
"code": null,
"e": 488,
"s": 386,
"text": "algorithm: It is a string type value that dependent on OpenSSL. The examples are aes192, aes256, etc."
},
{
"code": null,
"e": 657,
"s": 488,
"text": "key: It is the raw key which is used by the algorithm and iv. It holds the string, Buffer, TypedArray or DataView. The key can be a KeyObject optionally of type secret."
},
{
"code": null,
"e": 930,
"s": 657,
"text": "iv: It is an initialization vector that must be uncertain and very unique. However, an ideal iv will be cryptographically random. It don’t need to be secret. It can holds string, Buffer, TypedArray, or DataView type data. If cipher doesn’t requires iv then it can be null."
},
{
"code": null,
"e": 1409,
"s": 930,
"text": "options: It is an optional parameter that is used to control stream behavior. It is optional except when a cipher is used in CCM or OCB mode(e.g. ‘aes-128-ccm’). In that case, the authTagLength option is required which defines the length(bytes) of the authentication tag whereas, in GCM mode, the authTagLength option is not needed but it can be used to set the length of the authentication tag that will be returned by the getAuthTag() method and the default value is 16 bytes."
},
{
"code": null,
"e": 1540,
"s": 1409,
"text": "Return Value: It returns Cipher object.Below examples illustrate the use of crypto.createCipheriv() method in Node.js:Example 1: "
},
{
"code": null,
"e": 1551,
"s": 1540,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the // crypto.createCipheriv() method // Includes crypto moduleconst crypto = require('crypto'); // Defining algorithmconst algorithm = 'aes-256-cbc'; // Defining keyconst key = crypto.randomBytes(32); // Defining ivconst iv = crypto.randomBytes(16); // An encrypt functionfunction encrypt(text) { // Creating Cipheriv with its parameter let cipher = crypto.createCipheriv( 'aes-256-cbc', Buffer.from(key), iv); // Updating text let encrypted = cipher.update(text); // Using concatenation encrypted = Buffer.concat([encrypted, cipher.final()]); // Returning iv and encrypted data return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };} // Displays outputvar output = encrypt(\"GeeksforGeeks\");console.log(output);",
"e": 2335,
"s": 1551,
"text": null
},
{
"code": null,
"e": 2344,
"s": 2335,
"text": "Output: "
},
{
"code": null,
"e": 2440,
"s": 2344,
"text": "{ iv: 'fb1f4b0a7daaada6cae678df32fad0f0',\n encryptedData: '41aad2618892aa3d1850d336ad15b50e' }"
},
{
"code": null,
"e": 2453,
"s": 2440,
"text": "Example 2: "
},
{
"code": null,
"e": 2464,
"s": 2453,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the // crypto.createCipheriv() method // Includes crypto moduleconst crypto = require('crypto'); // Defining algorithmconst algorithm = 'aes-192-cbc'; // Defining passwordconst password = 'bncaskdbvasbvlaslslasfhj'; // Defining keyconst key = crypto.scryptSync(password, 'GfG', 24); // Defininf ivconst iv = Buffer.alloc(16, 0); // Creating cipherconst cipher = crypto.createCipheriv(algorithm, key, iv); // Declaring encryptedlet encrypted = ''; // Reading datacipher.on('readable', () => { let chunk; while (null !== (chunk = cipher.read())) { encrypted += chunk.toString('base64'); }}); // Handling end eventcipher.on('end', () => {console.log(encrypted);}); // Writing datacipher.write('CS-Portal');cipher.end();console.log(\"done\");",
"e": 3244,
"s": 2464,
"text": null
},
{
"code": null,
"e": 3253,
"s": 3244,
"text": "Output: "
},
{
"code": null,
"e": 3283,
"s": 3253,
"text": "done\nMfHwhG/WPv+TIbG/qM78qA=="
},
{
"code": null,
"e": 3384,
"s": 3283,
"text": "Reference: https://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options "
},
{
"code": null,
"e": 3401,
"s": 3384,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3423,
"s": 3401,
"text": "Node.js-crypto-module"
},
{
"code": null,
"e": 3431,
"s": 3423,
"text": "Node.js"
},
{
"code": null,
"e": 3448,
"s": 3431,
"text": "Web Technologies"
}
] |
Intellij Idea - Debugging | Debugger makes application debugging much easier. Using debugger, we can stop the execution of program at a certain point, inspect variables, step into function and do many things. IntelliJ provides inbuilt Java debugger.
Breakpoint allows stopping program execution at certain point. Breakpoints can be set by hovering the mouse over the Editor’s gutter area and clicking on it.
Breakpoints are denoted using red circle symbols. Consider the breakpoint set at line 3.
Consider the following steps to understand more on how the breakpoints work −
Right-click on the red circle symbol.
Right-click on the red circle symbol.
Select the More options.
Select the More options.
To remove breakpoint just click on same symbol.
To remove breakpoint just click on same symbol.
Follow these steps to start the debugger −
Navigate to the Run menu.
Select the Debug option.
While debugging, if a function is encountered and a step into action is selected, then debugger will stop program execution at each point of that function as if debugging is enabled for that function.
For instance, when program execution reaches at line 9 and if we select the step into action then it stops the execution at each line in the sayGoodBye() function.
The Step out action is exactly the reverse of Step in action. For instance, if you perform the step out action with the above scenario then debugger will return from the sayGoodBye() method and start execution at line 10.
The Step over action does not enter into function instead, it will jump to the next line of code. For instance, if you are at line 9 and execute the step over action then it will move execution to line 10.
The Resume Program action will continue execution of program by ignoring all breakpoints.
The Stop action helps stop the debugger.
While debugging, we may sometimes reach a line of code that calls several methods. When debugging these lines of code, the debugger typically allows us to use step into and leads us through all child functions and then back to the parent function. However, what if we only wanted to step into one child function? With Smart step-into, it allows us to choose the function to step into.
Now, let us create a Java class with the following line of code −
public class HelloWorld {
public static void main(String[] args) {
allFunctions();
}
static void allFunctions() {
System.out.println(function1() + " " + function2() + " " + function3());
}
static String function1() {
return "function1";
}
static String function2() {
return "function2";
}
static String function3() {
return "function3";
}
}
In the above code, allFunctions() calls 3 more functions. Let us set the breakpoint at
this function. Follow these steps to perform smart step into −
Go to run
Select smart step into.
Select the child function to go.
During debugging, IntelliJ shows value of variable in the Editor window itself. We can also
view the same information in the Debug window.
Evaluate expression allows to evaluate expression on the fly. Follow these steps to perform
this action −
Start application in debugger
Start application in debugger
Navigate to Run->Evaluate expression.
Navigate to Run->Evaluate expression.
Enter expression. In the example given below, the current value of variable ‘i’ is 0;
hence, expression ‘i > 100’ will evaluate to false
Enter expression. In the example given below, the current value of variable ‘i’ is 0;
hence, expression ‘i > 100’ will evaluate to false | [
{
"code": null,
"e": 2445,
"s": 2223,
"text": "Debugger makes application debugging much easier. Using debugger, we can stop the execution of program at a certain point, inspect variables, step into function and do many things. IntelliJ provides inbuilt Java debugger."
},
{
"code": null,
"e": 2603,
"s": 2445,
"text": "Breakpoint allows stopping program execution at certain point. Breakpoints can be set by hovering the mouse over the Editor’s gutter area and clicking on it."
},
{
"code": null,
"e": 2692,
"s": 2603,
"text": "Breakpoints are denoted using red circle symbols. Consider the breakpoint set at line 3."
},
{
"code": null,
"e": 2770,
"s": 2692,
"text": "Consider the following steps to understand more on how the breakpoints work −"
},
{
"code": null,
"e": 2808,
"s": 2770,
"text": "Right-click on the red circle symbol."
},
{
"code": null,
"e": 2846,
"s": 2808,
"text": "Right-click on the red circle symbol."
},
{
"code": null,
"e": 2871,
"s": 2846,
"text": "Select the More options."
},
{
"code": null,
"e": 2896,
"s": 2871,
"text": "Select the More options."
},
{
"code": null,
"e": 2944,
"s": 2896,
"text": "To remove breakpoint just click on same symbol."
},
{
"code": null,
"e": 2992,
"s": 2944,
"text": "To remove breakpoint just click on same symbol."
},
{
"code": null,
"e": 3035,
"s": 2992,
"text": "Follow these steps to start the debugger −"
},
{
"code": null,
"e": 3061,
"s": 3035,
"text": "Navigate to the Run menu."
},
{
"code": null,
"e": 3086,
"s": 3061,
"text": "Select the Debug option."
},
{
"code": null,
"e": 3287,
"s": 3086,
"text": "While debugging, if a function is encountered and a step into action is selected, then debugger will stop program execution at each point of that function as if debugging is enabled for that function."
},
{
"code": null,
"e": 3451,
"s": 3287,
"text": "For instance, when program execution reaches at line 9 and if we select the step into action then it stops the execution at each line in the sayGoodBye() function."
},
{
"code": null,
"e": 3673,
"s": 3451,
"text": "The Step out action is exactly the reverse of Step in action. For instance, if you perform the step out action with the above scenario then debugger will return from the sayGoodBye() method and start execution at line 10."
},
{
"code": null,
"e": 3879,
"s": 3673,
"text": "The Step over action does not enter into function instead, it will jump to the next line of code. For instance, if you are at line 9 and execute the step over action then it will move execution to line 10."
},
{
"code": null,
"e": 3969,
"s": 3879,
"text": "The Resume Program action will continue execution of program by ignoring all breakpoints."
},
{
"code": null,
"e": 4010,
"s": 3969,
"text": "The Stop action helps stop the debugger."
},
{
"code": null,
"e": 4395,
"s": 4010,
"text": "While debugging, we may sometimes reach a line of code that calls several methods. When debugging these lines of code, the debugger typically allows us to use step into and leads us through all child functions and then back to the parent function. However, what if we only wanted to step into one child function? With Smart step-into, it allows us to choose the function to step into."
},
{
"code": null,
"e": 4461,
"s": 4395,
"text": "Now, let us create a Java class with the following line of code −"
},
{
"code": null,
"e": 4862,
"s": 4461,
"text": "public class HelloWorld {\n public static void main(String[] args) {\n allFunctions();\n }\n static void allFunctions() {\n System.out.println(function1() + \" \" + function2() + \" \" + function3());\n }\n static String function1() {\n return \"function1\";\n }\n static String function2() {\n return \"function2\";\n }\n static String function3() {\n return \"function3\";\n }\n}"
},
{
"code": null,
"e": 5012,
"s": 4862,
"text": "In the above code, allFunctions() calls 3 more functions. Let us set the breakpoint at\nthis function. Follow these steps to perform smart step into −"
},
{
"code": null,
"e": 5022,
"s": 5012,
"text": "Go to run"
},
{
"code": null,
"e": 5046,
"s": 5022,
"text": "Select smart step into."
},
{
"code": null,
"e": 5079,
"s": 5046,
"text": "Select the child function to go."
},
{
"code": null,
"e": 5218,
"s": 5079,
"text": "During debugging, IntelliJ shows value of variable in the Editor window itself. We can also\nview the same information in the Debug window."
},
{
"code": null,
"e": 5324,
"s": 5218,
"text": "Evaluate expression allows to evaluate expression on the fly. Follow these steps to perform\nthis action −"
},
{
"code": null,
"e": 5354,
"s": 5324,
"text": "Start application in debugger"
},
{
"code": null,
"e": 5384,
"s": 5354,
"text": "Start application in debugger"
},
{
"code": null,
"e": 5422,
"s": 5384,
"text": "Navigate to Run->Evaluate expression."
},
{
"code": null,
"e": 5460,
"s": 5422,
"text": "Navigate to Run->Evaluate expression."
},
{
"code": null,
"e": 5597,
"s": 5460,
"text": "Enter expression. In the example given below, the current value of variable ‘i’ is 0;\nhence, expression ‘i > 100’ will evaluate to false"
}
] |
Find the count of even odd pairs in a given Array | 08 Apr, 2021
Given an array arr[], the task is to find the count even-odd pairs in the array.Examples:
Input: arr[] = { 1, 2, 1, 3 } Output: 2 Explanation: The 2 pairs of the form (even, odd) are {2, 1} and {2, 3}.
Input: arr[] = { 5, 4, 1, 2, 3} Output: 3
Naive Approach:
Run two nested loops to get all the possible pairs of numbers in the array.For each pair, check whether if a[i] is even and a[j] is odd.If it is, then increase the required count by one.When all the pairs have been checked, print the count in the end.
Run two nested loops to get all the possible pairs of numbers in the array.
For each pair, check whether if a[i] is even and a[j] is odd.
If it is, then increase the required count by one.
When all the pairs have been checked, print the count in the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to count the pairs in array// of the form (even, odd) #include <bits/stdc++.h>using namespace std; // Function to count the pairs in array// of the form (even, odd)int findCount(int arr[], int n){ // variable to store count of such pairs int res = 0; // Iterate through all pairs for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) // Increment count // if condition is satisfied if ((arr[i] % 2 == 0) && (arr[j] % 2 == 1)) { res++; } return res;} // Driver codeint main(){ int a[] = { 5, 4, 1, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << findCount(a, n); return 0;}
// Java program to count the pairs in array// of the form (even, odd)import java.util.*; class GFG{ // Function to count the pairs in array// of the form (even, odd)static int findCount(int arr[], int n){ // Variable to store count of such pairs int res = 0; // Iterate through all pairs for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) // Increment count // if condition is satisfied if ((arr[i] % 2 == 0) && (arr[j] % 2 == 1)) { res++; } return res;} // Driver codepublic static void main(String[] args){ int a[] = { 5, 4, 1, 2, 3 }; int n = a.length; System.out.print(findCount(a, n));}} // This code is contributed by Rohit_ranjan
# Python3 program to count the pairs# in array of the form (even, odd) # Function to count the pairs in # array of the form (even, odd)def findCount(arr, n): # Variable to store count # of such pairs res = 0 # Iterate through all pairs for i in range(0, n - 1): for j in range(i + 1, n): # Increment count # if condition is satisfied if ((arr[i] % 2 == 0) and (arr[j] % 2 == 1)): res = res + 1 return res # Driver codea = [ 5, 4, 1, 2, 3 ]n = len(a) print(findCount(a, n)) # This code is contributed by PratikBasu
// C# program to count the pairs in array// of the form (even, odd)using System; class GFG{ // Function to count the pairs in array// of the form (even, odd)static int findCount(int []arr, int n){ // Variable to store count of such pairs int res = 0; // Iterate through all pairs for(int i = 0; i < n - 1; i++) for(int j = i + 1; j < n; j++) // Increment count // if condition is satisfied if ((arr[i] % 2 == 0) && (arr[j] % 2 == 1)) { res++; } return res;} // Driver codepublic static void Main(String[] args){ int []a = { 5, 4, 1, 2, 3 }; int n = a.Length; Console.Write(findCount(a, n));}} // This code is contributed by Rohit_ranjan
<script> // Javascript program to count the pairs in array// of the form (even, odd) // Function to count the pairs in array// of the form (even, odd)function findCount(arr, n){ // variable to store count of such pairs let res = 0; // Iterate through all pairs for (let i = 0; i < n - 1; i++) for (let j = i + 1; j < n; j++) // Increment count // if condition is satisfied if ((arr[i] % 2 == 0) && (arr[j] % 2 == 1)) { res++; } return res;} // Driver codelet a = [ 5, 4, 1, 2, 3 ];let n = a.length;document.write(findCount(a, n)); </script>
3
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient Approach:
For each element starting from index 0 we will check if it’s even or not.If it’s even we will increase the count by 1.Else we will increase our final answer by count.
For each element starting from index 0 we will check if it’s even or not.
If it’s even we will increase the count by 1.
Else we will increase our final answer by count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to count the pairs in array// of the form (even, odd) #include <bits/stdc++.h>using namespace std; // Function to count the pairs in array// of the form (even, odd)int findCount(int arr[], int n){ int count = 0, ans = 0; for (int i = 0; i < n; i++) { // check if number is even or not if (arr[i] % 2 == 0) count++; else ans = ans + count; } return ans;} // Driver codeint main(){ int a[] = { 5, 4, 1, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << findCount(a, n); return 0;}
// Java program to count the pairs// in array of the form (even, odd)class GFG{ // Function to count the pairs in // array of the form (even, odd)static int findCount(int arr[], int n){ int count = 0, ans = 0; for(int i = 0; i < n; i++) { // Check if number is even // or not if (arr[i] % 2 == 0) { count++; } else { ans = ans + count; } } return ans;} // Driver codepublic static void main(String[] args){ int a[] = { 5, 4, 1, 2, 3 }; int n = a.length; System.out.print(findCount(a, n));}} // This code is contributed by amal kumar choubey
# Python3 program to count the pairs# in array of the form (even, odd) # Function to count the pairs in# array of the form (even, odd)def findCount(arr, n): count = 0 ans = 0 for i in range(0, n): # Check if number is even or not if (arr[i] % 2 == 0): count = count + 1 else: ans = ans + count return ans # Driver codea = [ 5, 4, 1, 2, 3 ]n = len(a) print(findCount(a, n)) # This code is contributed by PratikBasu
// C# program to count the pairs in// array of the form (even, odd)using System; class GFG{ // Function to count the pairs in// array of the form (even, odd)static int findCount(int []arr, int n){ int count = 0, ans = 0; for(int i = 0; i < n; i++) { // Check if number is even or not if (arr[i] % 2 == 0) { count++; } else { ans = ans + count; } } return ans;} // Driver codepublic static void Main(){ int []a = { 5, 4, 1, 2, 3 }; int n = a.Length; Console.WriteLine(findCount(a, n));}} // This code is contributed by Code_Mech
<script>// Javascript program to count the pairs in array// of the form (even, odd) // Function to count the pairs in array// of the form (even, odd)function findCount(arr, n){ let count = 0, ans = 0; for (let i = 0; i < n; i++) { // check if number is even or not if (arr[i] % 2 == 0) count++; else ans = ans + count; } return ans;} // Driver codelet a = [ 5, 4, 1, 2, 3 ];let n = a.length;document.write(findCount(a, n)); // This code is contributed by subhammahato348.</script>
3
Time Complexity: O(n)
Auxiliary Space: O(1)
Rohit_ranjan
PratikBasu
Code_Mech
Amal Kumar Choubey
subhammahato348
frequency-counting
Arrays
Mathematical
School Programming
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "Given an array arr[], the task is to find the count even-odd pairs in the array.Examples: "
},
{
"code": null,
"e": 232,
"s": 119,
"text": "Input: arr[] = { 1, 2, 1, 3 } Output: 2 Explanation: The 2 pairs of the form (even, odd) are {2, 1} and {2, 3}. "
},
{
"code": null,
"e": 277,
"s": 232,
"text": "Input: arr[] = { 5, 4, 1, 2, 3} Output: 3 "
},
{
"code": null,
"e": 294,
"s": 277,
"text": "Naive Approach: "
},
{
"code": null,
"e": 546,
"s": 294,
"text": "Run two nested loops to get all the possible pairs of numbers in the array.For each pair, check whether if a[i] is even and a[j] is odd.If it is, then increase the required count by one.When all the pairs have been checked, print the count in the end."
},
{
"code": null,
"e": 622,
"s": 546,
"text": "Run two nested loops to get all the possible pairs of numbers in the array."
},
{
"code": null,
"e": 684,
"s": 622,
"text": "For each pair, check whether if a[i] is even and a[j] is odd."
},
{
"code": null,
"e": 735,
"s": 684,
"text": "If it is, then increase the required count by one."
},
{
"code": null,
"e": 801,
"s": 735,
"text": "When all the pairs have been checked, print the count in the end."
},
{
"code": null,
"e": 853,
"s": 801,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 857,
"s": 853,
"text": "C++"
},
{
"code": null,
"e": 862,
"s": 857,
"text": "Java"
},
{
"code": null,
"e": 870,
"s": 862,
"text": "Python3"
},
{
"code": null,
"e": 873,
"s": 870,
"text": "C#"
},
{
"code": null,
"e": 884,
"s": 873,
"text": "Javascript"
},
{
"code": "// C++ program to count the pairs in array// of the form (even, odd) #include <bits/stdc++.h>using namespace std; // Function to count the pairs in array// of the form (even, odd)int findCount(int arr[], int n){ // variable to store count of such pairs int res = 0; // Iterate through all pairs for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) // Increment count // if condition is satisfied if ((arr[i] % 2 == 0) && (arr[j] % 2 == 1)) { res++; } return res;} // Driver codeint main(){ int a[] = { 5, 4, 1, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << findCount(a, n); return 0;}",
"e": 1595,
"s": 884,
"text": null
},
{
"code": "// Java program to count the pairs in array// of the form (even, odd)import java.util.*; class GFG{ // Function to count the pairs in array// of the form (even, odd)static int findCount(int arr[], int n){ // Variable to store count of such pairs int res = 0; // Iterate through all pairs for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) // Increment count // if condition is satisfied if ((arr[i] % 2 == 0) && (arr[j] % 2 == 1)) { res++; } return res;} // Driver codepublic static void main(String[] args){ int a[] = { 5, 4, 1, 2, 3 }; int n = a.length; System.out.print(findCount(a, n));}} // This code is contributed by Rohit_ranjan",
"e": 2363,
"s": 1595,
"text": null
},
{
"code": "# Python3 program to count the pairs# in array of the form (even, odd) # Function to count the pairs in # array of the form (even, odd)def findCount(arr, n): # Variable to store count # of such pairs res = 0 # Iterate through all pairs for i in range(0, n - 1): for j in range(i + 1, n): # Increment count # if condition is satisfied if ((arr[i] % 2 == 0) and (arr[j] % 2 == 1)): res = res + 1 return res # Driver codea = [ 5, 4, 1, 2, 3 ]n = len(a) print(findCount(a, n)) # This code is contributed by PratikBasu",
"e": 2969,
"s": 2363,
"text": null
},
{
"code": "// C# program to count the pairs in array// of the form (even, odd)using System; class GFG{ // Function to count the pairs in array// of the form (even, odd)static int findCount(int []arr, int n){ // Variable to store count of such pairs int res = 0; // Iterate through all pairs for(int i = 0; i < n - 1; i++) for(int j = i + 1; j < n; j++) // Increment count // if condition is satisfied if ((arr[i] % 2 == 0) && (arr[j] % 2 == 1)) { res++; } return res;} // Driver codepublic static void Main(String[] args){ int []a = { 5, 4, 1, 2, 3 }; int n = a.Length; Console.Write(findCount(a, n));}} // This code is contributed by Rohit_ranjan",
"e": 3733,
"s": 2969,
"text": null
},
{
"code": "<script> // Javascript program to count the pairs in array// of the form (even, odd) // Function to count the pairs in array// of the form (even, odd)function findCount(arr, n){ // variable to store count of such pairs let res = 0; // Iterate through all pairs for (let i = 0; i < n - 1; i++) for (let j = i + 1; j < n; j++) // Increment count // if condition is satisfied if ((arr[i] % 2 == 0) && (arr[j] % 2 == 1)) { res++; } return res;} // Driver codelet a = [ 5, 4, 1, 2, 3 ];let n = a.length;document.write(findCount(a, n)); </script>",
"e": 4373,
"s": 3733,
"text": null
},
{
"code": null,
"e": 4375,
"s": 4373,
"text": "3"
},
{
"code": null,
"e": 4400,
"s": 4377,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 4422,
"s": 4400,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4444,
"s": 4422,
"text": "Efficient Approach: "
},
{
"code": null,
"e": 4611,
"s": 4444,
"text": "For each element starting from index 0 we will check if it’s even or not.If it’s even we will increase the count by 1.Else we will increase our final answer by count."
},
{
"code": null,
"e": 4685,
"s": 4611,
"text": "For each element starting from index 0 we will check if it’s even or not."
},
{
"code": null,
"e": 4731,
"s": 4685,
"text": "If it’s even we will increase the count by 1."
},
{
"code": null,
"e": 4780,
"s": 4731,
"text": "Else we will increase our final answer by count."
},
{
"code": null,
"e": 4832,
"s": 4780,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 4836,
"s": 4832,
"text": "C++"
},
{
"code": null,
"e": 4841,
"s": 4836,
"text": "Java"
},
{
"code": null,
"e": 4849,
"s": 4841,
"text": "Python3"
},
{
"code": null,
"e": 4852,
"s": 4849,
"text": "C#"
},
{
"code": null,
"e": 4863,
"s": 4852,
"text": "Javascript"
},
{
"code": "// C++ program to count the pairs in array// of the form (even, odd) #include <bits/stdc++.h>using namespace std; // Function to count the pairs in array// of the form (even, odd)int findCount(int arr[], int n){ int count = 0, ans = 0; for (int i = 0; i < n; i++) { // check if number is even or not if (arr[i] % 2 == 0) count++; else ans = ans + count; } return ans;} // Driver codeint main(){ int a[] = { 5, 4, 1, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << findCount(a, n); return 0;}",
"e": 5425,
"s": 4863,
"text": null
},
{
"code": "// Java program to count the pairs// in array of the form (even, odd)class GFG{ // Function to count the pairs in // array of the form (even, odd)static int findCount(int arr[], int n){ int count = 0, ans = 0; for(int i = 0; i < n; i++) { // Check if number is even // or not if (arr[i] % 2 == 0) { count++; } else { ans = ans + count; } } return ans;} // Driver codepublic static void main(String[] args){ int a[] = { 5, 4, 1, 2, 3 }; int n = a.length; System.out.print(findCount(a, n));}} // This code is contributed by amal kumar choubey",
"e": 6072,
"s": 5425,
"text": null
},
{
"code": "# Python3 program to count the pairs# in array of the form (even, odd) # Function to count the pairs in# array of the form (even, odd)def findCount(arr, n): count = 0 ans = 0 for i in range(0, n): # Check if number is even or not if (arr[i] % 2 == 0): count = count + 1 else: ans = ans + count return ans # Driver codea = [ 5, 4, 1, 2, 3 ]n = len(a) print(findCount(a, n)) # This code is contributed by PratikBasu",
"e": 6561,
"s": 6072,
"text": null
},
{
"code": "// C# program to count the pairs in// array of the form (even, odd)using System; class GFG{ // Function to count the pairs in// array of the form (even, odd)static int findCount(int []arr, int n){ int count = 0, ans = 0; for(int i = 0; i < n; i++) { // Check if number is even or not if (arr[i] % 2 == 0) { count++; } else { ans = ans + count; } } return ans;} // Driver codepublic static void Main(){ int []a = { 5, 4, 1, 2, 3 }; int n = a.Length; Console.WriteLine(findCount(a, n));}} // This code is contributed by Code_Mech",
"e": 7183,
"s": 6561,
"text": null
},
{
"code": "<script>// Javascript program to count the pairs in array// of the form (even, odd) // Function to count the pairs in array// of the form (even, odd)function findCount(arr, n){ let count = 0, ans = 0; for (let i = 0; i < n; i++) { // check if number is even or not if (arr[i] % 2 == 0) count++; else ans = ans + count; } return ans;} // Driver codelet a = [ 5, 4, 1, 2, 3 ];let n = a.length;document.write(findCount(a, n)); // This code is contributed by subhammahato348.</script>",
"e": 7720,
"s": 7183,
"text": null
},
{
"code": null,
"e": 7722,
"s": 7720,
"text": "3"
},
{
"code": null,
"e": 7746,
"s": 7724,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 7768,
"s": 7746,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7781,
"s": 7768,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 7792,
"s": 7781,
"text": "PratikBasu"
},
{
"code": null,
"e": 7802,
"s": 7792,
"text": "Code_Mech"
},
{
"code": null,
"e": 7821,
"s": 7802,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 7837,
"s": 7821,
"text": "subhammahato348"
},
{
"code": null,
"e": 7856,
"s": 7837,
"text": "frequency-counting"
},
{
"code": null,
"e": 7863,
"s": 7856,
"text": "Arrays"
},
{
"code": null,
"e": 7876,
"s": 7863,
"text": "Mathematical"
},
{
"code": null,
"e": 7895,
"s": 7876,
"text": "School Programming"
},
{
"code": null,
"e": 7902,
"s": 7895,
"text": "Arrays"
},
{
"code": null,
"e": 7915,
"s": 7902,
"text": "Mathematical"
},
{
"code": null,
"e": 8013,
"s": 7915,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8081,
"s": 8013,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 8125,
"s": 8081,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 8157,
"s": 8125,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 8205,
"s": 8157,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 8219,
"s": 8205,
"text": "Linear Search"
},
{
"code": null,
"e": 8249,
"s": 8219,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 8292,
"s": 8249,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8352,
"s": 8292,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8367,
"s": 8352,
"text": "C++ Data Types"
}
] |
Program for Octal to Decimal Conversion | 05 Apr, 2022
Given an octal number as input, we need to write a program to convert the given octal number into equivalent decimal number.
Examples:
Input : 67
Output: 55
Input : 512
Output: 330
Input : 123
Output: 83
The idea is to extract the digits of a given octal number starting from the rightmost digit and keep a variable dec_value. At the time of extracting digits from the octal number, multiply the digit with the proper base (Power of 8) and add it to the variable dec_value. In the end, the variable dec_value will store the required decimal number.
For Example:
If the octal number is 67.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
dec_value = 6*(8^1) + 7*(8^0) = 55
The below diagram explains how to convert an octal number (123) to an equivalent decimal value:
Below is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to convert octal to decimal#include <iostream>using namespace std; // Function to convert octal to decimalint octalToDecimal(int n){ int num = n; int dec_value = 0; // Initializing base value to 1, i.e 8^0 int base = 1; int temp = num; while (temp) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit with appropriate // base value and adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value;} // Driver program to test above functionint main(){ int num = 67; cout << octalToDecimal(num) << endl;}
// Java program to convert octal to decimalimport java.io.*; class GFG { // Function to convert octal to decimal static int octalToDecimal(int n) { int num = n; int dec_value = 0; // Initializing base value to 1, i.e 8^0 int base = 1; int temp = num; while (temp > 0) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit with appropriate // base value and adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value; } // driver program public static void main(String[] args) { int num = 67; System.out.println(octalToDecimal(num)); }} // This code is contributed// by Pramod Kumar
# Python3 program to convert# octal to decimal # Function to convert# octal to decimal def octalToDecimal(n): num = n dec_value = 0 # Initializing base value # to 1, i.e 8^0 base = 1 temp = num while (temp): # Extracting last digit last_digit = temp % 10 temp = int(temp / 10) # Multiplying last digit # with appropriate base # value and adding it # to dec_value dec_value += last_digit * base base = base * 8 return dec_value # Driver Codenum = 67print(octalToDecimal(num)) # This code is contributed by mits
// C# program to convert octal to// decimalusing System; class GFG { // Function to convert octal // to decimal static int octalToDecimal(int n) { int num = n; int dec_value = 0; // Initializing base value // to 1, i.e 8^0 int b_ase = 1; int temp = num; while (temp > 0) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit // with appropriate base // value and adding it to // dec_value dec_value += last_digit * b_ase; b_ase = b_ase * 8; } return dec_value; } // driver program public static void Main() { int num = 67; Console.WriteLine(octalToDecimal(num)); }} // This code is contributed by vt_m.
<?php// PHP program to convert octal to decimal // Function to convert// octal to decimalfunction octalToDecimal($n){ $num = $n; $dec_value = 0; // Initializing base value // to 1, i.e 8^0 $base = 1; $temp = $num; while ($temp) { // Extracting last digit $last_digit = $temp % 10; $temp = $temp / 10; // Multiplying last digit // with appropriate base // value and adding it // to dec_value $dec_value += $last_digit * $base; $base = $base * 8; } return $dec_value;} // Driver Code $num = 67; echo octalToDecimal($num); // This code is contributed by anuj_67?>
<script> // JavaScript program to convert octal to decimal // Function to convert octal to decimalfunction octalToDecimal(n){ let num = n; let dec_value = 0; // Initializing base value to 1, i.e 8^0 let base = 1; let temp = num; while (temp) { // Extracting last digit let last_digit = temp % 10; temp = Math.floor(temp / 10); // Multiplying last digit with appropriate // base value and adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value;} // Driver program to test above function let num = 67; document.write(octalToDecimal(num) + "<br>"); // This code is contributed by Surbhi Tyagi </script>
55
Using predefined function
C++
Java
Python3
C#
Javascript
// C++ program to convert octal to decimal#include <iostream>using namespace std;int OctToDec(string n){ return stoi(n, 0, 8);}int main(){ string n = "67"; cout << OctToDec(n); return 0;} // This code is contributed by phasing17
// Java program to convert octal to decimalimport java.io.*; class GFG { public static int OctToDec(String n) { return Integer.parseInt(n, 8); } public static void main(String[] args) { String n = "67"; System.out.println(OctToDec(n)); }}
# Python program to convert octal to decimaldef OctToDec(n): return int(n, 8); if __name__ == '__main__': n = "67"; print(OctToDec(n)); # This code is contributed by 29AjayKumar
using System; public class GFG{ public static int OctToDec(String n) { return Convert.ToInt32(n, 8); } static public void Main (){ string n = "67"; Console.WriteLine(OctToDec(n)); }} // THIS CODE IS CONTRIBUTED BY RAG2127
<script>// javascript program to convert octal to decimal function OctToDec(n) { return parseInt(n, 8); } var n = "67"; document.write(OctToDec(n));// This code contributed by Princi Singh</script>
55
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
Mithun Kumar
surbhityagi15
le0
princi singh
29AjayKumar
rag2127
phasing17
base-conversion
Computer Organization & Architecture
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cache Memory in Computer Organization
Addressing Modes
Logical and Physical Address in Operating System
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization | RISC and CISC
IEEE Standard 754 Floating Point Numbers
Difference between RAM and ROM
Introduction to memory and memory units
Analog to Digital Conversion
Difference between Half adder and full adder | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 177,
"s": 52,
"text": "Given an octal number as input, we need to write a program to convert the given octal number into equivalent decimal number."
},
{
"code": null,
"e": 187,
"s": 177,
"text": "Examples:"
},
{
"code": null,
"e": 258,
"s": 187,
"text": "Input : 67\nOutput: 55\n\nInput : 512\nOutput: 330\n\nInput : 123\nOutput: 83"
},
{
"code": null,
"e": 603,
"s": 258,
"text": "The idea is to extract the digits of a given octal number starting from the rightmost digit and keep a variable dec_value. At the time of extracting digits from the octal number, multiply the digit with the proper base (Power of 8) and add it to the variable dec_value. In the end, the variable dec_value will store the required decimal number."
},
{
"code": null,
"e": 617,
"s": 603,
"text": "For Example: "
},
{
"code": null,
"e": 645,
"s": 617,
"text": "If the octal number is 67. "
},
{
"code": null,
"e": 654,
"s": 645,
"text": "Chapters"
},
{
"code": null,
"e": 681,
"s": 654,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 731,
"s": 681,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 754,
"s": 731,
"text": "captions off, selected"
},
{
"code": null,
"e": 762,
"s": 754,
"text": "English"
},
{
"code": null,
"e": 780,
"s": 762,
"text": "default, selected"
},
{
"code": null,
"e": 804,
"s": 780,
"text": "This is a modal window."
},
{
"code": null,
"e": 873,
"s": 804,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 895,
"s": 873,
"text": "End of dialog window."
},
{
"code": null,
"e": 930,
"s": 895,
"text": "dec_value = 6*(8^1) + 7*(8^0) = 55"
},
{
"code": null,
"e": 1028,
"s": 930,
"text": "The below diagram explains how to convert an octal number (123) to an equivalent decimal value: "
},
{
"code": null,
"e": 1072,
"s": 1028,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 1076,
"s": 1072,
"text": "C++"
},
{
"code": null,
"e": 1081,
"s": 1076,
"text": "Java"
},
{
"code": null,
"e": 1089,
"s": 1081,
"text": "Python3"
},
{
"code": null,
"e": 1092,
"s": 1089,
"text": "C#"
},
{
"code": null,
"e": 1096,
"s": 1092,
"text": "PHP"
},
{
"code": null,
"e": 1107,
"s": 1096,
"text": "Javascript"
},
{
"code": "// C++ program to convert octal to decimal#include <iostream>using namespace std; // Function to convert octal to decimalint octalToDecimal(int n){ int num = n; int dec_value = 0; // Initializing base value to 1, i.e 8^0 int base = 1; int temp = num; while (temp) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit with appropriate // base value and adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value;} // Driver program to test above functionint main(){ int num = 67; cout << octalToDecimal(num) << endl;}",
"e": 1788,
"s": 1107,
"text": null
},
{
"code": "// Java program to convert octal to decimalimport java.io.*; class GFG { // Function to convert octal to decimal static int octalToDecimal(int n) { int num = n; int dec_value = 0; // Initializing base value to 1, i.e 8^0 int base = 1; int temp = num; while (temp > 0) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit with appropriate // base value and adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value; } // driver program public static void main(String[] args) { int num = 67; System.out.println(octalToDecimal(num)); }} // This code is contributed// by Pramod Kumar",
"e": 2624,
"s": 1788,
"text": null
},
{
"code": "# Python3 program to convert# octal to decimal # Function to convert# octal to decimal def octalToDecimal(n): num = n dec_value = 0 # Initializing base value # to 1, i.e 8^0 base = 1 temp = num while (temp): # Extracting last digit last_digit = temp % 10 temp = int(temp / 10) # Multiplying last digit # with appropriate base # value and adding it # to dec_value dec_value += last_digit * base base = base * 8 return dec_value # Driver Codenum = 67print(octalToDecimal(num)) # This code is contributed by mits",
"e": 3230,
"s": 2624,
"text": null
},
{
"code": "// C# program to convert octal to// decimalusing System; class GFG { // Function to convert octal // to decimal static int octalToDecimal(int n) { int num = n; int dec_value = 0; // Initializing base value // to 1, i.e 8^0 int b_ase = 1; int temp = num; while (temp > 0) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit // with appropriate base // value and adding it to // dec_value dec_value += last_digit * b_ase; b_ase = b_ase * 8; } return dec_value; } // driver program public static void Main() { int num = 67; Console.WriteLine(octalToDecimal(num)); }} // This code is contributed by vt_m.",
"e": 4089,
"s": 3230,
"text": null
},
{
"code": "<?php// PHP program to convert octal to decimal // Function to convert// octal to decimalfunction octalToDecimal($n){ $num = $n; $dec_value = 0; // Initializing base value // to 1, i.e 8^0 $base = 1; $temp = $num; while ($temp) { // Extracting last digit $last_digit = $temp % 10; $temp = $temp / 10; // Multiplying last digit // with appropriate base // value and adding it // to dec_value $dec_value += $last_digit * $base; $base = $base * 8; } return $dec_value;} // Driver Code $num = 67; echo octalToDecimal($num); // This code is contributed by anuj_67?>",
"e": 4768,
"s": 4089,
"text": null
},
{
"code": "<script> // JavaScript program to convert octal to decimal // Function to convert octal to decimalfunction octalToDecimal(n){ let num = n; let dec_value = 0; // Initializing base value to 1, i.e 8^0 let base = 1; let temp = num; while (temp) { // Extracting last digit let last_digit = temp % 10; temp = Math.floor(temp / 10); // Multiplying last digit with appropriate // base value and adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value;} // Driver program to test above function let num = 67; document.write(octalToDecimal(num) + \"<br>\"); // This code is contributed by Surbhi Tyagi </script>",
"e": 5492,
"s": 4768,
"text": null
},
{
"code": null,
"e": 5495,
"s": 5492,
"text": "55"
},
{
"code": null,
"e": 5521,
"s": 5495,
"text": "Using predefined function"
},
{
"code": null,
"e": 5525,
"s": 5521,
"text": "C++"
},
{
"code": null,
"e": 5530,
"s": 5525,
"text": "Java"
},
{
"code": null,
"e": 5538,
"s": 5530,
"text": "Python3"
},
{
"code": null,
"e": 5541,
"s": 5538,
"text": "C#"
},
{
"code": null,
"e": 5552,
"s": 5541,
"text": "Javascript"
},
{
"code": "// C++ program to convert octal to decimal#include <iostream>using namespace std;int OctToDec(string n){ return stoi(n, 0, 8);}int main(){ string n = \"67\"; cout << OctToDec(n); return 0;} // This code is contributed by phasing17",
"e": 5786,
"s": 5552,
"text": null
},
{
"code": "// Java program to convert octal to decimalimport java.io.*; class GFG { public static int OctToDec(String n) { return Integer.parseInt(n, 8); } public static void main(String[] args) { String n = \"67\"; System.out.println(OctToDec(n)); }}",
"e": 6065,
"s": 5786,
"text": null
},
{
"code": "# Python program to convert octal to decimaldef OctToDec(n): return int(n, 8); if __name__ == '__main__': n = \"67\"; print(OctToDec(n)); # This code is contributed by 29AjayKumar",
"e": 6257,
"s": 6065,
"text": null
},
{
"code": "using System; public class GFG{ public static int OctToDec(String n) { return Convert.ToInt32(n, 8); } static public void Main (){ string n = \"67\"; Console.WriteLine(OctToDec(n)); }} // THIS CODE IS CONTRIBUTED BY RAG2127",
"e": 6534,
"s": 6257,
"text": null
},
{
"code": "<script>// javascript program to convert octal to decimal function OctToDec(n) { return parseInt(n, 8); } var n = \"67\"; document.write(OctToDec(n));// This code contributed by Princi Singh</script>",
"e": 6756,
"s": 6534,
"text": null
},
{
"code": null,
"e": 6759,
"s": 6756,
"text": "55"
},
{
"code": null,
"e": 7058,
"s": 6761,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 7184,
"s": 7058,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7189,
"s": 7184,
"text": "vt_m"
},
{
"code": null,
"e": 7202,
"s": 7189,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7216,
"s": 7202,
"text": "surbhityagi15"
},
{
"code": null,
"e": 7220,
"s": 7216,
"text": "le0"
},
{
"code": null,
"e": 7233,
"s": 7220,
"text": "princi singh"
},
{
"code": null,
"e": 7245,
"s": 7233,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7253,
"s": 7245,
"text": "rag2127"
},
{
"code": null,
"e": 7263,
"s": 7253,
"text": "phasing17"
},
{
"code": null,
"e": 7279,
"s": 7263,
"text": "base-conversion"
},
{
"code": null,
"e": 7316,
"s": 7279,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 7351,
"s": 7316,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 7359,
"s": 7351,
"text": "GATE CS"
},
{
"code": null,
"e": 7457,
"s": 7359,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7495,
"s": 7457,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 7512,
"s": 7495,
"text": "Addressing Modes"
},
{
"code": null,
"e": 7561,
"s": 7512,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 7623,
"s": 7561,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 7661,
"s": 7623,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 7702,
"s": 7661,
"text": "IEEE Standard 754 Floating Point Numbers"
},
{
"code": null,
"e": 7733,
"s": 7702,
"text": "Difference between RAM and ROM"
},
{
"code": null,
"e": 7773,
"s": 7733,
"text": "Introduction to memory and memory units"
},
{
"code": null,
"e": 7802,
"s": 7773,
"text": "Analog to Digital Conversion"
}
] |
How to upload images in MySQL using PHP PDO ? | 10 Jun, 2022
In this article, we will upload images to the MySQL database using PHP PDO and display them on the webpage.
Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this tutorial, we will be using the WAMP server.
Article content:
Table StructureDatabase configuration using PDO.HTML & PHP FilesWorking ProcedureConclusion
Table Structure
Database configuration using PDO.
HTML & PHP Files
Working Procedure
Conclusion
To upload images to the MySQL database using PDO-PHP and display them on the webpage, follow the steps given below:
1. Create Database: Create a database using PHPMyAdmin, the database is named “geeksforgeeks” here. You can give any name to your database. You can also use your existing database or create a new one.
create database “geeksforgeeks”
2. Create Table: We now create a table named ‘images‘. The table contains three fields:
id – int(11) – primary key – auto increment
name – varchar(100)
image – varchar(255)
Your table structure should look like this:
create table “images”
Or copy and paste the following code into the SQL panel of your PHPMyAdmin.
CREATE TABLE `images`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`image` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
To do this from the SQL panel refer to the following screenshot:
create a table from SQL panel
3. Creating folders and files:
We will now create a folder named “uploads“. The files uploaded by the client on the server will be stored in this folder. Create index.php, database_connection.php and view.php files. Keep your main project folder (for example.. GeeksforGeeks) in the “C://xampp/htdocs/”, if you are using XAMPP or “C://wamp64/www/” folder if you are using the WAMP server respectively. The folder structure should look like this:
folder structure
Database configuration using PHP PDO:
database_connection.php: Create a “database_connection.php“ file for the database connection.
PHP
<?php $server = "localhost";$username = "root";$password = "";$dbname = "geeksforgeeks"; try { $conn = new PDO( "mysql:host=$server; dbname=$dbname", "$username", "$password" ); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );}catch(PDOException $e) { die('Unable to connect with the database');} ?>
index.php: Below is the PHP source code for uploading the images using HTML form. Let us first understand the PHP part.
In the below code, the first block verifies that the ‘submit’ button from the form has been clicked using the PHP isset() function. And the second if block verifies that the image file exists with a valid extension. $_FILES is a two-dimensional superglobal associative array of items that are being uploaded via the HTTP POST method. The move_uploaded_file() function is used to upload the pdf file to the server. We are passing 2 values, the temporary file name and the folder where the file will be stored. The files will be stored in the “GeeksForGeeks/uploads/ ” folder which we created earlier.
In the HTML <form> tag, we are using “enctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form. The multiple attributes in the input file element are used to enable selecting multiple files.
PHP
<?phpinclude "database_connection.php"; if(isset($_POST['submit'])) { // Count total files $countfiles = count($_FILES['files']['name']); // Prepared statement $query = "INSERT INTO images (name,image) VALUES(?,?)"; $statement = $conn->prepare($query); // Loop all files for($i = 0; $i < $countfiles; $i++) { // File name $filename = $_FILES['files']['name'][$i]; // Location $target_file = './uploads/'.$filename; // file extension $file_extension = pathinfo( $target_file, PATHINFO_EXTENSION); $file_extension = strtolower($file_extension); // Valid image extension $valid_extension = array("png","jpeg","jpg"); if(in_array($file_extension, $valid_extension)) { // Upload file if(move_uploaded_file( $_FILES['files']['tmp_name'][$i], $target_file) ) { // Execute query $statement->execute( array($filename,$target_file)); } } } echo "File upload successfully";}?> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Geeks for geeks Image Upload</title></head> <body> <h1>Upload Images</h1> <form method='post' action='' enctype='multipart/form-data'> <input type='file' name='files[]' multiple /> <input type='submit' value='Submit' name='submit' /> </form> <a href="view.php">|View Uploads|</a></body> </html>
view.php: Code to display the uploaded images.
PHP
<?phpinclude "database_connection.php";?> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> </head> <body> <?php $stmt = $conn->prepare('select * from images'); $stmt->execute(); $imagelist = $stmt->fetchAll(); foreach($imagelist as $image) { ?> <img src="<?=$image['image']?>" title="<?=$image['name'] ?>" width='200' height='200'> <?php } ?></body> </html>
4. Working Procedure:
1. Run the local server or any server and redirect to your index.php page.
2. Select your image file to upload and click on submit button to upload the image to the database.
3. Click on the view upload link to check the uploaded file.
5. Conclusion: You can add CSS and change HTML as per the application requirement. In the above, the working of this upload image feature in PHP is implemented.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
sanjyotpanure
PHP-function
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 161,
"s": 52,
"text": "In this article, we will upload images to the MySQL database using PHP PDO and display them on the webpage. "
},
{
"code": null,
"e": 299,
"s": 161,
"text": "Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this tutorial, we will be using the WAMP server."
},
{
"code": null,
"e": 316,
"s": 299,
"text": "Article content:"
},
{
"code": null,
"e": 408,
"s": 316,
"text": "Table StructureDatabase configuration using PDO.HTML & PHP FilesWorking ProcedureConclusion"
},
{
"code": null,
"e": 424,
"s": 408,
"text": "Table Structure"
},
{
"code": null,
"e": 458,
"s": 424,
"text": "Database configuration using PDO."
},
{
"code": null,
"e": 475,
"s": 458,
"text": "HTML & PHP Files"
},
{
"code": null,
"e": 493,
"s": 475,
"text": "Working Procedure"
},
{
"code": null,
"e": 504,
"s": 493,
"text": "Conclusion"
},
{
"code": null,
"e": 620,
"s": 504,
"text": "To upload images to the MySQL database using PDO-PHP and display them on the webpage, follow the steps given below:"
},
{
"code": null,
"e": 821,
"s": 620,
"text": "1. Create Database: Create a database using PHPMyAdmin, the database is named “geeksforgeeks” here. You can give any name to your database. You can also use your existing database or create a new one."
},
{
"code": null,
"e": 853,
"s": 821,
"text": "create database “geeksforgeeks”"
},
{
"code": null,
"e": 941,
"s": 853,
"text": "2. Create Table: We now create a table named ‘images‘. The table contains three fields:"
},
{
"code": null,
"e": 985,
"s": 941,
"text": "id – int(11) – primary key – auto increment"
},
{
"code": null,
"e": 1005,
"s": 985,
"text": "name – varchar(100)"
},
{
"code": null,
"e": 1026,
"s": 1005,
"text": "image – varchar(255)"
},
{
"code": null,
"e": 1070,
"s": 1026,
"text": "Your table structure should look like this:"
},
{
"code": null,
"e": 1092,
"s": 1070,
"text": "create table “images”"
},
{
"code": null,
"e": 1168,
"s": 1092,
"text": "Or copy and paste the following code into the SQL panel of your PHPMyAdmin."
},
{
"code": null,
"e": 1368,
"s": 1168,
"text": "CREATE TABLE `images`(\n `id` int(11) NOT NULL AUTO_INCREMENT, \n `name` varchar(100) NOT NULL,\n `image` varchar(255) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;"
},
{
"code": null,
"e": 1433,
"s": 1368,
"text": "To do this from the SQL panel refer to the following screenshot:"
},
{
"code": null,
"e": 1463,
"s": 1433,
"text": "create a table from SQL panel"
},
{
"code": null,
"e": 1494,
"s": 1463,
"text": "3. Creating folders and files:"
},
{
"code": null,
"e": 1909,
"s": 1494,
"text": "We will now create a folder named “uploads“. The files uploaded by the client on the server will be stored in this folder. Create index.php, database_connection.php and view.php files. Keep your main project folder (for example.. GeeksforGeeks) in the “C://xampp/htdocs/”, if you are using XAMPP or “C://wamp64/www/” folder if you are using the WAMP server respectively. The folder structure should look like this:"
},
{
"code": null,
"e": 1926,
"s": 1909,
"text": "folder structure"
},
{
"code": null,
"e": 1964,
"s": 1926,
"text": "Database configuration using PHP PDO:"
},
{
"code": null,
"e": 2058,
"s": 1964,
"text": "database_connection.php: Create a “database_connection.php“ file for the database connection."
},
{
"code": null,
"e": 2062,
"s": 2058,
"text": "PHP"
},
{
"code": "<?php $server = \"localhost\";$username = \"root\";$password = \"\";$dbname = \"geeksforgeeks\"; try { $conn = new PDO( \"mysql:host=$server; dbname=$dbname\", \"$username\", \"$password\" ); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );}catch(PDOException $e) { die('Unable to connect with the database');} ?>",
"e": 2428,
"s": 2062,
"text": null
},
{
"code": null,
"e": 2548,
"s": 2428,
"text": "index.php: Below is the PHP source code for uploading the images using HTML form. Let us first understand the PHP part."
},
{
"code": null,
"e": 3148,
"s": 2548,
"text": "In the below code, the first block verifies that the ‘submit’ button from the form has been clicked using the PHP isset() function. And the second if block verifies that the image file exists with a valid extension. $_FILES is a two-dimensional superglobal associative array of items that are being uploaded via the HTTP POST method. The move_uploaded_file() function is used to upload the pdf file to the server. We are passing 2 values, the temporary file name and the folder where the file will be stored. The files will be stored in the “GeeksForGeeks/uploads/ ” folder which we created earlier."
},
{
"code": null,
"e": 3547,
"s": 3148,
"text": "In the HTML <form> tag, we are using “enctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form. The multiple attributes in the input file element are used to enable selecting multiple files."
},
{
"code": null,
"e": 3551,
"s": 3547,
"text": "PHP"
},
{
"code": "<?phpinclude \"database_connection.php\"; if(isset($_POST['submit'])) { // Count total files $countfiles = count($_FILES['files']['name']); // Prepared statement $query = \"INSERT INTO images (name,image) VALUES(?,?)\"; $statement = $conn->prepare($query); // Loop all files for($i = 0; $i < $countfiles; $i++) { // File name $filename = $_FILES['files']['name'][$i]; // Location $target_file = './uploads/'.$filename; // file extension $file_extension = pathinfo( $target_file, PATHINFO_EXTENSION); $file_extension = strtolower($file_extension); // Valid image extension $valid_extension = array(\"png\",\"jpeg\",\"jpg\"); if(in_array($file_extension, $valid_extension)) { // Upload file if(move_uploaded_file( $_FILES['files']['tmp_name'][$i], $target_file) ) { // Execute query $statement->execute( array($filename,$target_file)); } } } echo \"File upload successfully\";}?> <!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Geeks for geeks Image Upload</title></head> <body> <h1>Upload Images</h1> <form method='post' action='' enctype='multipart/form-data'> <input type='file' name='files[]' multiple /> <input type='submit' value='Submit' name='submit' /> </form> <a href=\"view.php\">|View Uploads|</a></body> </html>",
"e": 5200,
"s": 3551,
"text": null
},
{
"code": null,
"e": 5247,
"s": 5200,
"text": "view.php: Code to display the uploaded images."
},
{
"code": null,
"e": 5251,
"s": 5247,
"text": "PHP"
},
{
"code": "<?phpinclude \"database_connection.php\";?> <!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> </head> <body> <?php $stmt = $conn->prepare('select * from images'); $stmt->execute(); $imagelist = $stmt->fetchAll(); foreach($imagelist as $image) { ?> <img src=\"<?=$image['image']?>\" title=\"<?=$image['name'] ?>\" width='200' height='200'> <?php } ?></body> </html>",
"e": 5764,
"s": 5251,
"text": null
},
{
"code": null,
"e": 5786,
"s": 5764,
"text": "4. Working Procedure:"
},
{
"code": null,
"e": 5861,
"s": 5786,
"text": "1. Run the local server or any server and redirect to your index.php page."
},
{
"code": null,
"e": 5963,
"s": 5863,
"text": "2. Select your image file to upload and click on submit button to upload the image to the database."
},
{
"code": null,
"e": 6026,
"s": 5965,
"text": "3. Click on the view upload link to check the uploaded file."
},
{
"code": null,
"e": 6189,
"s": 6028,
"text": "5. Conclusion: You can add CSS and change HTML as per the application requirement. In the above, the working of this upload image feature in PHP is implemented."
},
{
"code": null,
"e": 6360,
"s": 6191,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 6374,
"s": 6360,
"text": "sanjyotpanure"
},
{
"code": null,
"e": 6387,
"s": 6374,
"text": "PHP-function"
},
{
"code": null,
"e": 6401,
"s": 6387,
"text": "PHP-Questions"
},
{
"code": null,
"e": 6405,
"s": 6401,
"text": "PHP"
},
{
"code": null,
"e": 6422,
"s": 6405,
"text": "Web Technologies"
},
{
"code": null,
"e": 6426,
"s": 6422,
"text": "PHP"
}
] |
Python program to convert time from 12 hour to 24 hour format | Given a PC's time and it converted to 24 hour format. Here we are applying string slicing.
Here we follow the rules if time is PM then add 12 with hour part and if time is AM then don't add.
Input: 12:20:20 PM
Output: 24:20:20
Step 1: Input current datetime.
Step 2: Extract only time from datetime format.
Step 3: Using string slicing check last two words PM or AM.
Step 4: if last two word is PM then add 12 and if word are AM then don't add it.
import datetime
def timeconvert(str1):
if str1[-2:] == "AM" and str1[:2] == "12":
return "00" + str1[2:-2]
elif str1[-2:] == "AM":
return str1[:-2]
elif str1[-2:] == "PM" and str1[:2] == "12":
return str1[:-2]
else:
return str(int(str1[:2]) + 12) + str1[2:8]
dt=datetime.datetime.now()
print("Conversion Of Time ::",timeconvert(dt.strftime("%H:%M:%S")))
Conversion Of Time :: 24:04:53 | [
{
"code": null,
"e": 1278,
"s": 1187,
"text": "Given a PC's time and it converted to 24 hour format. Here we are applying string slicing."
},
{
"code": null,
"e": 1378,
"s": 1278,
"text": "Here we follow the rules if time is PM then add 12 with hour part and if time is AM then don't add."
},
{
"code": null,
"e": 1414,
"s": 1378,
"text": "Input: 12:20:20 PM\nOutput: 24:20:20"
},
{
"code": null,
"e": 1635,
"s": 1414,
"text": "Step 1: Input current datetime.\nStep 2: Extract only time from datetime format.\nStep 3: Using string slicing check last two words PM or AM.\nStep 4: if last two word is PM then add 12 and if word are AM then don't add it."
},
{
"code": null,
"e": 2052,
"s": 1635,
"text": "import datetime\n def timeconvert(str1):\n if str1[-2:] == \"AM\" and str1[:2] == \"12\":\n return \"00\" + str1[2:-2]\n elif str1[-2:] == \"AM\":\n return str1[:-2]\n elif str1[-2:] == \"PM\" and str1[:2] == \"12\":\n return str1[:-2]\n else:\n return str(int(str1[:2]) + 12) + str1[2:8]\n dt=datetime.datetime.now()\nprint(\"Conversion Of Time ::\",timeconvert(dt.strftime(\"%H:%M:%S\")))"
},
{
"code": null,
"e": 2083,
"s": 2052,
"text": "Conversion Of Time :: 24:04:53"
}
] |
Javascript | Window confirm() Method | 01 Jun, 2022
The confirm() method is used to display a modal dialog with an optional message and two buttons, OK and Cancel. It returns true if the user clicks “OK”, and false otherwise. It prevents the user from accessing other parts of the page until the box is closed.
Syntax:
confirm(message)
message is the optional string to be displayed in the dialog. It returns a boolean value indicating whether OK or Cancel was selected (true means OK and false means that the user clicked cancel).
Example-1:
HTML
<!DOCTYPE html><html> <head> <title> Window confirm() Method </title></head> <body style="text-align: center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> Window confirm() Method </h2> <p>Click the button to display a confirm box.</p> <button onclick="geek()">Click me!</button> <script> function geek() { confirm("Press OK to close this option"); } </script></body> </html>
Output: Before clicking the button:
After clicking the button:
Example-2:
HTML
<!DOCTYPE html><html> <head> <title> Window confirm() Method </title></head> <body style="text-align: center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> Window confirm() Method </h2> <button onclick="geek()">Click me!</button> <p id="g"></p> <script> function geek() { var doc; var result = confirm("Press a button!"); if (result == true) { doc = "OK was pressed."; } else { doc = "Cancel was pressed."; } document.getElementById("g").innerHTML = doc; } </script></body> </html>
Output: Before clicking the button:
After clicking the button:
Supported Browsers: The browser supported by window confirm() method are listed below:
Google Chrome 1 and above
Edge 12 and above
Internet Explorer 4 and above
Firefox 1 and above
Opera 3 and above
Safari 1 and above
kumargaurav97520
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 288,
"s": 28,
"text": "The confirm() method is used to display a modal dialog with an optional message and two buttons, OK and Cancel. It returns true if the user clicks “OK”, and false otherwise. It prevents the user from accessing other parts of the page until the box is closed. "
},
{
"code": null,
"e": 296,
"s": 288,
"text": "Syntax:"
},
{
"code": null,
"e": 313,
"s": 296,
"text": "confirm(message)"
},
{
"code": null,
"e": 510,
"s": 313,
"text": "message is the optional string to be displayed in the dialog. It returns a boolean value indicating whether OK or Cancel was selected (true means OK and false means that the user clicked cancel). "
},
{
"code": null,
"e": 522,
"s": 510,
"text": "Example-1: "
},
{
"code": null,
"e": 527,
"s": 522,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Window confirm() Method </title></head> <body style=\"text-align: center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> Window confirm() Method </h2> <p>Click the button to display a confirm box.</p> <button onclick=\"geek()\">Click me!</button> <script> function geek() { confirm(\"Press OK to close this option\"); } </script></body> </html>",
"e": 1004,
"s": 527,
"text": null
},
{
"code": null,
"e": 1040,
"s": 1004,
"text": "Output: Before clicking the button:"
},
{
"code": null,
"e": 1070,
"s": 1043,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1085,
"s": 1073,
"text": "Example-2: "
},
{
"code": null,
"e": 1090,
"s": 1085,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Window confirm() Method </title></head> <body style=\"text-align: center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> Window confirm() Method </h2> <button onclick=\"geek()\">Click me!</button> <p id=\"g\"></p> <script> function geek() { var doc; var result = confirm(\"Press a button!\"); if (result == true) { doc = \"OK was pressed.\"; } else { doc = \"Cancel was pressed.\"; } document.getElementById(\"g\").innerHTML = doc; } </script></body> </html>",
"e": 1759,
"s": 1090,
"text": null
},
{
"code": null,
"e": 1795,
"s": 1759,
"text": "Output: Before clicking the button:"
},
{
"code": null,
"e": 1825,
"s": 1798,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1915,
"s": 1828,
"text": "Supported Browsers: The browser supported by window confirm() method are listed below:"
},
{
"code": null,
"e": 1941,
"s": 1915,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 1959,
"s": 1941,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 1989,
"s": 1959,
"text": "Internet Explorer 4 and above"
},
{
"code": null,
"e": 2009,
"s": 1989,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 2027,
"s": 2009,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 2046,
"s": 2027,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 2063,
"s": 2046,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 2084,
"s": 2063,
"text": "javascript-functions"
},
{
"code": null,
"e": 2095,
"s": 2084,
"text": "JavaScript"
},
{
"code": null,
"e": 2112,
"s": 2095,
"text": "Web Technologies"
},
{
"code": null,
"e": 2210,
"s": 2112,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2271,
"s": 2210,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2343,
"s": 2271,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2383,
"s": 2343,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2435,
"s": 2383,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2476,
"s": 2435,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2538,
"s": 2476,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2571,
"s": 2538,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2632,
"s": 2571,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2682,
"s": 2632,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to create a line chart with mean and standard deviation using ggplot2 in R? | Sometimes we have mean and standard deviation given for groups or factors, these are generally obtained from previous research studies and is referred to as the secondary data. In this case. the line chart with mean and standard deviation using ggplot2 can be created by defining the minimum and maximum inside geom_error function of ggplot2 package, where the difference between mean and standard deviation defines the standard deviation if the minimum is set as mean minus one standard deviation and the maximum is set as mean plus one standard deviation.
Consider the below data frame −
Live Demo
Group<−c("G1","G2","G3","G4")
Mean<−c(25,27,23,26)
SD<−c(3.24,2.25,3.6,4.1)
df<−data.frame(Group,Mean,SD)
df
Group Mean SD
1 G1 25 3.24
2 G2 27 2.25
3 G3 23 3.60
4 G4 26 4.10
Loading ggplot2 package and creating the plot with mean and standard deviation −
library(ggplot2)
ggplot(df,aes(Group,Mean))+geom_errorbar(aes(ymin=Mean-SD,ymax=Mean+SD),width=0.2)+geom_line(group=1)+geom_point() | [
{
"code": null,
"e": 1745,
"s": 1187,
"text": "Sometimes we have mean and standard deviation given for groups or factors, these are generally obtained from previous research studies and is referred to as the secondary data. In this case. the line chart with mean and standard deviation using ggplot2 can be created by defining the minimum and maximum inside geom_error function of ggplot2 package, where the difference between mean and standard deviation defines the standard deviation if the minimum is set as mean minus one standard deviation and the maximum is set as mean plus one standard deviation."
},
{
"code": null,
"e": 1777,
"s": 1745,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1788,
"s": 1777,
"text": " Live Demo"
},
{
"code": null,
"e": 1897,
"s": 1788,
"text": "Group<−c(\"G1\",\"G2\",\"G3\",\"G4\")\nMean<−c(25,27,23,26)\nSD<−c(3.24,2.25,3.6,4.1)\ndf<−data.frame(Group,Mean,SD)\ndf"
},
{
"code": null,
"e": 1963,
"s": 1897,
"text": "Group Mean SD\n1 G1 25 3.24\n2 G2 27 2.25\n3 G3 23 3.60\n4 G4 26 4.10"
},
{
"code": null,
"e": 2044,
"s": 1963,
"text": "Loading ggplot2 package and creating the plot with mean and standard deviation −"
},
{
"code": null,
"e": 2176,
"s": 2044,
"text": "library(ggplot2)\nggplot(df,aes(Group,Mean))+geom_errorbar(aes(ymin=Mean-SD,ymax=Mean+SD),width=0.2)+geom_line(group=1)+geom_point()"
}
] |
PLSQL | REMAINDER Function | 18 Oct, 2019
The REMAINDER function is an inbuilt function in PLSQL which is used to return the remainder of a divided by b.
Syntax:
REMAINDER(a, b)
Parameters Used:This function accepts two parameters a and b which is used in calculating the remainder when a is divided by b.
Return Value:This function returns a numeric value when the input number a is divided by b.
Supported Versions of Oracle/PLSQL is given below:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Let’s see some examples which illustrate the REMAINDER function:
Example-1:
DECLARE
Test_Number number1 := 15;
Test_Number number2 := 5;
BEGIN
dbms_output.put_line(REMAINDER(Test_Number number1,
Test_Number number2));
END;
Output:
0
In the above example, when 15 is divided by 5 then it returns a remainder of 0.
Example-2:
DECLARE
Test_Number number1 := 11.6;
Test_Number number2 := 2;
BEGIN
dbms_output.put_line(REMAINDER(Test_Number number1,
Test_Number number2));
END;
Output:
-0.4
In the above example, when 11.6 is divided by 2 then it returns a remainder of -0.4
Example-3:
DECLARE
Test_Number number1 := -15;
Test_Number number2 := 4;
BEGIN
dbms_output.put_line(REMAINDER(Test_Number number1,
Test_Number number2));
END;
Output:
1
In the above example, when -15 is divided by 4 then it returns a remainder of 1.
Advantage:This function is used to find out the remainder when a is divided by b.
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": "\n18 Oct, 2019"
},
{
"code": null,
"e": 140,
"s": 28,
"text": "The REMAINDER function is an inbuilt function in PLSQL which is used to return the remainder of a divided by b."
},
{
"code": null,
"e": 148,
"s": 140,
"text": "Syntax:"
},
{
"code": null,
"e": 164,
"s": 148,
"text": "REMAINDER(a, b)"
},
{
"code": null,
"e": 292,
"s": 164,
"text": "Parameters Used:This function accepts two parameters a and b which is used in calculating the remainder when a is divided by b."
},
{
"code": null,
"e": 384,
"s": 292,
"text": "Return Value:This function returns a numeric value when the input number a is divided by b."
},
{
"code": null,
"e": 435,
"s": 384,
"text": "Supported Versions of Oracle/PLSQL is given below:"
},
{
"code": null,
"e": 484,
"s": 435,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 495,
"s": 484,
"text": "Oracle 12c"
},
{
"code": null,
"e": 506,
"s": 495,
"text": "Oracle 11g"
},
{
"code": null,
"e": 517,
"s": 506,
"text": "Oracle 10g"
},
{
"code": null,
"e": 527,
"s": 517,
"text": "Oracle 9i"
},
{
"code": null,
"e": 537,
"s": 527,
"text": "Oracle 8i"
},
{
"code": null,
"e": 602,
"s": 537,
"text": "Let’s see some examples which illustrate the REMAINDER function:"
},
{
"code": null,
"e": 613,
"s": 602,
"text": "Example-1:"
},
{
"code": null,
"e": 816,
"s": 613,
"text": "DECLARE \n Test_Number number1 := 15;\n Test_Number number2 := 5;\n \nBEGIN \n dbms_output.put_line(REMAINDER(Test_Number number1, \n Test_Number number2)); \n \nEND; "
},
{
"code": null,
"e": 824,
"s": 816,
"text": "Output:"
},
{
"code": null,
"e": 826,
"s": 824,
"text": "0"
},
{
"code": null,
"e": 906,
"s": 826,
"text": "In the above example, when 15 is divided by 5 then it returns a remainder of 0."
},
{
"code": null,
"e": 917,
"s": 906,
"text": "Example-2:"
},
{
"code": null,
"e": 1122,
"s": 917,
"text": "DECLARE \n Test_Number number1 := 11.6;\n Test_Number number2 := 2;\n \nBEGIN \n dbms_output.put_line(REMAINDER(Test_Number number1, \n Test_Number number2)); \n \nEND; "
},
{
"code": null,
"e": 1130,
"s": 1122,
"text": "Output:"
},
{
"code": null,
"e": 1135,
"s": 1130,
"text": "-0.4"
},
{
"code": null,
"e": 1219,
"s": 1135,
"text": "In the above example, when 11.6 is divided by 2 then it returns a remainder of -0.4"
},
{
"code": null,
"e": 1230,
"s": 1219,
"text": "Example-3:"
},
{
"code": null,
"e": 1434,
"s": 1230,
"text": "DECLARE \n Test_Number number1 := -15;\n Test_Number number2 := 4;\n \nBEGIN \n dbms_output.put_line(REMAINDER(Test_Number number1, \n Test_Number number2)); \n \nEND; "
},
{
"code": null,
"e": 1442,
"s": 1434,
"text": "Output:"
},
{
"code": null,
"e": 1444,
"s": 1442,
"text": "1"
},
{
"code": null,
"e": 1525,
"s": 1444,
"text": "In the above example, when -15 is divided by 4 then it returns a remainder of 1."
},
{
"code": null,
"e": 1607,
"s": 1525,
"text": "Advantage:This function is used to find out the remainder when a is divided by b."
},
{
"code": null,
"e": 1618,
"s": 1607,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 1622,
"s": 1618,
"text": "SQL"
},
{
"code": null,
"e": 1626,
"s": 1622,
"text": "SQL"
}
] |
Prefix Sum Array – Implementation and Applications in Competitive Programming | 02 Jul, 2022
Given an array arr[] of size n, its prefix sum array is another array prefixSum[] of the same size, such that the value of prefixSum[i] is arr[0] + arr[1] + arr[2] ... arr[i].
Examples :
Input : arr[] = {10, 20, 10, 5, 15}
Output : prefixSum[] = {10, 30, 40, 45, 60}
Explanation : While traversing the array, update
the element by adding it with its previous element.
prefixSum[0] = 10,
prefixSum[1] = prefixSum[0] + arr[1] = 30,
prefixSum[2] = prefixSum[1] + arr[2] = 40 and so on.
To fill the prefix sum array, we run through index 1 to last and keep on adding the present element with the previous value in the prefix sum array.Below is the implementation :
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for Implementing prefix sum array#include <bits/stdc++.h>using namespace std; // Fills prefix sum arrayvoid fillPrefixSum(int arr[], int n, int prefixSum[]){ prefixSum[0] = arr[0]; // Adding present element with previous element for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // Driver Codeint main(){ int arr[] = { 10, 4, 16, 20 }; int n = sizeof(arr) / sizeof(arr[0]); int prefixSum[n]; fillPrefixSum(arr, n, prefixSum); for (int i = 0; i < n; i++) cout << prefixSum[i] << " ";} // This code is contributed by Aditya Kumar (adityakumar129)
// C program for Implementing prefix sum array#include <stdio.h> // Fills prefix sum arrayvoid fillPrefixSum(int arr[], int n, int prefixSum[]){ prefixSum[0] = arr[0]; // Adding present element with previous element for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // Driver Codeint main(){ int arr[] = { 10, 4, 16, 20 }; int n = sizeof(arr) / sizeof(arr[0]); int prefixSum[n]; fillPrefixSum(arr, n, prefixSum); for (int i = 0; i < n; i++) cout << prefixSum[i] << " ";} // This code is contributed by Aditya Kumar (adityakumar129)
// Java Program for Implementing prefix sum arrayclassclass Prefix { // Fills prefix sum array static void fillPrefixSum(int arr[], int n, int prefixSum[]) { prefixSum[0] = arr[0]; // Adding present element with previous element for (int i = 1; i < n; ++i) prefixSum[i] = prefixSum[i - 1] + arr[i]; } // Driver code public static void main(String[] args) { int arr[] = { 10, 4, 16, 20 }; int n = arr.length; int prefixSum[] = new int[n]; fillPrefixSum(arr, n, prefixSum); for (int i = 0; i < n; i++) System.out.print(prefixSum[i] + " "); System.out.println(""); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python Program for Implementing # prefix sum array # Fills prefix sum arraydef fillPrefixSum(arr, n, prefixSum): prefixSum[0] = arr[0] # Adding present element # with previous element for i in range(1, n): prefixSum[i] = prefixSum[i - 1] + arr[i] # Driver codearr =[10, 4, 16, 20 ]n = len(arr) prefixSum = [0 for i in range(n + 1)] fillPrefixSum(arr, n, prefixSum) for i in range(n): print(prefixSum[i], " ", end ="") # This code is contributed# by Anant Agarwal.
// C# Program for Implementing// prefix sum arrayclassusing System; class GFG { // Fills prefix sum array static void fillPrefixSum(int[] arr, int n, int[] prefixSum) { prefixSum[0] = arr[0]; // Adding present element // with previous element for (int i = 1; i < n; ++i) prefixSum[i] = prefixSum[i - 1] + arr[i]; } // Driver code public static void Main() { int[] arr = { 10, 4, 16, 20 }; int n = arr.Length; int[] prefixSum = new int[n]; fillPrefixSum(arr, n, prefixSum); for (int i = 0; i < n; i++) Console.Write(prefixSum[i] + " "); Console.Write(""); }} // This Code is Contributed by nitin mittal
<?php// PHP program for // Implementing prefix // sum array // Fills prefix sum arrayfunction fillPrefixSum($arr, $n){ $prefixSum = array(); $prefixSum[0] = $arr[0]; // Adding present element // with previous element for ($i = 1; $i < $n; $i++) $prefixSum[$i] = $prefixSum[$i - 1] + $arr[$i]; for ($i = 0; $i < $n; $i++) echo $prefixSum[$i] . " ";} // Driver Code$arr = array(10, 4, 16, 20);$n = count($arr); fillPrefixSum($arr, $n); // This code is contributed// by Sam007?>
<script> // JavaScript Program for Implementing // prefix sum arrayclass // Fills prefix sum array function fillPrefixSum(arr, n, prefixSum) { prefixSum[0] = arr[0]; // Adding present element // with previous element for (let i = 1; i < n; ++i) prefixSum[i] = prefixSum[i - 1] + arr[i]; } let arr = [ 10, 4, 16, 20 ]; let n = arr.length; let prefixSum = new Array(n); fillPrefixSum(arr, n, prefixSum); for (let i = 0; i < n; i++) document.write(prefixSum[i] + " "); document.write(""); </script>
Output:
10 14 30 50
Given an array arr[] of size n. Given Q queries and in each query given L and R, print sum of array elements from index L to R.
C++14
Java
Python3
C#
C++14
#include <iostream>using namespace std;const int N = 1e5+10;int a[N];int pf[N]; int main() {int n;cin >> n;for(int i=1; i<=n; i++){ cin >> a[i]; if(i==0) pf[i]=a[i]; else pf[i] = pf[i-1] + a[i]; //cout<<pf[i];}int q;cin >> q;while(q--){ int l, r; cin >> l >> r;//Calculating sum from l to r. if(r>n || l<1) { cout<<"Please input in range 1 to "<<n<<endl; break; } if(l==1) cout << pf[r] << endl; else cout << pf[r] - pf[l-1] << endl; }return 0;}
import java.util.*; class GFG { public static void main(String[] args) { int n = 6; int[] a = { 3, 6, 2, 8, 9, 2 }; int[] pf = new int[n + 2]; pf[0] = 0; for (int i = 0; i < n; i++) { pf[i + 1] = pf[i] + a[i]; } int[][] q = { { 2, 3 }, { 4, 6 }, { 1, 5 }, { 3, 6 } }; for (int i = 0; i < q.length; i++) { int l = q[i][0]; int r = q[i][1]; // Calculating sum from r to l. System.out.print(pf[r] - pf[l - 1] + "\n"); } }} // This code is contributed by umadevi9616
if __name__ == '__main__': n = 6; a = [ 3, 6, 2, 8, 9, 2 ]; pf = [0 for i in range(n+2)]; for i in range(n): pf[i + 1] = pf[i] + a[i]; q =[ [ 2, 3 ],[ 4, 6 ],[ 1, 5 ],[ 3, 6 ]]; for i in range(4): l = q[i][0]; r = q[i][1]; # Calculating sum from r to l. print(pf[r] - pf[l - 1] ); # This code is contributed by gauravrajput1
using System; public class GFG { public static void Main(String[] args) { int n = 6; int[] a = { 3, 6, 2, 8, 9, 2 }; int[] pf = new int[n + 2]; pf[0] = 0; for (int i = 0; i < n; i++) { pf[i + 1] = pf[i] + a[i]; } int[,] q = { { 2, 3 }, { 4, 6 }, { 1, 5 }, { 3, 6 } }; for (int i = 0; i < q.GetLength(0); i++) { int l = q[i,0]; int r = q[i,1]; // Calculating sum from r to l. Console.Write(pf[r] - pf[l - 1] + "\n"); } }} // This code is contributed by gauravrajput1
<script> var n = 6; var a = [ 3, 6, 2, 8, 9, 2 ]; var pf = Array(n + 2).fill(0); pf[0] = 0; for (i = 0; i < n; i++) { pf[i + 1] = pf[i] + a[i]; } var q = [ [ 2, 3 ], [ 4, 6 ], [ 1, 5 ], [ 3, 6 ] ]; for (i = 0; i < q.length; i++) { var l = q[i][0]; var r = q[i][1]; // Calculating sum from r to l. document.write(pf[r-1] - pf[l - 1] + "<br/>"); } // This code is contributed by gauravrajput1</script>
Example:
Input : n = 6
a[ ] = {3, 6, 2, 8, 9, 2}
q = 4
l = 2, r = 3.
l = 4, r = 6.
l = 1, r = 5.
l = 3, r = 6.
Output : 8
19
28
21
Time Complexity: O(n)
Applications :
Equilibrium index of an array: The equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes.
Find if there is a subarray with 0 sum: Given an array of positive and negative numbers, find if there is a subarray (of size at least one) with 0 sum.
Maximum subarray size, such that all subarrays of that size have sum less than k: Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have the sum of elements less than k.
Find the prime numbers which can written as sum of most consecutive primes: Given an array of limits. For every limit, find the prime number which can be written as the sum of the most consecutive primes smaller than or equal to the limit.
Longest Span with same Sum in two Binary arrays : Given two binary arrays, arr1[] and arr2[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + .... + arr1[j] = arr2[i] + arr2[i+1] + .... + arr2[j].
Maximum subarray sum modulo m: Given an array of n elements and an integer m. The task is to find the maximum value of the sum of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of this modulo operation.
Maximum subarray size, such that all subarrays of that size have sum less than k: Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have sum of elements less than k.
Maximum occurred integer in n ranges : Given n ranges of the form L and R, the task is to find the maximum occurring integer in all the ranges. If more than one such integer exits, print the smallest one.
Minimum cost for acquiring all coins with k extra coins allowed with every coin: You are given a list of N coins of different denominations. you can pay an amount equivalent to any 1 coin and can acquire that coin. In addition, once you have paid for a coin, we can choose at most K more coins and can acquire those for free. The task is to find the minimum amount required to acquire all the N coins for a given value of K.
Random number generator in arbitrary probability distribution fashion: Given n numbers, each with some frequency of occurrence. Return a random number with a probability proportional to its frequency of occurrence.
An Example Problem : Consider an array of size n with all initial values as 0. Perform the given ‘m’ add operations from index ‘a’ to ‘b’ and evaluate the highest element in the array. An add operation adds 100 to all elements from a to b (both inclusive).
Example:
Input : n = 5 // We consider array {0, 0, 0, 0, 0}
m = 3.
a = 2, b = 4.
a = 1, b = 3.
a = 1, b = 2.
Output : 300
Explanation :
After I operation -
A : 0 100 100 100 0
After II operation -
A : 100 200 200 100 0
After III operation -
A : 200 300 200 100 0
Highest element : 300
A simple approach is running a loop ‘m’ times. Inputting a and b and running a loop from a to b, adding all elements by 100. The efficient approach using Prefix Sum Array:
1 : Run a loop for 'm' times, inputting 'a' and 'b'.
2 : Add 100 at index 'a-1' and subtract 100 from index 'b'.
3 : After completion of 'm' operations, compute the prefix sum array.
4 : Scan the largest element and we're done.
What we did was adding 100 at ‘a’ because this will add 100 to all elements while taking the prefix sum array. Subtracting 100 from ‘b+1’ will reverse the changes made by adding 100 to elements from ‘b’ onward.For better understanding :
After I operation -
A : 0 100 0 0 -100
Prefix Sum Array : 0 100 100 100 0
After II operation -
A : 100 100 0 -100 -100
Prefix Sum Array : 100 200 200 100 0
After III operation -
A : 200 100 -100 -100 -100
Prefix Sum Array : 200 300 200 100 0
Final Prefix Sum Array : 200 300 200 100 0
The required highest element : 300
C++14
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; int find(int m, vector<pair<int,int>> q){ int mx = 0; vector<int> pre(5,0); for (int i = 0; i < m; i++) { // take input a and b int a = q[i].first, b = q[i].second; // add 100 at first index and // subtract 100 from last index // pre[1] becomes 100 pre[a-1] += 100; // pre[4] becomes -100 and this pre[b] -=100; // continues m times as we input diff. values of a and b } for (int i = 1; i < 5; i++) { // add all values in a cumulative way pre[i] += pre[i - 1]; // keep track of max value mx = max(mx, pre[i]); } return mx;} // Driver Codeint main(){ int m = 3; vector<pair<int,int>> q = {{2,4},{1,3},{1,2}}; // Function call cout<< find(m,q); return 0;}
import java.util.*; class GFG{ static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } }static int find(int m, pair []q){ int mx = 0; int []pre = new int[5]; for (int i = 0; i < m; i++) { // take input a and b int a = q[i].first, b = q[i].second; // add 100 at first index and // subtract 100 from last index // pre[1] becomes 100 pre[a-1] += 100; // pre[4] becomes -100 and this pre[b] -=100; // continues m times as we input diff. values of a and b } for (int i = 1; i < 5; i++) { // add all values in a cumulative way pre[i] += pre[i - 1]; // keep track of max value mx = Math.max(mx, pre[i]); } return mx;} // Driver Codepublic static void main(String[] args){ int m = 3; pair[] q = {new pair(2,4),new pair(1,3), new pair(1,2)}; // Function call System.out.print( find(m,q));}} // This code is contributed by gauravrajput1
# Python implementation of the approachdef find( m, q): mx = 0 pre = [0 for i in range(5) ] for i in range(m): # take input a and b a,b = q[i][0], q[i][1] # add 100 at first index and # subtract 100 from last index # pre[1] becomes 100 pre[a-1] += 100 # pre[4] becomes -100 and this pre[b] -=100; # continues m times as we input diff. values of a and b for i in range(1,5): # add all values in a cumulative way pre[i] += pre[i - 1] # keep track of max value mx = max(mx, pre[i]) return mx # Driver Codem = 3q = [[2,4],[1,3],[1,2]] # Function callprint(find(m,q)) # This code is contributed by rohitsingh07052
using System; public class GFG{ public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } }static int find(int m, pair []q){ int mx = 0; int []pre = new int[5]; for (int i = 0; i < m; i++) { // take input a and b int a = q[i].first, b = q[i].second; // add 100 at first index and // subtract 100 from last index // pre[1] becomes 100 pre[a-1] += 100; // pre[4] becomes -100 and this pre[b] -=100; // continues m times as we input diff. values of a and b } for (int i = 1; i < 5; i++) { // add all values in a cumulative way pre[i] += pre[i - 1]; // keep track of max value mx = Math.Max(mx, pre[i]); } return mx;} // Driver Codepublic static void Main(String[] args){ int m = 3; pair[] q = {new pair(2,4),new pair(1,3), new pair(1,2)}; // Function call Console.Write( find(m,q));}} // This code is contributed by gauravrajput1.
<script> function find( m,q){ let mx = 0; let pre = [0,0,0,0,0]; for (let i = 0; i < m; i++) { // take input a and b let a = q[i][0], b = q[i][1]; // add 100 at first index and // subtract 100 from last index // pre[1] becomes 100 pre[a-1] += 100; // pre[4] becomes -100 and this pre[b] -=100; // continues m times as we input diff. values of a and b } for (let i = 1; i < 5; i++) { // add all values in a cumulative way pre[i] += pre[i - 1]; // keep track of max value mx = Math.max(mx, pre[i]); } return mx;} // Driver Codelet m = 3;let q = [[2,4],[1,3],[1,2]]; // Function call document.write(find(m,q)); </script>
300
Recent Articles on Prefix Sum Technique
Practice Problems on Prefix Sum
DSA Self Paced – The Most used and Trusted Course on DSA
This article is contributed by Rohit Thapliyal. 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.
nitin mittal
Sam007
varadthokal3
chayanranparacr
rohitsingh07052
divyeshrabadiya07
hrushipatil2019262
GauravRajput1
umadevi9616
sweetygupta
adityakumar129
prefix-sum
Arrays
Competitive Programming
prefix-sum
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Fast I/O for Competitive Programming | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jul, 2022"
},
{
"code": null,
"e": 230,
"s": 54,
"text": "Given an array arr[] of size n, its prefix sum array is another array prefixSum[] of the same size, such that the value of prefixSum[i] is arr[0] + arr[1] + arr[2] ... arr[i]."
},
{
"code": null,
"e": 242,
"s": 230,
"text": "Examples : "
},
{
"code": null,
"e": 543,
"s": 242,
"text": "Input : arr[] = {10, 20, 10, 5, 15}\nOutput : prefixSum[] = {10, 30, 40, 45, 60}\n\nExplanation : While traversing the array, update \nthe element by adding it with its previous element.\nprefixSum[0] = 10, \nprefixSum[1] = prefixSum[0] + arr[1] = 30, \nprefixSum[2] = prefixSum[1] + arr[2] = 40 and so on."
},
{
"code": null,
"e": 722,
"s": 543,
"text": "To fill the prefix sum array, we run through index 1 to last and keep on adding the present element with the previous value in the prefix sum array.Below is the implementation : "
},
{
"code": null,
"e": 726,
"s": 722,
"text": "C++"
},
{
"code": null,
"e": 728,
"s": 726,
"text": "C"
},
{
"code": null,
"e": 733,
"s": 728,
"text": "Java"
},
{
"code": null,
"e": 741,
"s": 733,
"text": "Python3"
},
{
"code": null,
"e": 744,
"s": 741,
"text": "C#"
},
{
"code": null,
"e": 748,
"s": 744,
"text": "PHP"
},
{
"code": null,
"e": 759,
"s": 748,
"text": "Javascript"
},
{
"code": "// C++ program for Implementing prefix sum array#include <bits/stdc++.h>using namespace std; // Fills prefix sum arrayvoid fillPrefixSum(int arr[], int n, int prefixSum[]){ prefixSum[0] = arr[0]; // Adding present element with previous element for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // Driver Codeint main(){ int arr[] = { 10, 4, 16, 20 }; int n = sizeof(arr) / sizeof(arr[0]); int prefixSum[n]; fillPrefixSum(arr, n, prefixSum); for (int i = 0; i < n; i++) cout << prefixSum[i] << \" \";} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1381,
"s": 759,
"text": null
},
{
"code": "// C program for Implementing prefix sum array#include <stdio.h> // Fills prefix sum arrayvoid fillPrefixSum(int arr[], int n, int prefixSum[]){ prefixSum[0] = arr[0]; // Adding present element with previous element for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // Driver Codeint main(){ int arr[] = { 10, 4, 16, 20 }; int n = sizeof(arr) / sizeof(arr[0]); int prefixSum[n]; fillPrefixSum(arr, n, prefixSum); for (int i = 0; i < n; i++) cout << prefixSum[i] << \" \";} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1977,
"s": 1381,
"text": null
},
{
"code": "// Java Program for Implementing prefix sum arrayclassclass Prefix { // Fills prefix sum array static void fillPrefixSum(int arr[], int n, int prefixSum[]) { prefixSum[0] = arr[0]; // Adding present element with previous element for (int i = 1; i < n; ++i) prefixSum[i] = prefixSum[i - 1] + arr[i]; } // Driver code public static void main(String[] args) { int arr[] = { 10, 4, 16, 20 }; int n = arr.length; int prefixSum[] = new int[n]; fillPrefixSum(arr, n, prefixSum); for (int i = 0; i < n; i++) System.out.print(prefixSum[i] + \" \"); System.out.println(\"\"); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 2715,
"s": 1977,
"text": null
},
{
"code": "# Python Program for Implementing # prefix sum array # Fills prefix sum arraydef fillPrefixSum(arr, n, prefixSum): prefixSum[0] = arr[0] # Adding present element # with previous element for i in range(1, n): prefixSum[i] = prefixSum[i - 1] + arr[i] # Driver codearr =[10, 4, 16, 20 ]n = len(arr) prefixSum = [0 for i in range(n + 1)] fillPrefixSum(arr, n, prefixSum) for i in range(n): print(prefixSum[i], \" \", end =\"\") # This code is contributed# by Anant Agarwal.",
"e": 3213,
"s": 2715,
"text": null
},
{
"code": "// C# Program for Implementing// prefix sum arrayclassusing System; class GFG { // Fills prefix sum array static void fillPrefixSum(int[] arr, int n, int[] prefixSum) { prefixSum[0] = arr[0]; // Adding present element // with previous element for (int i = 1; i < n; ++i) prefixSum[i] = prefixSum[i - 1] + arr[i]; } // Driver code public static void Main() { int[] arr = { 10, 4, 16, 20 }; int n = arr.Length; int[] prefixSum = new int[n]; fillPrefixSum(arr, n, prefixSum); for (int i = 0; i < n; i++) Console.Write(prefixSum[i] + \" \"); Console.Write(\"\"); }} // This Code is Contributed by nitin mittal",
"e": 3970,
"s": 3213,
"text": null
},
{
"code": "<?php// PHP program for // Implementing prefix // sum array // Fills prefix sum arrayfunction fillPrefixSum($arr, $n){ $prefixSum = array(); $prefixSum[0] = $arr[0]; // Adding present element // with previous element for ($i = 1; $i < $n; $i++) $prefixSum[$i] = $prefixSum[$i - 1] + $arr[$i]; for ($i = 0; $i < $n; $i++) echo $prefixSum[$i] . \" \";} // Driver Code$arr = array(10, 4, 16, 20);$n = count($arr); fillPrefixSum($arr, $n); // This code is contributed// by Sam007?>",
"e": 4554,
"s": 3970,
"text": null
},
{
"code": "<script> // JavaScript Program for Implementing // prefix sum arrayclass // Fills prefix sum array function fillPrefixSum(arr, n, prefixSum) { prefixSum[0] = arr[0]; // Adding present element // with previous element for (let i = 1; i < n; ++i) prefixSum[i] = prefixSum[i - 1] + arr[i]; } let arr = [ 10, 4, 16, 20 ]; let n = arr.length; let prefixSum = new Array(n); fillPrefixSum(arr, n, prefixSum); for (let i = 0; i < n; i++) document.write(prefixSum[i] + \" \"); document.write(\"\"); </script>",
"e": 5158,
"s": 4554,
"text": null
},
{
"code": null,
"e": 5167,
"s": 5158,
"text": "Output: "
},
{
"code": null,
"e": 5179,
"s": 5167,
"text": "10 14 30 50"
},
{
"code": null,
"e": 5307,
"s": 5179,
"text": "Given an array arr[] of size n. Given Q queries and in each query given L and R, print sum of array elements from index L to R."
},
{
"code": null,
"e": 5313,
"s": 5307,
"text": "C++14"
},
{
"code": null,
"e": 5318,
"s": 5313,
"text": "Java"
},
{
"code": null,
"e": 5326,
"s": 5318,
"text": "Python3"
},
{
"code": null,
"e": 5329,
"s": 5326,
"text": "C#"
},
{
"code": null,
"e": 5335,
"s": 5329,
"text": "C++14"
},
{
"code": "#include <iostream>using namespace std;const int N = 1e5+10;int a[N];int pf[N]; int main() {int n;cin >> n;for(int i=1; i<=n; i++){ cin >> a[i]; if(i==0) pf[i]=a[i]; else pf[i] = pf[i-1] + a[i]; //cout<<pf[i];}int q;cin >> q;while(q--){ int l, r; cin >> l >> r;//Calculating sum from l to r. if(r>n || l<1) { cout<<\"Please input in range 1 to \"<<n<<endl; break; } if(l==1) cout << pf[r] << endl; else cout << pf[r] - pf[l-1] << endl; }return 0;}",
"e": 5863,
"s": 5335,
"text": null
},
{
"code": "import java.util.*; class GFG { public static void main(String[] args) { int n = 6; int[] a = { 3, 6, 2, 8, 9, 2 }; int[] pf = new int[n + 2]; pf[0] = 0; for (int i = 0; i < n; i++) { pf[i + 1] = pf[i] + a[i]; } int[][] q = { { 2, 3 }, { 4, 6 }, { 1, 5 }, { 3, 6 } }; for (int i = 0; i < q.length; i++) { int l = q[i][0]; int r = q[i][1]; // Calculating sum from r to l. System.out.print(pf[r] - pf[l - 1] + \"\\n\"); } }} // This code is contributed by umadevi9616",
"e": 6472,
"s": 5863,
"text": null
},
{
"code": "if __name__ == '__main__': n = 6; a = [ 3, 6, 2, 8, 9, 2 ]; pf = [0 for i in range(n+2)]; for i in range(n): pf[i + 1] = pf[i] + a[i]; q =[ [ 2, 3 ],[ 4, 6 ],[ 1, 5 ],[ 3, 6 ]]; for i in range(4): l = q[i][0]; r = q[i][1]; # Calculating sum from r to l. print(pf[r] - pf[l - 1] ); # This code is contributed by gauravrajput1 ",
"e": 6867,
"s": 6472,
"text": null
},
{
"code": "using System; public class GFG { public static void Main(String[] args) { int n = 6; int[] a = { 3, 6, 2, 8, 9, 2 }; int[] pf = new int[n + 2]; pf[0] = 0; for (int i = 0; i < n; i++) { pf[i + 1] = pf[i] + a[i]; } int[,] q = { { 2, 3 }, { 4, 6 }, { 1, 5 }, { 3, 6 } }; for (int i = 0; i < q.GetLength(0); i++) { int l = q[i,0]; int r = q[i,1]; // Calculating sum from r to l. Console.Write(pf[r] - pf[l - 1] + \"\\n\"); } }} // This code is contributed by gauravrajput1 ",
"e": 7466,
"s": 6867,
"text": null
},
{
"code": "<script> var n = 6; var a = [ 3, 6, 2, 8, 9, 2 ]; var pf = Array(n + 2).fill(0); pf[0] = 0; for (i = 0; i < n; i++) { pf[i + 1] = pf[i] + a[i]; } var q = [ [ 2, 3 ], [ 4, 6 ], [ 1, 5 ], [ 3, 6 ] ]; for (i = 0; i < q.length; i++) { var l = q[i][0]; var r = q[i][1]; // Calculating sum from r to l. document.write(pf[r-1] - pf[l - 1] + \"<br/>\"); } // This code is contributed by gauravrajput1</script>",
"e": 7995,
"s": 7466,
"text": null
},
{
"code": null,
"e": 8006,
"s": 7995,
"text": "Example: "
},
{
"code": null,
"e": 8150,
"s": 8006,
"text": "Input : n = 6\n a[ ] = {3, 6, 2, 8, 9, 2}\n q = 4\n l = 2, r = 3.\n l = 4, r = 6.\n l = 1, r = 5.\n l = 3, r = 6."
},
{
"code": null,
"e": 8201,
"s": 8150,
"text": "Output : 8\n 19\n 28\n 21"
},
{
"code": null,
"e": 8223,
"s": 8201,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 8239,
"s": 8223,
"text": "Applications : "
},
{
"code": null,
"e": 8414,
"s": 8239,
"text": "Equilibrium index of an array: The equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes."
},
{
"code": null,
"e": 8566,
"s": 8414,
"text": "Find if there is a subarray with 0 sum: Given an array of positive and negative numbers, find if there is a subarray (of size at least one) with 0 sum."
},
{
"code": null,
"e": 8833,
"s": 8566,
"text": "Maximum subarray size, such that all subarrays of that size have sum less than k: Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have the sum of elements less than k."
},
{
"code": null,
"e": 9073,
"s": 8833,
"text": "Find the prime numbers which can written as sum of most consecutive primes: Given an array of limits. For every limit, find the prime number which can be written as the sum of the most consecutive primes smaller than or equal to the limit."
},
{
"code": null,
"e": 9336,
"s": 9073,
"text": "Longest Span with same Sum in two Binary arrays : Given two binary arrays, arr1[] and arr2[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + .... + arr1[j] = arr2[i] + arr2[i+1] + .... + arr2[j]."
},
{
"code": null,
"e": 9582,
"s": 9336,
"text": "Maximum subarray sum modulo m: Given an array of n elements and an integer m. The task is to find the maximum value of the sum of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of this modulo operation."
},
{
"code": null,
"e": 9845,
"s": 9582,
"text": "Maximum subarray size, such that all subarrays of that size have sum less than k: Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have sum of elements less than k."
},
{
"code": null,
"e": 10050,
"s": 9845,
"text": "Maximum occurred integer in n ranges : Given n ranges of the form L and R, the task is to find the maximum occurring integer in all the ranges. If more than one such integer exits, print the smallest one."
},
{
"code": null,
"e": 10475,
"s": 10050,
"text": "Minimum cost for acquiring all coins with k extra coins allowed with every coin: You are given a list of N coins of different denominations. you can pay an amount equivalent to any 1 coin and can acquire that coin. In addition, once you have paid for a coin, we can choose at most K more coins and can acquire those for free. The task is to find the minimum amount required to acquire all the N coins for a given value of K."
},
{
"code": null,
"e": 10690,
"s": 10475,
"text": "Random number generator in arbitrary probability distribution fashion: Given n numbers, each with some frequency of occurrence. Return a random number with a probability proportional to its frequency of occurrence."
},
{
"code": null,
"e": 10948,
"s": 10690,
"text": "An Example Problem : Consider an array of size n with all initial values as 0. Perform the given ‘m’ add operations from index ‘a’ to ‘b’ and evaluate the highest element in the array. An add operation adds 100 to all elements from a to b (both inclusive). "
},
{
"code": null,
"e": 10959,
"s": 10948,
"text": "Example: "
},
{
"code": null,
"e": 11273,
"s": 10959,
"text": "Input : n = 5 // We consider array {0, 0, 0, 0, 0}\n m = 3.\n a = 2, b = 4.\n a = 1, b = 3.\n a = 1, b = 2.\nOutput : 300\n\nExplanation : \n\nAfter I operation -\nA : 0 100 100 100 0\n\nAfter II operation -\nA : 100 200 200 100 0\n\nAfter III operation -\nA : 200 300 200 100 0\n\nHighest element : 300"
},
{
"code": null,
"e": 11446,
"s": 11273,
"text": "A simple approach is running a loop ‘m’ times. Inputting a and b and running a loop from a to b, adding all elements by 100. The efficient approach using Prefix Sum Array: "
},
{
"code": null,
"e": 11674,
"s": 11446,
"text": "1 : Run a loop for 'm' times, inputting 'a' and 'b'.\n2 : Add 100 at index 'a-1' and subtract 100 from index 'b'.\n3 : After completion of 'm' operations, compute the prefix sum array.\n4 : Scan the largest element and we're done."
},
{
"code": null,
"e": 11912,
"s": 11674,
"text": "What we did was adding 100 at ‘a’ because this will add 100 to all elements while taking the prefix sum array. Subtracting 100 from ‘b+1’ will reverse the changes made by adding 100 to elements from ‘b’ onward.For better understanding : "
},
{
"code": null,
"e": 12238,
"s": 11912,
"text": "After I operation -\nA : 0 100 0 0 -100 \nPrefix Sum Array : 0 100 100 100 0\n\nAfter II operation -\nA : 100 100 0 -100 -100\nPrefix Sum Array : 100 200 200 100 0\n\nAfter III operation -\nA : 200 100 -100 -100 -100\nPrefix Sum Array : 200 300 200 100 0\n\nFinal Prefix Sum Array : 200 300 200 100 0 \n\nThe required highest element : 300"
},
{
"code": null,
"e": 12244,
"s": 12238,
"text": "C++14"
},
{
"code": null,
"e": 12249,
"s": 12244,
"text": "Java"
},
{
"code": null,
"e": 12257,
"s": 12249,
"text": "Python3"
},
{
"code": null,
"e": 12260,
"s": 12257,
"text": "C#"
},
{
"code": null,
"e": 12271,
"s": 12260,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int find(int m, vector<pair<int,int>> q){ int mx = 0; vector<int> pre(5,0); for (int i = 0; i < m; i++) { // take input a and b int a = q[i].first, b = q[i].second; // add 100 at first index and // subtract 100 from last index // pre[1] becomes 100 pre[a-1] += 100; // pre[4] becomes -100 and this pre[b] -=100; // continues m times as we input diff. values of a and b } for (int i = 1; i < 5; i++) { // add all values in a cumulative way pre[i] += pre[i - 1]; // keep track of max value mx = max(mx, pre[i]); } return mx;} // Driver Codeint main(){ int m = 3; vector<pair<int,int>> q = {{2,4},{1,3},{1,2}}; // Function call cout<< find(m,q); return 0;}",
"e": 13213,
"s": 12271,
"text": null
},
{
"code": "import java.util.*; class GFG{ static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } }static int find(int m, pair []q){ int mx = 0; int []pre = new int[5]; for (int i = 0; i < m; i++) { // take input a and b int a = q[i].first, b = q[i].second; // add 100 at first index and // subtract 100 from last index // pre[1] becomes 100 pre[a-1] += 100; // pre[4] becomes -100 and this pre[b] -=100; // continues m times as we input diff. values of a and b } for (int i = 1; i < 5; i++) { // add all values in a cumulative way pre[i] += pre[i - 1]; // keep track of max value mx = Math.max(mx, pre[i]); } return mx;} // Driver Codepublic static void main(String[] args){ int m = 3; pair[] q = {new pair(2,4),new pair(1,3), new pair(1,2)}; // Function call System.out.print( find(m,q));}} // This code is contributed by gauravrajput1 ",
"e": 14438,
"s": 13213,
"text": null
},
{
"code": "# Python implementation of the approachdef find( m, q): mx = 0 pre = [0 for i in range(5) ] for i in range(m): # take input a and b a,b = q[i][0], q[i][1] # add 100 at first index and # subtract 100 from last index # pre[1] becomes 100 pre[a-1] += 100 # pre[4] becomes -100 and this pre[b] -=100; # continues m times as we input diff. values of a and b for i in range(1,5): # add all values in a cumulative way pre[i] += pre[i - 1] # keep track of max value mx = max(mx, pre[i]) return mx # Driver Codem = 3q = [[2,4],[1,3],[1,2]] # Function callprint(find(m,q)) # This code is contributed by rohitsingh07052",
"e": 15251,
"s": 14438,
"text": null
},
{
"code": "using System; public class GFG{ public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } }static int find(int m, pair []q){ int mx = 0; int []pre = new int[5]; for (int i = 0; i < m; i++) { // take input a and b int a = q[i].first, b = q[i].second; // add 100 at first index and // subtract 100 from last index // pre[1] becomes 100 pre[a-1] += 100; // pre[4] becomes -100 and this pre[b] -=100; // continues m times as we input diff. values of a and b } for (int i = 1; i < 5; i++) { // add all values in a cumulative way pre[i] += pre[i - 1]; // keep track of max value mx = Math.Max(mx, pre[i]); } return mx;} // Driver Codepublic static void Main(String[] args){ int m = 3; pair[] q = {new pair(2,4),new pair(1,3), new pair(1,2)}; // Function call Console.Write( find(m,q));}} // This code is contributed by gauravrajput1.",
"e": 16471,
"s": 15251,
"text": null
},
{
"code": "<script> function find( m,q){ let mx = 0; let pre = [0,0,0,0,0]; for (let i = 0; i < m; i++) { // take input a and b let a = q[i][0], b = q[i][1]; // add 100 at first index and // subtract 100 from last index // pre[1] becomes 100 pre[a-1] += 100; // pre[4] becomes -100 and this pre[b] -=100; // continues m times as we input diff. values of a and b } for (let i = 1; i < 5; i++) { // add all values in a cumulative way pre[i] += pre[i - 1]; // keep track of max value mx = Math.max(mx, pre[i]); } return mx;} // Driver Codelet m = 3;let q = [[2,4],[1,3],[1,2]]; // Function call document.write(find(m,q)); </script>",
"e": 17318,
"s": 16471,
"text": null
},
{
"code": null,
"e": 17322,
"s": 17318,
"text": "300"
},
{
"code": null,
"e": 17362,
"s": 17322,
"text": "Recent Articles on Prefix Sum Technique"
},
{
"code": null,
"e": 17394,
"s": 17362,
"text": "Practice Problems on Prefix Sum"
},
{
"code": null,
"e": 17451,
"s": 17394,
"text": "DSA Self Paced – The Most used and Trusted Course on DSA"
},
{
"code": null,
"e": 17875,
"s": 17451,
"text": "This article is contributed by Rohit Thapliyal. 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": 17888,
"s": 17875,
"text": "nitin mittal"
},
{
"code": null,
"e": 17895,
"s": 17888,
"text": "Sam007"
},
{
"code": null,
"e": 17908,
"s": 17895,
"text": "varadthokal3"
},
{
"code": null,
"e": 17924,
"s": 17908,
"text": "chayanranparacr"
},
{
"code": null,
"e": 17940,
"s": 17924,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 17958,
"s": 17940,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 17977,
"s": 17958,
"text": "hrushipatil2019262"
},
{
"code": null,
"e": 17991,
"s": 17977,
"text": "GauravRajput1"
},
{
"code": null,
"e": 18003,
"s": 17991,
"text": "umadevi9616"
},
{
"code": null,
"e": 18015,
"s": 18003,
"text": "sweetygupta"
},
{
"code": null,
"e": 18030,
"s": 18015,
"text": "adityakumar129"
},
{
"code": null,
"e": 18041,
"s": 18030,
"text": "prefix-sum"
},
{
"code": null,
"e": 18048,
"s": 18041,
"text": "Arrays"
},
{
"code": null,
"e": 18072,
"s": 18048,
"text": "Competitive Programming"
},
{
"code": null,
"e": 18083,
"s": 18072,
"text": "prefix-sum"
},
{
"code": null,
"e": 18090,
"s": 18083,
"text": "Arrays"
},
{
"code": null,
"e": 18188,
"s": 18090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18220,
"s": 18188,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 18243,
"s": 18220,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 18328,
"s": 18243,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 18384,
"s": 18328,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 18411,
"s": 18384,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 18454,
"s": 18411,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 18497,
"s": 18454,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 18538,
"s": 18497,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 18565,
"s": 18538,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Java.io.Console class in Java | 09 Jan, 2017
The Java.io.Console class provides methods to access the character-based console device, if any, associated with the current Java virtual machine. The Console class was added to java.io by JDK 6.
Important Points:
It is used to read from and write to the console, if one exists.
Console is primarily a convenience class because most of its functionality is available through System.in and System.out. However, its use can simplify some types of console interactions, especially when reading strings from the console.
Console supplies no constructors. Instead, a Console object is obtained by calling System.console( ), which is shown here:static Console console( )If a console is available, then a reference to it is returned. Otherwise, null is returned. A console will not be available in all cases. Thus, if null is returned, no console I/O is possible.
static Console console( )
If a console is available, then a reference to it is returned. Otherwise, null is returned. A console will not be available in all cases. Thus, if null is returned, no console I/O is possible.
It provides methods to read text and password. If you read password using Console class, it will not be displayed to the user.The java.io.Console class is attached with system console internally.
Important Methods:
writer : Retrieves the unique PrintWriter object associated with this console.Syntax:public PrintWriter writer()
Returns: The printwriter associated with this console
public PrintWriter writer()
Returns: The printwriter associated with this console
reader : Retrieves the unique Reader object associated with this console.Syntax:public Reader reader()
Returns: The reader associated with this console
public Reader reader()
Returns: The reader associated with this console
format : Writes a formatted string to this console’s output stream using the specified format string and arguments.Syntax:public Console format(String fmt, Object... args)
Parameters:
fmt - A format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string.
If there are more arguments than format specifiers, the extra arguments are ignored.
Returns:This console
Throws: IllegalFormatException
public Console format(String fmt, Object... args)
Parameters:
fmt - A format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string.
If there are more arguments than format specifiers, the extra arguments are ignored.
Returns:This console
Throws: IllegalFormatException
printf : A convenience method to write a formatted string to this console’s output stream using the specified format string and arguments.Syntax:public Console printf(String format, Object... args)
Parameters:
format - A format string as described in Format string syntax.
args - Arguments referenced by the format specifiers in the format string.
If there are more arguments than format specifiers, the extra arguments are ignored.
Returns:This console
Throws:IllegalFormatException
public Console printf(String format, Object... args)
Parameters:
format - A format string as described in Format string syntax.
args - Arguments referenced by the format specifiers in the format string.
If there are more arguments than format specifiers, the extra arguments are ignored.
Returns:This console
Throws:IllegalFormatException
readLine : Provides a formatted prompt, then reads a single line of text from the console.Syntax:public String readLine(String fmt,Object... args)
Parameters:
fmt - A format string as described in Format string syntax.
args - Arguments referenced by the format specifiers in the format string.
If there are more arguments than format specifiers, the extra arguments are ignored.
Returns: A string containing the line read from the console,
not including any line-termination characters, or null
if an end of stream has been reached.
Throws:
IllegalFormatException
IOError - If an I/O error occurs.
public String readLine(String fmt,Object... args)
Parameters:
fmt - A format string as described in Format string syntax.
args - Arguments referenced by the format specifiers in the format string.
If there are more arguments than format specifiers, the extra arguments are ignored.
Returns: A string containing the line read from the console,
not including any line-termination characters, or null
if an end of stream has been reached.
Throws:
IllegalFormatException
IOError - If an I/O error occurs.
readLine : Reads a single line of text from the console.Syntax:public String readLine()
Returns: A string containing the line read from the console,
not including any line-termination characters, or null
if an end of stream has been reached.
Throws: IOError
public String readLine()
Returns: A string containing the line read from the console,
not including any line-termination characters, or null
if an end of stream has been reached.
Throws: IOError
readPassword: Provides a formatted prompt, then reads a password or passphrase from the console with echoing disabled.Syntax:public char[] readPassword(String fmt,Object... args)
Parameters:
fmt - A format string as described in Format string syntax for the prompt text.
args - Arguments referenced by the format specifiers in the format string.
Returns: A character array containing the password or passphrase read
from the console, not including any line-termination characters, or null
if an end of stream has been reached.
Throws:
IllegalFormatException
IOError
public char[] readPassword(String fmt,Object... args)
Parameters:
fmt - A format string as described in Format string syntax for the prompt text.
args - Arguments referenced by the format specifiers in the format string.
Returns: A character array containing the password or passphrase read
from the console, not including any line-termination characters, or null
if an end of stream has been reached.
Throws:
IllegalFormatException
IOError
readPassword : Reads a password or passphrase from the console with echoing disabledSyntax:public char[] readPassword()
Returns: A character array containing the password or passphrase
read from the console, not including any line-termination characters, or null
if an end of stream has been reached.
Throws:IOError
public char[] readPassword()
Returns: A character array containing the password or passphrase
read from the console, not including any line-termination characters, or null
if an end of stream has been reached.
Throws:IOError
flush : Flushes the console and forces any buffered output to be written immediately .Syntax:public void flush()
Specified by: flush in interface Flushable
public void flush()
Specified by: flush in interface Flushable
Program:
// Java Program to demonstrate Console Methods import java.io.*;class ConsoleDemo { public static void main(String args[]) { String str; //Obtaining a reference to the console. Console con = System.console(); // Checking If there is no console available, then exit. if(con == null) { System.out.print("No console available"); return; } // Read a string and then display it. str = con.readLine("Enter your name: "); con.printf("Here is your name: %s\n", str); //to read password and then display it System.out.println("Enter the password: "); char[] ch=con.readPassword(); //converting char array into string String pass = String.valueOf(ch); System.out.println("Password is: " + pass); }}
Output:
Enter your name: Nishant Sharma
Here is your name: Nishant Sharma
Enter the password:
Password is: dada
Note: System.console() returns null in an online IDE
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.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jan, 2017"
},
{
"code": null,
"e": 250,
"s": 54,
"text": "The Java.io.Console class provides methods to access the character-based console device, if any, associated with the current Java virtual machine. The Console class was added to java.io by JDK 6."
},
{
"code": null,
"e": 268,
"s": 250,
"text": "Important Points:"
},
{
"code": null,
"e": 333,
"s": 268,
"text": "It is used to read from and write to the console, if one exists."
},
{
"code": null,
"e": 571,
"s": 333,
"text": "Console is primarily a convenience class because most of its functionality is available through System.in and System.out. However, its use can simplify some types of console interactions, especially when reading strings from the console."
},
{
"code": null,
"e": 912,
"s": 571,
"text": "Console supplies no constructors. Instead, a Console object is obtained by calling System.console( ), which is shown here:static Console console( )If a console is available, then a reference to it is returned. Otherwise, null is returned. A console will not be available in all cases. Thus, if null is returned, no console I/O is possible."
},
{
"code": null,
"e": 939,
"s": 912,
"text": "static Console console( )"
},
{
"code": null,
"e": 1132,
"s": 939,
"text": "If a console is available, then a reference to it is returned. Otherwise, null is returned. A console will not be available in all cases. Thus, if null is returned, no console I/O is possible."
},
{
"code": null,
"e": 1328,
"s": 1132,
"text": "It provides methods to read text and password. If you read password using Console class, it will not be displayed to the user.The java.io.Console class is attached with system console internally."
},
{
"code": null,
"e": 1347,
"s": 1328,
"text": "Important Methods:"
},
{
"code": null,
"e": 1515,
"s": 1347,
"text": "writer : Retrieves the unique PrintWriter object associated with this console.Syntax:public PrintWriter writer() \nReturns: The printwriter associated with this console"
},
{
"code": null,
"e": 1598,
"s": 1515,
"text": "public PrintWriter writer() \nReturns: The printwriter associated with this console"
},
{
"code": null,
"e": 1753,
"s": 1598,
"text": "reader : Retrieves the unique Reader object associated with this console.Syntax:public Reader reader() \nReturns: The reader associated with this console\n"
},
{
"code": null,
"e": 1828,
"s": 1753,
"text": "public Reader reader() \nReturns: The reader associated with this console\n"
},
{
"code": null,
"e": 2286,
"s": 1828,
"text": "format : Writes a formatted string to this console’s output stream using the specified format string and arguments.Syntax:public Console format(String fmt, Object... args)\nParameters:\nfmt - A format string as described in Format string syntax\nargs - Arguments referenced by the format specifiers in the format string. \nIf there are more arguments than format specifiers, the extra arguments are ignored.\nReturns:This console\nThrows: IllegalFormatException \n"
},
{
"code": null,
"e": 2622,
"s": 2286,
"text": "public Console format(String fmt, Object... args)\nParameters:\nfmt - A format string as described in Format string syntax\nargs - Arguments referenced by the format specifiers in the format string. \nIf there are more arguments than format specifiers, the extra arguments are ignored.\nReturns:This console\nThrows: IllegalFormatException \n"
},
{
"code": null,
"e": 3109,
"s": 2622,
"text": "printf : A convenience method to write a formatted string to this console’s output stream using the specified format string and arguments.Syntax:public Console printf(String format, Object... args)\nParameters:\nformat - A format string as described in Format string syntax.\nargs - Arguments referenced by the format specifiers in the format string. \nIf there are more arguments than format specifiers, the extra arguments are ignored.\nReturns:This console\nThrows:IllegalFormatException \n"
},
{
"code": null,
"e": 3451,
"s": 3109,
"text": "public Console printf(String format, Object... args)\nParameters:\nformat - A format string as described in Format string syntax.\nargs - Arguments referenced by the format specifiers in the format string. \nIf there are more arguments than format specifiers, the extra arguments are ignored.\nReturns:This console\nThrows:IllegalFormatException \n"
},
{
"code": null,
"e": 4054,
"s": 3451,
"text": "readLine : Provides a formatted prompt, then reads a single line of text from the console.Syntax:public String readLine(String fmt,Object... args) \nParameters:\nfmt - A format string as described in Format string syntax.\nargs - Arguments referenced by the format specifiers in the format string. \nIf there are more arguments than format specifiers, the extra arguments are ignored.\nReturns: A string containing the line read from the console, \nnot including any line-termination characters, or null \nif an end of stream has been reached.\nThrows:\nIllegalFormatException\nIOError - If an I/O error occurs.\n"
},
{
"code": null,
"e": 4560,
"s": 4054,
"text": "public String readLine(String fmt,Object... args) \nParameters:\nfmt - A format string as described in Format string syntax.\nargs - Arguments referenced by the format specifiers in the format string. \nIf there are more arguments than format specifiers, the extra arguments are ignored.\nReturns: A string containing the line read from the console, \nnot including any line-termination characters, or null \nif an end of stream has been reached.\nThrows:\nIllegalFormatException\nIOError - If an I/O error occurs.\n"
},
{
"code": null,
"e": 4823,
"s": 4560,
"text": "readLine : Reads a single line of text from the console.Syntax:public String readLine() \nReturns: A string containing the line read from the console,\n not including any line-termination characters, or null \nif an end of stream has been reached.\nThrows: IOError \n"
},
{
"code": null,
"e": 5023,
"s": 4823,
"text": "public String readLine() \nReturns: A string containing the line read from the console,\n not including any line-termination characters, or null \nif an end of stream has been reached.\nThrows: IOError \n"
},
{
"code": null,
"e": 5592,
"s": 5023,
"text": "readPassword: Provides a formatted prompt, then reads a password or passphrase from the console with echoing disabled.Syntax:public char[] readPassword(String fmt,Object... args)\nParameters:\nfmt - A format string as described in Format string syntax for the prompt text.\nargs - Arguments referenced by the format specifiers in the format string.\nReturns: A character array containing the password or passphrase read \nfrom the console, not including any line-termination characters, or null \nif an end of stream has been reached.\nThrows:\nIllegalFormatException \nIOError"
},
{
"code": null,
"e": 6036,
"s": 5592,
"text": "public char[] readPassword(String fmt,Object... args)\nParameters:\nfmt - A format string as described in Format string syntax for the prompt text.\nargs - Arguments referenced by the format specifiers in the format string.\nReturns: A character array containing the password or passphrase read \nfrom the console, not including any line-termination characters, or null \nif an end of stream has been reached.\nThrows:\nIllegalFormatException \nIOError"
},
{
"code": null,
"e": 6354,
"s": 6036,
"text": "readPassword : Reads a password or passphrase from the console with echoing disabledSyntax:public char[] readPassword()\nReturns: A character array containing the password or passphrase \nread from the console, not including any line-termination characters, or null \nif an end of stream has been reached.\nThrows:IOError"
},
{
"code": null,
"e": 6581,
"s": 6354,
"text": "public char[] readPassword()\nReturns: A character array containing the password or passphrase \nread from the console, not including any line-termination characters, or null \nif an end of stream has been reached.\nThrows:IOError"
},
{
"code": null,
"e": 6737,
"s": 6581,
"text": "flush : Flushes the console and forces any buffered output to be written immediately .Syntax:public void flush()\nSpecified by: flush in interface Flushable"
},
{
"code": null,
"e": 6800,
"s": 6737,
"text": "public void flush()\nSpecified by: flush in interface Flushable"
},
{
"code": null,
"e": 6809,
"s": 6800,
"text": "Program:"
},
{
"code": "// Java Program to demonstrate Console Methods import java.io.*;class ConsoleDemo { public static void main(String args[]) { String str; //Obtaining a reference to the console. Console con = System.console(); // Checking If there is no console available, then exit. if(con == null) { System.out.print(\"No console available\"); return; } // Read a string and then display it. str = con.readLine(\"Enter your name: \"); con.printf(\"Here is your name: %s\\n\", str); //to read password and then display it System.out.println(\"Enter the password: \"); char[] ch=con.readPassword(); //converting char array into string String pass = String.valueOf(ch); System.out.println(\"Password is: \" + pass); }}",
"e": 7678,
"s": 6809,
"text": null
},
{
"code": null,
"e": 7686,
"s": 7678,
"text": "Output:"
},
{
"code": null,
"e": 7792,
"s": 7686,
"text": "Enter your name: Nishant Sharma\nHere is your name: Nishant Sharma\nEnter the password: \nPassword is: dada\n"
},
{
"code": null,
"e": 7845,
"s": 7792,
"text": "Note: System.console() returns null in an online IDE"
},
{
"code": null,
"e": 8147,
"s": 7845,
"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": 8272,
"s": 8147,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8281,
"s": 8272,
"text": "Java-I/O"
},
{
"code": null,
"e": 8286,
"s": 8281,
"text": "Java"
},
{
"code": null,
"e": 8291,
"s": 8286,
"text": "Java"
},
{
"code": null,
"e": 8389,
"s": 8291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8440,
"s": 8389,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 8471,
"s": 8440,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 8490,
"s": 8471,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 8520,
"s": 8490,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 8535,
"s": 8520,
"text": "Stream In Java"
},
{
"code": null,
"e": 8553,
"s": 8535,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 8573,
"s": 8553,
"text": "Collections in Java"
},
{
"code": null,
"e": 8597,
"s": 8573,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 8629,
"s": 8597,
"text": "Multidimensional Arrays in Java"
}
] |
How to Change Axis Intervals in R Plots? | 19 Dec, 2021
In this article, we will be looking at the different approaches to change axis intervals in the R programming language.
In this method of changing the axis intervals, the user needs to call the xlim() and ylim() functions, passing the arguments of the range of the axis intervals required by the user in form of the vector, this will be changing the axis intervals of the plot as per the specified parameters by the user in the R programming language.
xlim() and ylim() functions are used to limit the x-axis and the y-axis.
Syntax:
xlim(...)
ylim(...)
Parameters:
...: If numeric, will create a continuous scale, if factor or character, will create a discrete scale.
Syntax:
barplot(data,xlim=c(),ylim=c())
Example: Initial plot
R
gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg)
Output:
Example: Change axis intervals
R
gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg,xlim=c(0,20), ylim=c(0,15))
Output:
In this method to change the axis intervals of the given plot, the user needs to use the log arguments with the plot function to transform one of the axes into a log scale, this will be changing the axis defined by the user to the logarithm axis in the R programming language.
Syntax:
barplot(data,log='x/y')
Example: Initial plot
R
gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg)
Output:
Example: Change axis intervals
R
gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg,log='y')
Output:
In this approach to change the axis intervals of the given plot, the user needs to install and import the ggplot2 package in the working console of the R programming language, here the ggplot2 package is responsible for creating the plots, then the user needs to call the xlim() and the ylim() function with the required parameters as per the user to change the axis intervals as required by the user, these functions will be called with the plot created with ggplot2 and this will be leading to the change in the plot axis intervals as defined by the users.
Example: Initial plot
R
gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg)
Output:
Example: Change axis intervals
R
library(ggplot2) gfg<-data.frame(x=c(8,9,6,5,8,5,1,7,3,5), y=c(9,6,5,4,2,5,6,7,4,1)) ggplot(data=gfg,aes(x=x, y=y)) + geom_point()+xlim(0,15)+ylim(0,20)
Output:
In this method to change the axis interval, the user needs to install and import the ggplot2 package in the working R console, this package will be responsible for the plotting of the plot and for using some of the functionality. Then the user needs to call the scale_x_continous() /scale_x_continous() function with the plotted ggplot2 plot with the required parameters to change the axis intervals to a log scale in the R programming language.
scale_x_continuous() / scale_y_continuous() functions are used to for continuous position scales (x & y).
Syntax:
scale_x_continuous(..., expand = waiver())
scale_y_continuous(..., expand = waiver())
Parameters:
...: common continuous scale parameters: name, breaks, labels, na.value, limits and trans.
expand: a numeric vector of length two giving multiplicative and additive expansion constants.
Example: Initial plot
R
library(ggplot2) gfg<-data.frame(x=c(8,9,6,5,8,5,1,7,3,5), y=c(9,6,5,4,2,5,6,7,4,1)) ggplot(data=gfg,aes(x=x, y=y)) + geom_point()
Output:
Example: Change axis intervals
R
library(ggplot2) gfg<-data.frame(x=c(8,9,6,5,8,5,1,7,3,5), y=c(9,6,5,4,2,5,6,7,4,1)) ggplot(data=gfg,aes(x=x, y=y)) + geom_point()+scale_y_continuous(trans = 'log10')
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "In this article, we will be looking at the different approaches to change axis intervals in the R programming language."
},
{
"code": null,
"e": 480,
"s": 148,
"text": "In this method of changing the axis intervals, the user needs to call the xlim() and ylim() functions, passing the arguments of the range of the axis intervals required by the user in form of the vector, this will be changing the axis intervals of the plot as per the specified parameters by the user in the R programming language."
},
{
"code": null,
"e": 553,
"s": 480,
"text": "xlim() and ylim() functions are used to limit the x-axis and the y-axis."
},
{
"code": null,
"e": 561,
"s": 553,
"text": "Syntax:"
},
{
"code": null,
"e": 571,
"s": 561,
"text": "xlim(...)"
},
{
"code": null,
"e": 581,
"s": 571,
"text": "ylim(...)"
},
{
"code": null,
"e": 593,
"s": 581,
"text": "Parameters:"
},
{
"code": null,
"e": 697,
"s": 593,
"text": "...: If numeric, will create a continuous scale, if factor or character, will create a discrete scale."
},
{
"code": null,
"e": 705,
"s": 697,
"text": "Syntax:"
},
{
"code": null,
"e": 737,
"s": 705,
"text": "barplot(data,xlim=c(),ylim=c())"
},
{
"code": null,
"e": 759,
"s": 737,
"text": "Example: Initial plot"
},
{
"code": null,
"e": 761,
"s": 759,
"text": "R"
},
{
"code": "gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg)",
"e": 801,
"s": 761,
"text": null
},
{
"code": null,
"e": 809,
"s": 801,
"text": "Output:"
},
{
"code": null,
"e": 840,
"s": 809,
"text": "Example: Change axis intervals"
},
{
"code": null,
"e": 842,
"s": 840,
"text": "R"
},
{
"code": "gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg,xlim=c(0,20), ylim=c(0,15))",
"e": 909,
"s": 842,
"text": null
},
{
"code": null,
"e": 917,
"s": 909,
"text": "Output:"
},
{
"code": null,
"e": 1194,
"s": 917,
"text": "In this method to change the axis intervals of the given plot, the user needs to use the log arguments with the plot function to transform one of the axes into a log scale, this will be changing the axis defined by the user to the logarithm axis in the R programming language."
},
{
"code": null,
"e": 1202,
"s": 1194,
"text": "Syntax:"
},
{
"code": null,
"e": 1226,
"s": 1202,
"text": "barplot(data,log='x/y')"
},
{
"code": null,
"e": 1248,
"s": 1226,
"text": "Example: Initial plot"
},
{
"code": null,
"e": 1250,
"s": 1248,
"text": "R"
},
{
"code": "gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg)",
"e": 1290,
"s": 1250,
"text": null
},
{
"code": null,
"e": 1298,
"s": 1290,
"text": "Output:"
},
{
"code": null,
"e": 1329,
"s": 1298,
"text": "Example: Change axis intervals"
},
{
"code": null,
"e": 1331,
"s": 1329,
"text": "R"
},
{
"code": "gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg,log='y')",
"e": 1379,
"s": 1331,
"text": null
},
{
"code": null,
"e": 1387,
"s": 1379,
"text": "Output:"
},
{
"code": null,
"e": 1946,
"s": 1387,
"text": "In this approach to change the axis intervals of the given plot, the user needs to install and import the ggplot2 package in the working console of the R programming language, here the ggplot2 package is responsible for creating the plots, then the user needs to call the xlim() and the ylim() function with the required parameters as per the user to change the axis intervals as required by the user, these functions will be called with the plot created with ggplot2 and this will be leading to the change in the plot axis intervals as defined by the users."
},
{
"code": null,
"e": 1969,
"s": 1946,
"text": "Example: Initial plot "
},
{
"code": null,
"e": 1971,
"s": 1969,
"text": "R"
},
{
"code": "gfg<-c(8,9,6,5,8,5,1,7,3,5)barplot(gfg)",
"e": 2011,
"s": 1971,
"text": null
},
{
"code": null,
"e": 2019,
"s": 2011,
"text": "Output:"
},
{
"code": null,
"e": 2050,
"s": 2019,
"text": "Example: Change axis intervals"
},
{
"code": null,
"e": 2052,
"s": 2050,
"text": "R"
},
{
"code": "library(ggplot2) gfg<-data.frame(x=c(8,9,6,5,8,5,1,7,3,5), y=c(9,6,5,4,2,5,6,7,4,1)) ggplot(data=gfg,aes(x=x, y=y)) + geom_point()+xlim(0,15)+ylim(0,20)",
"e": 2222,
"s": 2052,
"text": null
},
{
"code": null,
"e": 2230,
"s": 2222,
"text": "Output:"
},
{
"code": null,
"e": 2676,
"s": 2230,
"text": "In this method to change the axis interval, the user needs to install and import the ggplot2 package in the working R console, this package will be responsible for the plotting of the plot and for using some of the functionality. Then the user needs to call the scale_x_continous() /scale_x_continous() function with the plotted ggplot2 plot with the required parameters to change the axis intervals to a log scale in the R programming language."
},
{
"code": null,
"e": 2782,
"s": 2676,
"text": "scale_x_continuous() / scale_y_continuous() functions are used to for continuous position scales (x & y)."
},
{
"code": null,
"e": 2790,
"s": 2782,
"text": "Syntax:"
},
{
"code": null,
"e": 2833,
"s": 2790,
"text": "scale_x_continuous(..., expand = waiver())"
},
{
"code": null,
"e": 2876,
"s": 2833,
"text": "scale_y_continuous(..., expand = waiver())"
},
{
"code": null,
"e": 2888,
"s": 2876,
"text": "Parameters:"
},
{
"code": null,
"e": 2979,
"s": 2888,
"text": "...: common continuous scale parameters: name, breaks, labels, na.value, limits and trans."
},
{
"code": null,
"e": 3074,
"s": 2979,
"text": "expand: a numeric vector of length two giving multiplicative and additive expansion constants."
},
{
"code": null,
"e": 3096,
"s": 3074,
"text": "Example: Initial plot"
},
{
"code": null,
"e": 3098,
"s": 3096,
"text": "R"
},
{
"code": "library(ggplot2) gfg<-data.frame(x=c(8,9,6,5,8,5,1,7,3,5), y=c(9,6,5,4,2,5,6,7,4,1)) ggplot(data=gfg,aes(x=x, y=y)) + geom_point()",
"e": 3246,
"s": 3098,
"text": null
},
{
"code": null,
"e": 3254,
"s": 3246,
"text": "Output:"
},
{
"code": null,
"e": 3285,
"s": 3254,
"text": "Example: Change axis intervals"
},
{
"code": null,
"e": 3287,
"s": 3285,
"text": "R"
},
{
"code": "library(ggplot2) gfg<-data.frame(x=c(8,9,6,5,8,5,1,7,3,5), y=c(9,6,5,4,2,5,6,7,4,1)) ggplot(data=gfg,aes(x=x, y=y)) + geom_point()+scale_y_continuous(trans = 'log10')",
"e": 3471,
"s": 3287,
"text": null
},
{
"code": null,
"e": 3479,
"s": 3471,
"text": "Output:"
},
{
"code": null,
"e": 3486,
"s": 3479,
"text": "Picked"
},
{
"code": null,
"e": 3495,
"s": 3486,
"text": "R-Charts"
},
{
"code": null,
"e": 3504,
"s": 3495,
"text": "R-Graphs"
},
{
"code": null,
"e": 3512,
"s": 3504,
"text": "R-plots"
},
{
"code": null,
"e": 3523,
"s": 3512,
"text": "R Language"
},
{
"code": null,
"e": 3621,
"s": 3523,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3673,
"s": 3621,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3731,
"s": 3673,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3766,
"s": 3731,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3804,
"s": 3766,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3821,
"s": 3804,
"text": "R - if statement"
},
{
"code": null,
"e": 3870,
"s": 3821,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3907,
"s": 3870,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3950,
"s": 3907,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3987,
"s": 3950,
"text": "How to import an Excel File into R ?"
}
] |
Merge multiple CSV files using R | 06 Jun, 2021
In this article, we will be looking at the approach to merge multiple CSV files in the R programming language.
In this approach to merge multiple CSV files, the user needs to install and import three different packages namely- dplyr,plyr, and readr in the R programming language console to call the functions which are list.files(), lapply(), and bind_rows() from these packages and pass the required parameters to these functions to merge the given multiple CSV files to a single data frame in the R programming language.
list.files() function produces a character vector of the names of files or directories in the named directory.
Syntax:
list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
lapply() function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.
Syntax:
lapply(X, FUN, ...)
bind_rows() function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one.
Syntax:
bind_rows(..., .id = NULL)
Folder in Use:
To actually merge multiple CSV/Excel files as one dataframe first the required packages are imported and then list of files are read and joined together.
Example:
R
library("dplyr") library("plyr") library("readr") gfg_data <- list.files(path = "C:/Users/Geetansh Sahni/Documents/R/Data", pattern = "*.csv", full.names = TRUE) %>% lapply(read_csv) %>% bind_rows gfg_data
Output:
Picked
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 139,
"s": 28,
"text": "In this article, we will be looking at the approach to merge multiple CSV files in the R programming language."
},
{
"code": null,
"e": 551,
"s": 139,
"text": "In this approach to merge multiple CSV files, the user needs to install and import three different packages namely- dplyr,plyr, and readr in the R programming language console to call the functions which are list.files(), lapply(), and bind_rows() from these packages and pass the required parameters to these functions to merge the given multiple CSV files to a single data frame in the R programming language."
},
{
"code": null,
"e": 662,
"s": 551,
"text": "list.files() function produces a character vector of the names of files or directories in the named directory."
},
{
"code": null,
"e": 670,
"s": 662,
"text": "Syntax:"
},
{
"code": null,
"e": 823,
"s": 670,
"text": "list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)"
},
{
"code": null,
"e": 968,
"s": 823,
"text": "lapply() function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X."
},
{
"code": null,
"e": 976,
"s": 968,
"text": "Syntax:"
},
{
"code": null,
"e": 996,
"s": 976,
"text": "lapply(X, FUN, ...)"
},
{
"code": null,
"e": 1155,
"s": 996,
"text": "bind_rows() function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one."
},
{
"code": null,
"e": 1163,
"s": 1155,
"text": "Syntax:"
},
{
"code": null,
"e": 1190,
"s": 1163,
"text": "bind_rows(..., .id = NULL)"
},
{
"code": null,
"e": 1205,
"s": 1190,
"text": "Folder in Use:"
},
{
"code": null,
"e": 1359,
"s": 1205,
"text": "To actually merge multiple CSV/Excel files as one dataframe first the required packages are imported and then list of files are read and joined together."
},
{
"code": null,
"e": 1368,
"s": 1359,
"text": "Example:"
},
{
"code": null,
"e": 1370,
"s": 1368,
"text": "R"
},
{
"code": "library(\"dplyr\") library(\"plyr\") library(\"readr\") gfg_data <- list.files(path = \"C:/Users/Geetansh Sahni/Documents/R/Data\", pattern = \"*.csv\", full.names = TRUE) %>% lapply(read_csv) %>% bind_rows gfg_data ",
"e": 1802,
"s": 1370,
"text": null
},
{
"code": null,
"e": 1810,
"s": 1802,
"text": "Output:"
},
{
"code": null,
"e": 1817,
"s": 1810,
"text": "Picked"
},
{
"code": null,
"e": 1823,
"s": 1817,
"text": "R-CSV"
},
{
"code": null,
"e": 1834,
"s": 1823,
"text": "R Language"
},
{
"code": null,
"e": 1932,
"s": 1834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1984,
"s": 1932,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2042,
"s": 1984,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2077,
"s": 2042,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2115,
"s": 2077,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2164,
"s": 2115,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2181,
"s": 2164,
"text": "R - if statement"
},
{
"code": null,
"e": 2218,
"s": 2181,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 2261,
"s": 2218,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2298,
"s": 2261,
"text": "How to import an Excel File into R ?"
}
] |
Minimum Steps to obtain N from 1 by the given operations | 05 Jul, 2022
Given an integer N, the task is to find the minimum number of operations needed to obtain the number N starting from 1. Below are the operations:
Add 1 to the current number.
Multiply the current number by 2.
Multiply the current number by 3.
Print the minimum number of operations required and the corresponding sequence to obtain N.
Examples:
Input: N = 3 Output: 1 1 3 Explanation: Operation 1: Multiply 1 * 3 = 3. Hence, only 1 operation is required.
Input: N = 5 Output: 3 1 2 4 5 Explanation: The minimum required operations are as follows: 1 * 2 -> 2 2 * 2 -> 4 4 + 1 -> 5
Recursive Approach: Recursively generate every possible combination to reduce N to 1 and calculate the number of operations required. Finally, after exhausting all possible combinations, print the sequence that required the minimum number of operations.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; vector<int> find_sequence(int n){ // Base Case if (n == 1) return {1, -1}; // Recursive Call for n-1 auto arr = find_sequence(n - 1); vector<int> ans = {arr[0] + 1, n - 1}; // Check if n is divisible by 2 if (n % 2 == 0) { vector<int> div_by_2 = find_sequence(n / 2); if (div_by_2[0] < ans[0]) ans = {div_by_2[0] + 1, n / 2}; } // Check if n is divisible by 3 if (n % 3 == 0) { vector<int> div_by_3 = find_sequence(n / 3); if (div_by_3[0] < ans[0]) vector<int> ans = {div_by_3[0] + 1, n / 3}; } // Returns a tuple (a, b), where // a: Minimum steps to obtain x from 1 // b: Previous number return ans;} // Function that find the optimal// solutionvector<int> find_solution(int n){ auto a = find_sequence(n); // Print the length cout << a[0] << endl; vector<int> sequence; sequence.push_back(n); //Exit condition for loop = -1 //when n has reached 1 while (a[1] != -1) { sequence.push_back(a[1]); auto arr = find_sequence(a[1]); a[1] = arr[1]; } // Return the sequence // in reverse order reverse(sequence.begin(), sequence.end()); return sequence;} // Driver Codeint main(){ // Given N int n = 5; // Function call auto i = find_solution(n); for(int j : i) cout << j << " ";} // This code is contributed by mohit kumar 29
// Java program to implement// the above approachimport java.util.*;import java.util.Collections;import java.util.Vector; //Vector<Integer> v = new Vector<Integer>(n); class GFG{ static Vector<Integer> find_sequence(int n){ Vector<Integer> temp = new Vector<Integer>(); temp.add(1); temp.add(-1); // Base Case if (n == 1) return temp; // Recursive Call for n-1 Vector<Integer> arr = find_sequence(n - 1); Vector<Integer> ans = new Vector<Integer>(n); ans.add(arr.get(0) + 1); ans.add(n - 1); // Check if n is divisible by 2 if (n % 2 == 0) { Vector<Integer> div_by_2 = find_sequence(n / 2); if (div_by_2.get(0) < ans.get(0)) { ans.clear(); ans.add(div_by_2.get(0) + 1); ans.add(n / 2); } } // Check if n is divisible by 3 if (n % 3 == 0) { Vector<Integer> div_by_3 = find_sequence(n / 3); if (div_by_3.get(0) < ans.get(0)) { ans.clear(); ans.add(div_by_3.get(0) + 1); ans.add(n / 3); } } // Returns a tuple (a, b), where // a: Minimum steps to obtain x from 1 // b: Previous number return ans;} // Function that find the optimal// solutionstatic Vector<Integer> find_solution(int n){ Vector<Integer> a = find_sequence(n); // Print the length System.out.println(a.get(0)); Vector<Integer> sequence = new Vector<Integer>(); sequence.add(n); // Exit condition for loop = -1 // when n has reached 1 while (a.get(1) != -1) { sequence.add(a.get(1)); Vector<Integer> arr = find_sequence(a.get(1)); a.set(1, arr.get(1)); } // Return the sequence // in reverse order Collections.reverse(sequence); return sequence;} // Driver Codepublic static void main(String args[]){ // Given N int n = 5; // Function call Vector<Integer> res = find_solution(n); for(int i = 0; i < res.size(); i++) { System.out.print(res.get(i) + " "); }}} // This code is contributed by Surendra_Gangwar
# Python3 program to implement# the above approach def find_sequence(n): # Base Case if n == 1: return 1, -1 # Recursive Call for n-1 ans = (find_sequence(n - 1)[0] + 1, n - 1) # Check if n is divisible by 2 if n % 2 == 0: div_by_2 = find_sequence(n // 2) if div_by_2[0] < ans[0]: ans = (div_by_2[0] + 1, n // 2) # Check if n is divisible by 3 if n % 3 == 0: div_by_3 = find_sequence(n // 3) if div_by_3[0] < ans[0]: ans = (div_by_3[0] + 1, n // 3) # Returns a tuple (a, b), where # a: Minimum steps to obtain x from 1 # b: Previous number return ans # Function that find the optimal# solutiondef find_solution(n): a, b = find_sequence(n) # Print the length print(a) sequence = [] sequence.append(n) # Exit condition for loop = -1 # when n has reached 1 while b != -1: sequence.append(b) _, b = find_sequence(b) # Return the sequence # in reverse order return sequence[::-1] # Driver Code # Given Nn = 5 # Function Callprint(*find_solution(n))
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ static List<int> find_sequence(int n){ List<int> temp = new List<int>(); temp.Add(1); temp.Add(-1); // Base Case if (n == 1) return temp; // Recursive Call for n-1 List<int> arr = find_sequence(n - 1); List<int> ans = new List<int>(n); ans.Add(arr[0] + 1); ans.Add(n - 1); // Check if n is divisible by 2 if (n % 2 == 0) { List<int> div_by_2 = find_sequence(n / 2); if (div_by_2[0] < ans[0]) { ans.Clear(); ans.Add(div_by_2[0] + 1); ans.Add(n / 2); } } // Check if n is divisible // by 3 if (n % 3 == 0) { List<int> div_by_3 = find_sequence(n / 3); if (div_by_3[0] < ans[0]) { ans.Clear(); ans.Add(div_by_3[0] + 1); ans.Add(n / 3); } } // Returns a tuple (a, b), where // a: Minimum steps to obtain x // from 1 b: Previous number return ans;} // Function that find the optimal// solutionstatic List<int> find_solution(int n){ List<int> a = find_sequence(n); // Print the length Console.WriteLine(a[0]); List<int> sequence = new List<int>(); sequence.Add(n); // Exit condition for loop = -1 // when n has reached 1 while (a[1] != -1) { sequence.Add(a[1]); List<int> arr = find_sequence(a[1]); a.Insert(1, arr[1]); } // Return the sequence // in reverse order sequence.Reverse(); return sequence;} // Driver Codepublic static void Main(String []args){ // Given N int n = 5; // Function call List<int> res = find_solution(n); for(int i = 0; i < res.Count; i++) { Console.Write(res[i] + " "); }}} // This code is contributed by shikhasingrajput
<script> // JavaScript program to implement// the above approach function find_sequence(n){ // Base Case if (n == 1) return [1, -1]; // Recursive Call for n-1 var arr = find_sequence(n - 1); var ans = [arr[0] + 1, n - 1]; // Check if n is divisible by 2 if (n % 2 == 0) { var div_by_2 = find_sequence(n / 2); if (div_by_2[0] < ans[0]) ans = [div_by_2[0] + 1, n / 2]; } // Check if n is divisible by 3 if (n % 3 == 0) { var div_by_3 = find_sequence(n / 3); if (div_by_3[0] < ans[0]) var ans = [div_by_3[0] + 1, n / 3]; } // Returns a tuple (a, b), where // a: Minimum steps to obtain x from 1 // b: Previous number return ans;} // Function that find the optimal// solutionfunction find_solution(n){ var a = find_sequence(n); // Print the length document.write( a[0] + "<br>"); var sequence = []; sequence.push(n); //Exit condition for loop = -1 //when n has reached 1 while (a[1] != -1) { sequence.push(a[1]); var arr = find_sequence(a[1]); a[1] = arr[1]; } // Return the sequence // in reverse order sequence.reverse(); return sequence;} // Driver Code// Given Nvar n = 5; // Function callvar i = find_solution(n); i.forEach(j => { document.write(j + " ");}); </script>
4
1 2 4 5
Time Complexity: T(N) = T(N-1) + T(N/2) + T(N/3), where N is given integer. This algorithm results in an exponential time complexity.
Auxiliary Space: O(1)
Recursion With Memoization Approach: The above approach can be optimized by memoizing the overlapping subproblems.
Below is the implementation of the above approach:
Python3
# Python3 program to implement# the above approach # Function to find the sequence# with given operationsdef find_sequence(n, map): # Base Case if n == 1: return 1, -1 # Check if the subproblem # is already computed or not if n in map: return map[n] # Recursive Call for n-1 ans = (find_sequence(n - 1, map)[0]\ + 1, n - 1) # Check if n is divisible by 2 if n % 2 == 0: div_by_2 = find_sequence(n // 2, map) if div_by_2[0] < ans[0]: ans = (div_by_2[0] + 1, n // 2) # Check if n is divisible by 3 if n % 3 == 0: div_by_3 = find_sequence(n // 3, map) if div_by_3[0] < ans[0]: ans = (div_by_3[0] + 1, n // 3) # Memoize map[n] = ans # Returns a tuple (a, b), where # a: Minimum steps to obtain x from 1 # b: Previous state return ans # Function to check if a sequence can# be obtained with given operationsdef find_solution(n): # Stores the computed # subproblems map = {} a, b = find_sequence(n, map) # Return a sequence in # reverse order print(a) sequence = [] sequence.append(n) # If n has reached 1 while b != -1: sequence.append(b) _, b = find_sequence(b, map) # Return sequence in reverse order return sequence[::-1] # Driver Code # Given Nn = 5 # Function Callprint(*find_solution(n))
4
1 2 4 5
Time Complexity: O(N) Auxiliary Space: O(N)
Iterative Dynamic Programming Approach: The above approach can be further optimized by using an iterative DP approach. Follow the steps below to solve the problem:
Create an array dp[] to store the minimum length of sequence that is required to compute 1 to N by the three available operations.Once the dp[] array is computed, obtain the sequence by traversing the dp[] array from N to 1.
Create an array dp[] to store the minimum length of sequence that is required to compute 1 to N by the three available operations.
Once the dp[] array is computed, obtain the sequence by traversing the dp[] array from N to 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to generate// the minimum sequencevoid find_sequence(int n){ // Stores the values for the // minimum length of sequences int dp[n + 1]; memset(dp, 0, sizeof(dp)); // Base Case dp[1] = 1; // Loop to build up the dp[] // array from 1 to n for(int i = 1; i < n + 1; i++) { if (dp[i] != 0) { // If i + 1 is within limits if (i + 1 < n + 1 && (dp[i + 1] == 0 || dp[i + 1] > dp[i] + 1)) { // Update the state of i + 1 // in dp[] array to minimum dp[i + 1] = dp[i] + 1; } // If i * 2 is within limits if (i * 2 < n + 1 && (dp[i * 2] == 0 || dp[i * 2] > dp[i] + 1)) { // Update the state of i * 2 // in dp[] array to minimum dp[i * 2] = dp[i] + 1; } // If i * 3 is within limits if (i * 3 < n + 1 && (dp[i * 3] == 0 || dp[i * 3] > dp[i] + 1)) { // Update the state of i * 3 // in dp[] array to minimum dp[i * 3] = dp[i] + 1; } } } // Generate the sequence by // traversing the array vector<int> sequence; while (n >= 1) { // Append n to the sequence sequence.push_back(n); // If the value of n in dp // is obtained from n - 1: if (dp[n - 1] == dp[n] - 1) { n--; } // If the value of n in dp[] // is obtained from n / 2: else if (n % 2 == 0 && dp[(int)floor(n / 2)] == dp[n] - 1) { n = (int)floor(n / 2); } // If the value of n in dp[] // is obtained from n / 3: else if (n % 3 == 0 && dp[(int)floor(n / 3)] == dp[n] - 1) { n = (int)floor(n / 3); } } // Print the sequence // in reverse order reverse(sequence.begin(), sequence.end()); // Print the length of // the minimal sequence cout << sequence.size() << endl; for(int i = 0; i < sequence.size(); i++) { cout << sequence[i] << " "; }} // Driver codeint main(){ // Given Number N int n = 5; // Function Call find_sequence(n); return 0;} // This code is contributed by divyeshrabadiya07
// Java program to implement// the above approachimport java.io.*;import java.util.*; class GFG{ // Function to generate// the minimum sequencepublic static void find_sequence(int n){ // Stores the values for the // minimum length of sequences int[] dp = new int[n + 1]; Arrays.fill(dp, 0); // Base Case dp[1] = 1; // Loop to build up the dp[] // array from 1 to n for(int i = 1; i < n + 1; i++) { if (dp[i] != 0) { // If i + 1 is within limits if (i + 1 < n + 1 && (dp[i + 1] == 0 || dp[i + 1] > dp[i] + 1)) { // Update the state of i + 1 // in dp[] array to minimum dp[i + 1] = dp[i] + 1; } // If i * 2 is within limits if (i * 2 < n + 1 && (dp[i * 2] == 0 || dp[i * 2] > dp[i] + 1)) { // Update the state of i * 2 // in dp[] array to minimum dp[i * 2] = dp[i] + 1; } // If i * 3 is within limits if (i * 3 < n + 1 && (dp[i * 3] == 0 || dp[i * 3] > dp[i] + 1)) { // Update the state of i * 3 // in dp[] array to minimum dp[i * 3] = dp[i] + 1; } } } // Generate the sequence by // traversing the array List<Integer> sequence = new ArrayList<Integer>(); while (n >= 1) { // Append n to the sequence sequence.add(n); // If the value of n in dp // is obtained from n - 1: if (dp[n - 1] == dp[n] - 1) { n--; } // If the value of n in dp[] // is obtained from n / 2: else if (n % 2 == 0 && dp[(int)Math.floor(n / 2)] == dp[n] - 1) { n = (int)Math.floor(n / 2); } // If the value of n in dp[] // is obtained from n / 3: else if (n % 3 == 0 && dp[(int)Math.floor(n / 3)] == dp[n] - 1) { n = (int)Math.floor(n / 3); } } // Print the sequence // in reverse order Collections.reverse(sequence); // Print the length of // the minimal sequence System.out.println(sequence.size()); for(int i = 0; i < sequence.size(); i++) { System.out.print(sequence.get(i) + " "); }} // Driver Codepublic static void main (String[] args){ // Given Number N int n = 5; // Function Call find_sequence(n);}} // This code is contributed by avanitrachhadiya2155
# Python3 program to implement# the above approach # Function to generate# the minimum sequencedef find_sequence(n): # Stores the values for the # minimum length of sequences dp = [0 for _ in range(n + 1)] # Base Case dp[1] = 1 # Loop to build up the dp[] # array from 1 to n for i in range(1, n + 1): if dp[i] != 0: # If i + 1 is within limits if i + 1 < n + 1 and (dp[i + 1] == 0 \ or dp[i + 1] > dp[i] + 1): # Update the state of i + 1 # in dp[] array to minimum dp[i + 1] = dp[i] + 1 # If i * 2 is within limits if i * 2 < n + 1 and (dp[i * 2] == 0 \ or dp[i * 2] > dp[i] + 1): # Update the state of i * 2 # in dp[] array to minimum dp[i * 2] = dp[i] + 1 # If i * 3 is within limits if i * 3 < n + 1 and (dp[i * 3] == 0 \ or dp[i * 3] > dp[i] + 1): # Update the state of i * 3 # in dp[] array to minimum dp[i * 3] = dp[i] + 1 # Generate the sequence by # traversing the array sequence = [] while n >= 1: # Append n to the sequence sequence.append(n) # If the value of n in dp # is obtained from n - 1: if dp[n - 1] == dp[n] - 1: n = n - 1 # If the value of n in dp[] # is obtained from n / 2: elif n % 2 == 0 \ and dp[n // 2] == dp[n] - 1: n = n // 2 # If the value of n in dp[] # is obtained from n / 3: elif n % 3 == 0 \ and dp[n // 3] == dp[n] - 1: n = n // 3 # Return the sequence # in reverse order return sequence[::-1] # Driver Code # Given Number Nn = 5 # Function Callsequence = find_sequence(n) # Print the length of# the minimal sequenceprint(len(sequence)) # Print the sequenceprint(*sequence)
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to generate // the minimum sequence public static void find_sequence(int n) { // Stores the values for the // minimum length of sequences int[] dp = new int[n + 1]; Array.Fill(dp, 0); // Base Case dp[1] = 1; // Loop to build up the dp[] // array from 1 to n for(int i = 1; i < n + 1; i++) { if(dp[i] != 0) { // If i + 1 is within limits if(i + 1 < n + 1 && (dp[i + 1] == 0 || dp[i + 1] > dp[i] + 1)) { // Update the state of i + 1 // in dp[] array to minimum dp[i + 1] = dp[i] + 1; } // If i * 2 is within limits if(i * 2 < n + 1 && (dp[i * 2] == 0 || dp[i * 2] > dp[i] + 1)) { // Update the state of i * 2 // in dp[] array to minimum dp[i * 2] = dp[i] + 1; } // If i * 3 is within limits if(i * 3 < n + 1 && (dp[i * 3] == 0 || dp[i * 3] > dp[i] + 1)) { // Update the state of i * 3 // in dp[] array to minimum dp[i * 3] = dp[i] + 1; } } } // Generate the sequence by // traversing the array List<int> sequence = new List<int>(); while(n >= 1) { // Append n to the sequence sequence.Add(n); // If the value of n in dp // is obtained from n - 1: if(dp[n - 1] == dp[n] - 1) { n--; } // If the value of n in dp[] // is obtained from n / 2: else if(n % 2 == 0 && dp[(int)Math.Floor((decimal)n / 2)] == dp[n] - 1) { n = (int)Math.Floor((decimal)n / 2); } // If the value of n in dp[] // is obtained from n / 3: else if(n % 3 == 0 && dp[(int)Math.Floor((decimal)n / 3)] == dp[n] - 1) { n = (int)Math.Floor((decimal)n / 3); } } // Print the sequence // in reverse order sequence.Reverse(); // Print the length of // the minimal sequence Console.WriteLine(sequence.Count); for(int i = 0; i < sequence.Count; i++) { Console.Write(sequence[i] + " "); } } // Driver Code static public void Main () { // Given Number N int n = 5; // Function Call find_sequence(n); }} // This code is contributed by rag2127
<script>// Javascript program to implement// the above approach // Function to generate// the minimum sequencefunction find_sequence(n){ // Stores the values for the // minimum length of sequences let dp = new Array(n + 1); for(let i=0;i<n+1;i++) { dp[i]=0; } // Base Case dp[1] = 1; // Loop to build up the dp[] // array from 1 to n for(let i = 1; i < n + 1; i++) { if (dp[i] != 0) { // If i + 1 is within limits if (i + 1 < n + 1 && (dp[i + 1] == 0 || dp[i + 1] > dp[i] + 1)) { // Update the state of i + 1 // in dp[] array to minimum dp[i + 1] = dp[i] + 1; } // If i * 2 is within limits if (i * 2 < n + 1 && (dp[i * 2] == 0 || dp[i * 2] > dp[i] + 1)) { // Update the state of i * 2 // in dp[] array to minimum dp[i * 2] = dp[i] + 1; } // If i * 3 is within limits if (i * 3 < n + 1 && (dp[i * 3] == 0 || dp[i * 3] > dp[i] + 1)) { // Update the state of i * 3 // in dp[] array to minimum dp[i * 3] = dp[i] + 1; } } } // Generate the sequence by // traversing the array let sequence = []; while (n >= 1) { // Append n to the sequence sequence.push(n); // If the value of n in dp // is obtained from n - 1: if (dp[n - 1] == dp[n] - 1) { n--; } // If the value of n in dp[] // is obtained from n / 2: else if (n % 2 == 0 && dp[Math.floor(n / 2)] == dp[n] - 1) { n = Math.floor(n / 2); } // If the value of n in dp[] // is obtained from n / 3: else if (n % 3 == 0 && dp[Math.floor(n / 3)] == dp[n] - 1) { n = Math.floor(n / 3); } } // Print the sequence // in reverse order sequence.reverse(); // Print the length of // the minimal sequence document.write(sequence.length+"<br>"); for(let i = 0; i < sequence.length; i++) { document.write(sequence[i] + " "); }} // Driver Codelet n = 5; // Function Callfind_sequence(n); // This code is contributed by unknown2108</script>
4
1 3 4 5
Time Complexity: O(N) Auxiliary Space: O(N)
mohit kumar 29
SURENDRA_GANGWAR
khushboogoyal499
shikhasingrajput
avanitrachhadiya2155
rag2127
divyeshrabadiya07
rrrtnx
unknown2108
vinayedula
Memoization
Dynamic Programming
Mathematical
Recursion
Dynamic Programming
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 199,
"s": 52,
"text": "Given an integer N, the task is to find the minimum number of operations needed to obtain the number N starting from 1. Below are the operations: "
},
{
"code": null,
"e": 228,
"s": 199,
"text": "Add 1 to the current number."
},
{
"code": null,
"e": 262,
"s": 228,
"text": "Multiply the current number by 2."
},
{
"code": null,
"e": 296,
"s": 262,
"text": "Multiply the current number by 3."
},
{
"code": null,
"e": 388,
"s": 296,
"text": "Print the minimum number of operations required and the corresponding sequence to obtain N."
},
{
"code": null,
"e": 400,
"s": 388,
"text": "Examples: "
},
{
"code": null,
"e": 510,
"s": 400,
"text": "Input: N = 3 Output: 1 1 3 Explanation: Operation 1: Multiply 1 * 3 = 3. Hence, only 1 operation is required."
},
{
"code": null,
"e": 636,
"s": 510,
"text": "Input: N = 5 Output: 3 1 2 4 5 Explanation: The minimum required operations are as follows: 1 * 2 -> 2 2 * 2 -> 4 4 + 1 -> 5 "
},
{
"code": null,
"e": 890,
"s": 636,
"text": "Recursive Approach: Recursively generate every possible combination to reduce N to 1 and calculate the number of operations required. Finally, after exhausting all possible combinations, print the sequence that required the minimum number of operations."
},
{
"code": null,
"e": 943,
"s": 890,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 947,
"s": 943,
"text": "C++"
},
{
"code": null,
"e": 952,
"s": 947,
"text": "Java"
},
{
"code": null,
"e": 960,
"s": 952,
"text": "Python3"
},
{
"code": null,
"e": 963,
"s": 960,
"text": "C#"
},
{
"code": null,
"e": 974,
"s": 963,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; vector<int> find_sequence(int n){ // Base Case if (n == 1) return {1, -1}; // Recursive Call for n-1 auto arr = find_sequence(n - 1); vector<int> ans = {arr[0] + 1, n - 1}; // Check if n is divisible by 2 if (n % 2 == 0) { vector<int> div_by_2 = find_sequence(n / 2); if (div_by_2[0] < ans[0]) ans = {div_by_2[0] + 1, n / 2}; } // Check if n is divisible by 3 if (n % 3 == 0) { vector<int> div_by_3 = find_sequence(n / 3); if (div_by_3[0] < ans[0]) vector<int> ans = {div_by_3[0] + 1, n / 3}; } // Returns a tuple (a, b), where // a: Minimum steps to obtain x from 1 // b: Previous number return ans;} // Function that find the optimal// solutionvector<int> find_solution(int n){ auto a = find_sequence(n); // Print the length cout << a[0] << endl; vector<int> sequence; sequence.push_back(n); //Exit condition for loop = -1 //when n has reached 1 while (a[1] != -1) { sequence.push_back(a[1]); auto arr = find_sequence(a[1]); a[1] = arr[1]; } // Return the sequence // in reverse order reverse(sequence.begin(), sequence.end()); return sequence;} // Driver Codeint main(){ // Given N int n = 5; // Function call auto i = find_solution(n); for(int j : i) cout << j << \" \";} // This code is contributed by mohit kumar 29",
"e": 2522,
"s": 974,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;import java.util.Collections;import java.util.Vector; //Vector<Integer> v = new Vector<Integer>(n); class GFG{ static Vector<Integer> find_sequence(int n){ Vector<Integer> temp = new Vector<Integer>(); temp.add(1); temp.add(-1); // Base Case if (n == 1) return temp; // Recursive Call for n-1 Vector<Integer> arr = find_sequence(n - 1); Vector<Integer> ans = new Vector<Integer>(n); ans.add(arr.get(0) + 1); ans.add(n - 1); // Check if n is divisible by 2 if (n % 2 == 0) { Vector<Integer> div_by_2 = find_sequence(n / 2); if (div_by_2.get(0) < ans.get(0)) { ans.clear(); ans.add(div_by_2.get(0) + 1); ans.add(n / 2); } } // Check if n is divisible by 3 if (n % 3 == 0) { Vector<Integer> div_by_3 = find_sequence(n / 3); if (div_by_3.get(0) < ans.get(0)) { ans.clear(); ans.add(div_by_3.get(0) + 1); ans.add(n / 3); } } // Returns a tuple (a, b), where // a: Minimum steps to obtain x from 1 // b: Previous number return ans;} // Function that find the optimal// solutionstatic Vector<Integer> find_solution(int n){ Vector<Integer> a = find_sequence(n); // Print the length System.out.println(a.get(0)); Vector<Integer> sequence = new Vector<Integer>(); sequence.add(n); // Exit condition for loop = -1 // when n has reached 1 while (a.get(1) != -1) { sequence.add(a.get(1)); Vector<Integer> arr = find_sequence(a.get(1)); a.set(1, arr.get(1)); } // Return the sequence // in reverse order Collections.reverse(sequence); return sequence;} // Driver Codepublic static void main(String args[]){ // Given N int n = 5; // Function call Vector<Integer> res = find_solution(n); for(int i = 0; i < res.size(); i++) { System.out.print(res.get(i) + \" \"); }}} // This code is contributed by Surendra_Gangwar",
"e": 4660,
"s": 2522,
"text": null
},
{
"code": "# Python3 program to implement# the above approach def find_sequence(n): # Base Case if n == 1: return 1, -1 # Recursive Call for n-1 ans = (find_sequence(n - 1)[0] + 1, n - 1) # Check if n is divisible by 2 if n % 2 == 0: div_by_2 = find_sequence(n // 2) if div_by_2[0] < ans[0]: ans = (div_by_2[0] + 1, n // 2) # Check if n is divisible by 3 if n % 3 == 0: div_by_3 = find_sequence(n // 3) if div_by_3[0] < ans[0]: ans = (div_by_3[0] + 1, n // 3) # Returns a tuple (a, b), where # a: Minimum steps to obtain x from 1 # b: Previous number return ans # Function that find the optimal# solutiondef find_solution(n): a, b = find_sequence(n) # Print the length print(a) sequence = [] sequence.append(n) # Exit condition for loop = -1 # when n has reached 1 while b != -1: sequence.append(b) _, b = find_sequence(b) # Return the sequence # in reverse order return sequence[::-1] # Driver Code # Given Nn = 5 # Function Callprint(*find_solution(n))",
"e": 5763,
"s": 4660,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ static List<int> find_sequence(int n){ List<int> temp = new List<int>(); temp.Add(1); temp.Add(-1); // Base Case if (n == 1) return temp; // Recursive Call for n-1 List<int> arr = find_sequence(n - 1); List<int> ans = new List<int>(n); ans.Add(arr[0] + 1); ans.Add(n - 1); // Check if n is divisible by 2 if (n % 2 == 0) { List<int> div_by_2 = find_sequence(n / 2); if (div_by_2[0] < ans[0]) { ans.Clear(); ans.Add(div_by_2[0] + 1); ans.Add(n / 2); } } // Check if n is divisible // by 3 if (n % 3 == 0) { List<int> div_by_3 = find_sequence(n / 3); if (div_by_3[0] < ans[0]) { ans.Clear(); ans.Add(div_by_3[0] + 1); ans.Add(n / 3); } } // Returns a tuple (a, b), where // a: Minimum steps to obtain x // from 1 b: Previous number return ans;} // Function that find the optimal// solutionstatic List<int> find_solution(int n){ List<int> a = find_sequence(n); // Print the length Console.WriteLine(a[0]); List<int> sequence = new List<int>(); sequence.Add(n); // Exit condition for loop = -1 // when n has reached 1 while (a[1] != -1) { sequence.Add(a[1]); List<int> arr = find_sequence(a[1]); a.Insert(1, arr[1]); } // Return the sequence // in reverse order sequence.Reverse(); return sequence;} // Driver Codepublic static void Main(String []args){ // Given N int n = 5; // Function call List<int> res = find_solution(n); for(int i = 0; i < res.Count; i++) { Console.Write(res[i] + \" \"); }}} // This code is contributed by shikhasingrajput",
"e": 7470,
"s": 5763,
"text": null
},
{
"code": "<script> // JavaScript program to implement// the above approach function find_sequence(n){ // Base Case if (n == 1) return [1, -1]; // Recursive Call for n-1 var arr = find_sequence(n - 1); var ans = [arr[0] + 1, n - 1]; // Check if n is divisible by 2 if (n % 2 == 0) { var div_by_2 = find_sequence(n / 2); if (div_by_2[0] < ans[0]) ans = [div_by_2[0] + 1, n / 2]; } // Check if n is divisible by 3 if (n % 3 == 0) { var div_by_3 = find_sequence(n / 3); if (div_by_3[0] < ans[0]) var ans = [div_by_3[0] + 1, n / 3]; } // Returns a tuple (a, b), where // a: Minimum steps to obtain x from 1 // b: Previous number return ans;} // Function that find the optimal// solutionfunction find_solution(n){ var a = find_sequence(n); // Print the length document.write( a[0] + \"<br>\"); var sequence = []; sequence.push(n); //Exit condition for loop = -1 //when n has reached 1 while (a[1] != -1) { sequence.push(a[1]); var arr = find_sequence(a[1]); a[1] = arr[1]; } // Return the sequence // in reverse order sequence.reverse(); return sequence;} // Driver Code// Given Nvar n = 5; // Function callvar i = find_solution(n); i.forEach(j => { document.write(j + \" \");}); </script>",
"e": 8831,
"s": 7470,
"text": null
},
{
"code": null,
"e": 8841,
"s": 8831,
"text": "4\n1 2 4 5"
},
{
"code": null,
"e": 8978,
"s": 8843,
"text": "Time Complexity: T(N) = T(N-1) + T(N/2) + T(N/3), where N is given integer. This algorithm results in an exponential time complexity. "
},
{
"code": null,
"e": 9000,
"s": 8978,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9115,
"s": 9000,
"text": "Recursion With Memoization Approach: The above approach can be optimized by memoizing the overlapping subproblems."
},
{
"code": null,
"e": 9168,
"s": 9115,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 9176,
"s": 9168,
"text": "Python3"
},
{
"code": "# Python3 program to implement# the above approach # Function to find the sequence# with given operationsdef find_sequence(n, map): # Base Case if n == 1: return 1, -1 # Check if the subproblem # is already computed or not if n in map: return map[n] # Recursive Call for n-1 ans = (find_sequence(n - 1, map)[0]\\ + 1, n - 1) # Check if n is divisible by 2 if n % 2 == 0: div_by_2 = find_sequence(n // 2, map) if div_by_2[0] < ans[0]: ans = (div_by_2[0] + 1, n // 2) # Check if n is divisible by 3 if n % 3 == 0: div_by_3 = find_sequence(n // 3, map) if div_by_3[0] < ans[0]: ans = (div_by_3[0] + 1, n // 3) # Memoize map[n] = ans # Returns a tuple (a, b), where # a: Minimum steps to obtain x from 1 # b: Previous state return ans # Function to check if a sequence can# be obtained with given operationsdef find_solution(n): # Stores the computed # subproblems map = {} a, b = find_sequence(n, map) # Return a sequence in # reverse order print(a) sequence = [] sequence.append(n) # If n has reached 1 while b != -1: sequence.append(b) _, b = find_sequence(b, map) # Return sequence in reverse order return sequence[::-1] # Driver Code # Given Nn = 5 # Function Callprint(*find_solution(n))",
"e": 10549,
"s": 9176,
"text": null
},
{
"code": null,
"e": 10559,
"s": 10549,
"text": "4\n1 2 4 5"
},
{
"code": null,
"e": 10605,
"s": 10561,
"text": "Time Complexity: O(N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 10771,
"s": 10605,
"text": "Iterative Dynamic Programming Approach: The above approach can be further optimized by using an iterative DP approach. Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 10996,
"s": 10771,
"text": "Create an array dp[] to store the minimum length of sequence that is required to compute 1 to N by the three available operations.Once the dp[] array is computed, obtain the sequence by traversing the dp[] array from N to 1."
},
{
"code": null,
"e": 11127,
"s": 10996,
"text": "Create an array dp[] to store the minimum length of sequence that is required to compute 1 to N by the three available operations."
},
{
"code": null,
"e": 11222,
"s": 11127,
"text": "Once the dp[] array is computed, obtain the sequence by traversing the dp[] array from N to 1."
},
{
"code": null,
"e": 11275,
"s": 11222,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 11279,
"s": 11275,
"text": "C++"
},
{
"code": null,
"e": 11284,
"s": 11279,
"text": "Java"
},
{
"code": null,
"e": 11292,
"s": 11284,
"text": "Python3"
},
{
"code": null,
"e": 11295,
"s": 11292,
"text": "C#"
},
{
"code": null,
"e": 11306,
"s": 11295,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to generate// the minimum sequencevoid find_sequence(int n){ // Stores the values for the // minimum length of sequences int dp[n + 1]; memset(dp, 0, sizeof(dp)); // Base Case dp[1] = 1; // Loop to build up the dp[] // array from 1 to n for(int i = 1; i < n + 1; i++) { if (dp[i] != 0) { // If i + 1 is within limits if (i + 1 < n + 1 && (dp[i + 1] == 0 || dp[i + 1] > dp[i] + 1)) { // Update the state of i + 1 // in dp[] array to minimum dp[i + 1] = dp[i] + 1; } // If i * 2 is within limits if (i * 2 < n + 1 && (dp[i * 2] == 0 || dp[i * 2] > dp[i] + 1)) { // Update the state of i * 2 // in dp[] array to minimum dp[i * 2] = dp[i] + 1; } // If i * 3 is within limits if (i * 3 < n + 1 && (dp[i * 3] == 0 || dp[i * 3] > dp[i] + 1)) { // Update the state of i * 3 // in dp[] array to minimum dp[i * 3] = dp[i] + 1; } } } // Generate the sequence by // traversing the array vector<int> sequence; while (n >= 1) { // Append n to the sequence sequence.push_back(n); // If the value of n in dp // is obtained from n - 1: if (dp[n - 1] == dp[n] - 1) { n--; } // If the value of n in dp[] // is obtained from n / 2: else if (n % 2 == 0 && dp[(int)floor(n / 2)] == dp[n] - 1) { n = (int)floor(n / 2); } // If the value of n in dp[] // is obtained from n / 3: else if (n % 3 == 0 && dp[(int)floor(n / 3)] == dp[n] - 1) { n = (int)floor(n / 3); } } // Print the sequence // in reverse order reverse(sequence.begin(), sequence.end()); // Print the length of // the minimal sequence cout << sequence.size() << endl; for(int i = 0; i < sequence.size(); i++) { cout << sequence[i] << \" \"; }} // Driver codeint main(){ // Given Number N int n = 5; // Function Call find_sequence(n); return 0;} // This code is contributed by divyeshrabadiya07",
"e": 13474,
"s": 11306,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.io.*;import java.util.*; class GFG{ // Function to generate// the minimum sequencepublic static void find_sequence(int n){ // Stores the values for the // minimum length of sequences int[] dp = new int[n + 1]; Arrays.fill(dp, 0); // Base Case dp[1] = 1; // Loop to build up the dp[] // array from 1 to n for(int i = 1; i < n + 1; i++) { if (dp[i] != 0) { // If i + 1 is within limits if (i + 1 < n + 1 && (dp[i + 1] == 0 || dp[i + 1] > dp[i] + 1)) { // Update the state of i + 1 // in dp[] array to minimum dp[i + 1] = dp[i] + 1; } // If i * 2 is within limits if (i * 2 < n + 1 && (dp[i * 2] == 0 || dp[i * 2] > dp[i] + 1)) { // Update the state of i * 2 // in dp[] array to minimum dp[i * 2] = dp[i] + 1; } // If i * 3 is within limits if (i * 3 < n + 1 && (dp[i * 3] == 0 || dp[i * 3] > dp[i] + 1)) { // Update the state of i * 3 // in dp[] array to minimum dp[i * 3] = dp[i] + 1; } } } // Generate the sequence by // traversing the array List<Integer> sequence = new ArrayList<Integer>(); while (n >= 1) { // Append n to the sequence sequence.add(n); // If the value of n in dp // is obtained from n - 1: if (dp[n - 1] == dp[n] - 1) { n--; } // If the value of n in dp[] // is obtained from n / 2: else if (n % 2 == 0 && dp[(int)Math.floor(n / 2)] == dp[n] - 1) { n = (int)Math.floor(n / 2); } // If the value of n in dp[] // is obtained from n / 3: else if (n % 3 == 0 && dp[(int)Math.floor(n / 3)] == dp[n] - 1) { n = (int)Math.floor(n / 3); } } // Print the sequence // in reverse order Collections.reverse(sequence); // Print the length of // the minimal sequence System.out.println(sequence.size()); for(int i = 0; i < sequence.size(); i++) { System.out.print(sequence.get(i) + \" \"); }} // Driver Codepublic static void main (String[] args){ // Given Number N int n = 5; // Function Call find_sequence(n);}} // This code is contributed by avanitrachhadiya2155",
"e": 16196,
"s": 13474,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to generate# the minimum sequencedef find_sequence(n): # Stores the values for the # minimum length of sequences dp = [0 for _ in range(n + 1)] # Base Case dp[1] = 1 # Loop to build up the dp[] # array from 1 to n for i in range(1, n + 1): if dp[i] != 0: # If i + 1 is within limits if i + 1 < n + 1 and (dp[i + 1] == 0 \\ or dp[i + 1] > dp[i] + 1): # Update the state of i + 1 # in dp[] array to minimum dp[i + 1] = dp[i] + 1 # If i * 2 is within limits if i * 2 < n + 1 and (dp[i * 2] == 0 \\ or dp[i * 2] > dp[i] + 1): # Update the state of i * 2 # in dp[] array to minimum dp[i * 2] = dp[i] + 1 # If i * 3 is within limits if i * 3 < n + 1 and (dp[i * 3] == 0 \\ or dp[i * 3] > dp[i] + 1): # Update the state of i * 3 # in dp[] array to minimum dp[i * 3] = dp[i] + 1 # Generate the sequence by # traversing the array sequence = [] while n >= 1: # Append n to the sequence sequence.append(n) # If the value of n in dp # is obtained from n - 1: if dp[n - 1] == dp[n] - 1: n = n - 1 # If the value of n in dp[] # is obtained from n / 2: elif n % 2 == 0 \\ and dp[n // 2] == dp[n] - 1: n = n // 2 # If the value of n in dp[] # is obtained from n / 3: elif n % 3 == 0 \\ and dp[n // 3] == dp[n] - 1: n = n // 3 # Return the sequence # in reverse order return sequence[::-1] # Driver Code # Given Number Nn = 5 # Function Callsequence = find_sequence(n) # Print the length of# the minimal sequenceprint(len(sequence)) # Print the sequenceprint(*sequence)",
"e": 18180,
"s": 16196,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to generate // the minimum sequence public static void find_sequence(int n) { // Stores the values for the // minimum length of sequences int[] dp = new int[n + 1]; Array.Fill(dp, 0); // Base Case dp[1] = 1; // Loop to build up the dp[] // array from 1 to n for(int i = 1; i < n + 1; i++) { if(dp[i] != 0) { // If i + 1 is within limits if(i + 1 < n + 1 && (dp[i + 1] == 0 || dp[i + 1] > dp[i] + 1)) { // Update the state of i + 1 // in dp[] array to minimum dp[i + 1] = dp[i] + 1; } // If i * 2 is within limits if(i * 2 < n + 1 && (dp[i * 2] == 0 || dp[i * 2] > dp[i] + 1)) { // Update the state of i * 2 // in dp[] array to minimum dp[i * 2] = dp[i] + 1; } // If i * 3 is within limits if(i * 3 < n + 1 && (dp[i * 3] == 0 || dp[i * 3] > dp[i] + 1)) { // Update the state of i * 3 // in dp[] array to minimum dp[i * 3] = dp[i] + 1; } } } // Generate the sequence by // traversing the array List<int> sequence = new List<int>(); while(n >= 1) { // Append n to the sequence sequence.Add(n); // If the value of n in dp // is obtained from n - 1: if(dp[n - 1] == dp[n] - 1) { n--; } // If the value of n in dp[] // is obtained from n / 2: else if(n % 2 == 0 && dp[(int)Math.Floor((decimal)n / 2)] == dp[n] - 1) { n = (int)Math.Floor((decimal)n / 2); } // If the value of n in dp[] // is obtained from n / 3: else if(n % 3 == 0 && dp[(int)Math.Floor((decimal)n / 3)] == dp[n] - 1) { n = (int)Math.Floor((decimal)n / 3); } } // Print the sequence // in reverse order sequence.Reverse(); // Print the length of // the minimal sequence Console.WriteLine(sequence.Count); for(int i = 0; i < sequence.Count; i++) { Console.Write(sequence[i] + \" \"); } } // Driver Code static public void Main () { // Given Number N int n = 5; // Function Call find_sequence(n); }} // This code is contributed by rag2127",
"e": 20624,
"s": 18180,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach // Function to generate// the minimum sequencefunction find_sequence(n){ // Stores the values for the // minimum length of sequences let dp = new Array(n + 1); for(let i=0;i<n+1;i++) { dp[i]=0; } // Base Case dp[1] = 1; // Loop to build up the dp[] // array from 1 to n for(let i = 1; i < n + 1; i++) { if (dp[i] != 0) { // If i + 1 is within limits if (i + 1 < n + 1 && (dp[i + 1] == 0 || dp[i + 1] > dp[i] + 1)) { // Update the state of i + 1 // in dp[] array to minimum dp[i + 1] = dp[i] + 1; } // If i * 2 is within limits if (i * 2 < n + 1 && (dp[i * 2] == 0 || dp[i * 2] > dp[i] + 1)) { // Update the state of i * 2 // in dp[] array to minimum dp[i * 2] = dp[i] + 1; } // If i * 3 is within limits if (i * 3 < n + 1 && (dp[i * 3] == 0 || dp[i * 3] > dp[i] + 1)) { // Update the state of i * 3 // in dp[] array to minimum dp[i * 3] = dp[i] + 1; } } } // Generate the sequence by // traversing the array let sequence = []; while (n >= 1) { // Append n to the sequence sequence.push(n); // If the value of n in dp // is obtained from n - 1: if (dp[n - 1] == dp[n] - 1) { n--; } // If the value of n in dp[] // is obtained from n / 2: else if (n % 2 == 0 && dp[Math.floor(n / 2)] == dp[n] - 1) { n = Math.floor(n / 2); } // If the value of n in dp[] // is obtained from n / 3: else if (n % 3 == 0 && dp[Math.floor(n / 3)] == dp[n] - 1) { n = Math.floor(n / 3); } } // Print the sequence // in reverse order sequence.reverse(); // Print the length of // the minimal sequence document.write(sequence.length+\"<br>\"); for(let i = 0; i < sequence.length; i++) { document.write(sequence[i] + \" \"); }} // Driver Codelet n = 5; // Function Callfind_sequence(n); // This code is contributed by unknown2108</script>",
"e": 23191,
"s": 20624,
"text": null
},
{
"code": null,
"e": 23201,
"s": 23191,
"text": "4\n1 3 4 5"
},
{
"code": null,
"e": 23248,
"s": 23203,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 23263,
"s": 23248,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 23280,
"s": 23263,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 23297,
"s": 23280,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 23314,
"s": 23297,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 23335,
"s": 23314,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 23343,
"s": 23335,
"text": "rag2127"
},
{
"code": null,
"e": 23361,
"s": 23343,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 23368,
"s": 23361,
"text": "rrrtnx"
},
{
"code": null,
"e": 23380,
"s": 23368,
"text": "unknown2108"
},
{
"code": null,
"e": 23391,
"s": 23380,
"text": "vinayedula"
},
{
"code": null,
"e": 23403,
"s": 23391,
"text": "Memoization"
},
{
"code": null,
"e": 23423,
"s": 23403,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 23436,
"s": 23423,
"text": "Mathematical"
},
{
"code": null,
"e": 23446,
"s": 23436,
"text": "Recursion"
},
{
"code": null,
"e": 23466,
"s": 23446,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 23479,
"s": 23466,
"text": "Mathematical"
},
{
"code": null,
"e": 23489,
"s": 23479,
"text": "Recursion"
}
] |
Lodash _.chain() Method | 16 Sep, 2020
The Lodash _.chain() method used to wrap the value with explicit method chain sequences enabled.
Syntax:
_.chain(value)
Parameter: This method accept a single a parameter as mentioned above and described below:
value: This parameter holds the value to wrap.
Return value: This method returns the wrapped value.
Below example illustrate the Lodash _.chain() method in JavaScript:
Example 1:
Javascript
const _ = require('lodash'); var person = [ { 'user': 'Tommy', 'income': 2600 }, { 'user': 'Asmita', 'income': 2400 }, { 'user': 'Hiyan', 'income': 2200 }]; var Earcning = _ .chain(person) .sortBy('income') .map(function(gfg) { return gfg.user + ' earn is ' + gfg.income; }) .value();console.log(Earcning)
Output:
Hiyan earn is 2200,
Asmita earn is 2400,
Tommy earn is 2600
Example 2:
Javascript
const _ = require('lodash'); var users = [ { 'user': 'Tommy', 'age': 23 }, { 'user': 'Asmita', 'age': 24 }, { 'user': 'Hiyan', 'age': 22 }]; var youngest = _ .chain(users) .sortBy('age') .map(function(o) { return o.user + ' is ' + o.age; }) .tail() .value();console.log(youngest)
Output:
Tommy is 23,Asmita is 24
Reference: https://docs-lodash.com/v4/chain/
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Sep, 2020"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "The Lodash _.chain() method used to wrap the value with explicit method chain sequences enabled. "
},
{
"code": null,
"e": 134,
"s": 126,
"text": "Syntax:"
},
{
"code": null,
"e": 150,
"s": 134,
"text": "_.chain(value)\n"
},
{
"code": null,
"e": 241,
"s": 150,
"text": "Parameter: This method accept a single a parameter as mentioned above and described below:"
},
{
"code": null,
"e": 288,
"s": 241,
"text": "value: This parameter holds the value to wrap."
},
{
"code": null,
"e": 341,
"s": 288,
"text": "Return value: This method returns the wrapped value."
},
{
"code": null,
"e": 409,
"s": 341,
"text": "Below example illustrate the Lodash _.chain() method in JavaScript:"
},
{
"code": null,
"e": 420,
"s": 409,
"text": "Example 1:"
},
{
"code": null,
"e": 431,
"s": 420,
"text": "Javascript"
},
{
"code": "const _ = require('lodash'); var person = [ { 'user': 'Tommy', 'income': 2600 }, { 'user': 'Asmita', 'income': 2400 }, { 'user': 'Hiyan', 'income': 2200 }]; var Earcning = _ .chain(person) .sortBy('income') .map(function(gfg) { return gfg.user + ' earn is ' + gfg.income; }) .value();console.log(Earcning)",
"e": 756,
"s": 431,
"text": null
},
{
"code": null,
"e": 764,
"s": 756,
"text": "Output:"
},
{
"code": null,
"e": 825,
"s": 764,
"text": "Hiyan earn is 2200,\nAsmita earn is 2400,\nTommy earn is 2600\n"
},
{
"code": null,
"e": 836,
"s": 825,
"text": "Example 2:"
},
{
"code": null,
"e": 847,
"s": 836,
"text": "Javascript"
},
{
"code": "const _ = require('lodash'); var users = [ { 'user': 'Tommy', 'age': 23 }, { 'user': 'Asmita', 'age': 24 }, { 'user': 'Hiyan', 'age': 22 }]; var youngest = _ .chain(users) .sortBy('age') .map(function(o) { return o.user + ' is ' + o.age; }) .tail() .value();console.log(youngest)",
"e": 1147,
"s": 847,
"text": null
},
{
"code": null,
"e": 1155,
"s": 1147,
"text": "Output:"
},
{
"code": null,
"e": 1181,
"s": 1155,
"text": "Tommy is 23,Asmita is 24\n"
},
{
"code": null,
"e": 1226,
"s": 1181,
"text": "Reference: https://docs-lodash.com/v4/chain/"
},
{
"code": null,
"e": 1244,
"s": 1226,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1255,
"s": 1244,
"text": "JavaScript"
},
{
"code": null,
"e": 1272,
"s": 1255,
"text": "Web Technologies"
},
{
"code": null,
"e": 1370,
"s": 1272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1431,
"s": 1370,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1503,
"s": 1431,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1543,
"s": 1503,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1596,
"s": 1543,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 1637,
"s": 1596,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1670,
"s": 1637,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1732,
"s": 1670,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1793,
"s": 1732,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1843,
"s": 1793,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python program to convert meters in yards and vice versa | 03 Jan, 2021
Given the distance in either meter or yard, the task here is to generate a Python program that converts distance given in meters to yards and vice versa.
Examples:
Input: Length in Meter: 245
Length in Yard : 100
Output: 245 Meter in Yard = 267.9344
100 Yards in Meter = 91.4403
Input: Length in Meter: 5
Length in Yard : 20
Output: 5 Meter in Yard = 5.4680
20 Yards in Meter = 18.2881
Formula used –
1 Meter = 1.09361 Yard
So from the above formula, 1 Meter is equivalent to 1.09361 yards, hence to convert meters to yards, simply multiply the distance given in meters by 1.09361, and to convert Yard to meter, we just have to divide length in Yard by 1.09361.
Below is the implementation.
Python3
meter = 5 # Length in Meteryard = 20 # Length in Yard # converting Meter to Yardmeter_to_yard = meter * 1.09361 # converting Yard to meteryard_to_meter = yard / 1.09361 # printing the outputprint("%d Meter in Yard = %.4f " % (meter, meter_to_yard))print("%d Yard in Meter = %.4f " % (yard, yard_to_meter))
Output:
5 Meter in Yard = 5.4680
20 Yard in Meter = 18.2881
Picked
school-programming
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 182,
"s": 28,
"text": "Given the distance in either meter or yard, the task here is to generate a Python program that converts distance given in meters to yards and vice versa."
},
{
"code": null,
"e": 192,
"s": 182,
"text": "Examples:"
},
{
"code": null,
"e": 450,
"s": 192,
"text": "Input: Length in Meter: 245\n Length in Yard : 100\n\nOutput: 245 Meter in Yard = 267.9344 \n 100 Yards in Meter = 91.4403\n\n\nInput: Length in Meter: 5\n Length in Yard : 20\n\nOutput: 5 Meter in Yard = 5.4680 \n 20 Yards in Meter = 18.2881"
},
{
"code": null,
"e": 466,
"s": 450,
"text": "Formula used – "
},
{
"code": null,
"e": 489,
"s": 466,
"text": "1 Meter = 1.09361 Yard"
},
{
"code": null,
"e": 727,
"s": 489,
"text": "So from the above formula, 1 Meter is equivalent to 1.09361 yards, hence to convert meters to yards, simply multiply the distance given in meters by 1.09361, and to convert Yard to meter, we just have to divide length in Yard by 1.09361."
},
{
"code": null,
"e": 756,
"s": 727,
"text": "Below is the implementation."
},
{
"code": null,
"e": 764,
"s": 756,
"text": "Python3"
},
{
"code": "meter = 5 # Length in Meteryard = 20 # Length in Yard # converting Meter to Yardmeter_to_yard = meter * 1.09361 # converting Yard to meteryard_to_meter = yard / 1.09361 # printing the outputprint(\"%d Meter in Yard = %.4f \" % (meter, meter_to_yard))print(\"%d Yard in Meter = %.4f \" % (yard, yard_to_meter))",
"e": 1075,
"s": 764,
"text": null
},
{
"code": null,
"e": 1083,
"s": 1075,
"text": "Output:"
},
{
"code": null,
"e": 1110,
"s": 1083,
"text": "5 Meter in Yard = 5.4680 "
},
{
"code": null,
"e": 1137,
"s": 1110,
"text": "20 Yard in Meter = 18.2881"
},
{
"code": null,
"e": 1144,
"s": 1137,
"text": "Picked"
},
{
"code": null,
"e": 1163,
"s": 1144,
"text": "school-programming"
},
{
"code": null,
"e": 1187,
"s": 1163,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1194,
"s": 1187,
"text": "Python"
},
{
"code": null,
"e": 1210,
"s": 1194,
"text": "Python Programs"
},
{
"code": null,
"e": 1229,
"s": 1210,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1327,
"s": 1229,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1359,
"s": 1327,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1386,
"s": 1359,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1407,
"s": 1386,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1430,
"s": 1407,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1486,
"s": 1430,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1508,
"s": 1486,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1547,
"s": 1508,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1585,
"s": 1547,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 1622,
"s": 1585,
"text": "Python Program for Fibonacci numbers"
}
] |
Python | Visualize missing values (NaN) values using Missingno Library | 04 Jul, 2019
In the case of a real-world dataset, it is very common that some values in the dataset are missing. We represent these missing values as NaN (Not a Number) values. But to build a good machine learning model our dataset should be complete. That’s why we use some imputation techniques to replace the NaN values with some probable values. But before doing that we need to have a good understanding of how the NaN values are distributed in our dataset.
Missingno library offers a very nice way to visualize the distribution of NaN values. Missingno is a Python library and compatible with Pandas.
Install the library –
pip install missingno
To get the dataset used in the code, click here.
Using this matrix you can very quickly find the pattern of missingness in the dataset. In our example, the columns AAWhiteSt-4 and SulphidityL-4 have a similar pattern of missing values while UCZAA shows a different pattern.
# Program to visualize missing values in dataset # Importing the librariesimport pandas as pdimport missingno as msno # Loading the datasetdf = pd.read_csv("kamyr-digester.csv") # Visualize missing values as a matrixmsno.matrix(df)
Output:
This bar chart gives you an idea about how many missing values are there in each column. In our example, AAWhiteSt-4 and SulphidityL-4 contain the most number of missing values followed by UCZAA.
# Program to visualize missing values in dataset # Importing the librariesimport pandas as pdimport missingno as msno # Loading the datasetdf = pd.read_csv("kamyr-digester.csv") # Visualize the number of missing# values as a bar chartmsno.bar(df)
Output:
Heatmap shows the correlation of missingness between every 2 columns. In our example, the correlation between AAWhiteSt-4 and SulphidityL-4 is 1 which means if one of them is present then the other one must be present.
A value near -1 means if one variable appears then the other variable is very likely to be missing.A value near 0 means there is no dependence between the occurrence of missing values of two variables.A value near 1 means if one variable appears then the other variable is very likely to be present.
# Program to visualize missing values in dataset # Importing the librariesimport pandas as pdimport missingno as msno # Loading the datasetdf = pd.read_csv("kamyr-digester.csv") # Visualize the correlation between the number of# missing values in different columns as a heatmapmsno.heatmap(df)
Output:
Reference : https://github.com/ResidentMario/missingno
Python-pandas
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jul, 2019"
},
{
"code": null,
"e": 478,
"s": 28,
"text": "In the case of a real-world dataset, it is very common that some values in the dataset are missing. We represent these missing values as NaN (Not a Number) values. But to build a good machine learning model our dataset should be complete. That’s why we use some imputation techniques to replace the NaN values with some probable values. But before doing that we need to have a good understanding of how the NaN values are distributed in our dataset."
},
{
"code": null,
"e": 622,
"s": 478,
"text": "Missingno library offers a very nice way to visualize the distribution of NaN values. Missingno is a Python library and compatible with Pandas."
},
{
"code": null,
"e": 644,
"s": 622,
"text": "Install the library –"
},
{
"code": null,
"e": 667,
"s": 644,
"text": "pip install missingno\n"
},
{
"code": null,
"e": 716,
"s": 667,
"text": "To get the dataset used in the code, click here."
},
{
"code": null,
"e": 941,
"s": 716,
"text": "Using this matrix you can very quickly find the pattern of missingness in the dataset. In our example, the columns AAWhiteSt-4 and SulphidityL-4 have a similar pattern of missing values while UCZAA shows a different pattern."
},
{
"code": "# Program to visualize missing values in dataset # Importing the librariesimport pandas as pdimport missingno as msno # Loading the datasetdf = pd.read_csv(\"kamyr-digester.csv\") # Visualize missing values as a matrixmsno.matrix(df)",
"e": 1176,
"s": 941,
"text": null
},
{
"code": null,
"e": 1184,
"s": 1176,
"text": "Output:"
},
{
"code": null,
"e": 1380,
"s": 1184,
"text": "This bar chart gives you an idea about how many missing values are there in each column. In our example, AAWhiteSt-4 and SulphidityL-4 contain the most number of missing values followed by UCZAA."
},
{
"code": "# Program to visualize missing values in dataset # Importing the librariesimport pandas as pdimport missingno as msno # Loading the datasetdf = pd.read_csv(\"kamyr-digester.csv\") # Visualize the number of missing# values as a bar chartmsno.bar(df)",
"e": 1630,
"s": 1380,
"text": null
},
{
"code": null,
"e": 1638,
"s": 1630,
"text": "Output:"
},
{
"code": null,
"e": 1857,
"s": 1638,
"text": "Heatmap shows the correlation of missingness between every 2 columns. In our example, the correlation between AAWhiteSt-4 and SulphidityL-4 is 1 which means if one of them is present then the other one must be present."
},
{
"code": null,
"e": 2157,
"s": 1857,
"text": "A value near -1 means if one variable appears then the other variable is very likely to be missing.A value near 0 means there is no dependence between the occurrence of missing values of two variables.A value near 1 means if one variable appears then the other variable is very likely to be present."
},
{
"code": "# Program to visualize missing values in dataset # Importing the librariesimport pandas as pdimport missingno as msno # Loading the datasetdf = pd.read_csv(\"kamyr-digester.csv\") # Visualize the correlation between the number of# missing values in different columns as a heatmapmsno.heatmap(df)",
"e": 2456,
"s": 2157,
"text": null
},
{
"code": null,
"e": 2464,
"s": 2456,
"text": "Output:"
},
{
"code": null,
"e": 2519,
"s": 2464,
"text": "Reference : https://github.com/ResidentMario/missingno"
},
{
"code": null,
"e": 2533,
"s": 2519,
"text": "Python-pandas"
},
{
"code": null,
"e": 2550,
"s": 2533,
"text": "Machine Learning"
},
{
"code": null,
"e": 2557,
"s": 2550,
"text": "Python"
},
{
"code": null,
"e": 2574,
"s": 2557,
"text": "Machine Learning"
}
] |
Selenium – Search for text on page | 03 Mar, 2021
Prerequisite:- Selenium
Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python.
In this article, we will learn how to know whether the text is on a web page or not using selenium in python.
Approach:
First, we will open the chrome driver using the Chrome() method in the Selenium web driver
Assign the Web URL.
Then the driver will open the Give Web URL
Get Web Page Source Code using page_source property.
Assign the text to be searched.
After getting the web page text, we will search whether the text is present or not.
Below is the implementation:
Python3
# import webdriver from selenium import webdriver # create webdriver object driver = webdriver.Chrome() # URL of the website url = "https://www.geeksforgeeks.org/" # Opening the URL driver.get(url) # Getting current URL source code get_source = driver.page_source # Text you want to searchsearch_text = "Floor" # print True if text is present else Falseprint(search_text in get_source)
Output:
True
Demonstration:
Picked
Python Selenium-Exercises
Python-selenium
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": "\n03 Mar, 2021"
},
{
"code": null,
"e": 52,
"s": 28,
"text": "Prerequisite:- Selenium"
},
{
"code": null,
"e": 326,
"s": 52,
"text": "Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python."
},
{
"code": null,
"e": 436,
"s": 326,
"text": "In this article, we will learn how to know whether the text is on a web page or not using selenium in python."
},
{
"code": null,
"e": 446,
"s": 436,
"text": "Approach:"
},
{
"code": null,
"e": 537,
"s": 446,
"text": "First, we will open the chrome driver using the Chrome() method in the Selenium web driver"
},
{
"code": null,
"e": 557,
"s": 537,
"text": "Assign the Web URL."
},
{
"code": null,
"e": 600,
"s": 557,
"text": "Then the driver will open the Give Web URL"
},
{
"code": null,
"e": 653,
"s": 600,
"text": "Get Web Page Source Code using page_source property."
},
{
"code": null,
"e": 685,
"s": 653,
"text": "Assign the text to be searched."
},
{
"code": null,
"e": 769,
"s": 685,
"text": "After getting the web page text, we will search whether the text is present or not."
},
{
"code": null,
"e": 798,
"s": 769,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 806,
"s": 798,
"text": "Python3"
},
{
"code": "# import webdriver from selenium import webdriver # create webdriver object driver = webdriver.Chrome() # URL of the website url = \"https://www.geeksforgeeks.org/\" # Opening the URL driver.get(url) # Getting current URL source code get_source = driver.page_source # Text you want to searchsearch_text = \"Floor\" # print True if text is present else Falseprint(search_text in get_source)",
"e": 1199,
"s": 806,
"text": null
},
{
"code": null,
"e": 1207,
"s": 1199,
"text": "Output:"
},
{
"code": null,
"e": 1212,
"s": 1207,
"text": "True"
},
{
"code": null,
"e": 1227,
"s": 1212,
"text": "Demonstration:"
},
{
"code": null,
"e": 1234,
"s": 1227,
"text": "Picked"
},
{
"code": null,
"e": 1260,
"s": 1234,
"text": "Python Selenium-Exercises"
},
{
"code": null,
"e": 1276,
"s": 1260,
"text": "Python-selenium"
},
{
"code": null,
"e": 1283,
"s": 1276,
"text": "Python"
},
{
"code": null,
"e": 1381,
"s": 1283,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1413,
"s": 1381,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1440,
"s": 1413,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1461,
"s": 1440,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1484,
"s": 1461,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1540,
"s": 1484,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1571,
"s": 1540,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1613,
"s": 1571,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1655,
"s": 1613,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1694,
"s": 1655,
"text": "Python | Get unique values from a list"
}
] |
Largest number that divides x and is co-prime with y | 12 Apr, 2021
Given two positive numbers x and y. Find the maximum valued integer a such that:
a divides x i.e. x % a = 0a and y are co-prime i.e. gcd(a, y) = 1
a divides x i.e. x % a = 0
a and y are co-prime i.e. gcd(a, y) = 1
Examples :
Input : x = 15
y = 3
Output : a = 5
Explanation: 5 is the max integer
which satisfies both the conditions.
15 % 5 =0
gcd(5, 3) = 1
Hence, output is 5.
Input : x = 14
y = 28
Output : a = 1
Explanation: 14 % 1 =0
gcd(1, 28) = 1
Hence, output is 1.
Approach: Here, first we will remove the common factors of x and y from x by finding the greatest common divisor (gcd) of x and y and dividing x with that gcd. Mathematically:
x = x / gcd(x, y) —— STEP1
Now, we repeat STEP1 till we get gcd(x, y) = 1. At last, we return a = x
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the// Largest Coprime Divisor #include <bits/stdc++.h>using namespace std; // Recursive function to return gcd// of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // function to find largest// coprime divisorint cpFact(int x, int y){ while (gcd(x, y) != 1) { x = x / gcd(x, y); } return x;} // divisor codeint main(){ int x = 15; int y = 3; cout << cpFact(x, y) << endl; x = 14; y = 28; cout << cpFact(x, y) << endl; x = 7; y = 3; cout << cpFact(x, y); return 0;}
// java program to find the// Largest Coprime Divisorimport java.io.*; class GFG { // Recursive function to return gcd // of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // function to find largest // coprime divisor static int cpFact(int x, int y) { while (gcd(x, y) != 1) { x = x / gcd(x, y); } return x; } // divisor code public static void main(String[] args) { int x = 15; int y = 3; System.out.println(cpFact(x, y)); x = 14; y = 28; System.out.println(cpFact(x, y)); x = 7; y = 3; System.out.println(cpFact(x, y)); }} // This article is contributed by vt_m.
# Python3 code to find the# Largest Coprime Divisor # Recursive function to return# gcd of a and bdef gcd (a, b): # Everything divides 0 if a == 0 or b == 0: return 0 # base case if a == b: return a # a is greater if a > b: return gcd(a - b, b) return gcd(a, b - a) # function to find largest# coprime divisordef cpFact(x, y): while gcd(x, y) != 1: x = x / gcd(x, y) return int(x) # divisor codex = 15y = 3print(cpFact(x, y))x = 14y = 28print(cpFact(x, y))x = 7y = 3print(cpFact(x, y)) # This code is contributed by "Sharad_Bhardwaj".
// C# program to find the// Largest Coprime Divisorusing System; class GFG { // Recursive function to return gcd // of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // function to find largest // coprime divisor static int cpFact(int x, int y) { while (gcd(x, y) != 1) { x = x / gcd(x, y); } return x; } // divisor code public static void Main() { int x = 15; int y = 3; Console.WriteLine(cpFact(x, y)); x = 14; y = 28; Console.WriteLine(cpFact(x, y)); x = 7; y = 3; Console.WriteLine(cpFact(x, y)); }} // This code is contributed by vt_m.
<?php// PHP program to find the// Largest Coprime Divisor // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if ($a == 0 || $b == 0) return 0; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return gcd($a - $b, $b); return gcd($a, $b - $a);} // function to find largest// coprime divisorfunction cpFact( $x, $y){ while (gcd($x, $y) != 1) { $x = $x / gcd($x, $y); } return $x;} // Driver Code$x = 15;$y = 3;echo cpFact($x, $y), "\n";$x = 14;$y = 28;echo cpFact($x, $y), "\n";$x = 7;$y = 3;echo cpFact($x, $y); // This code is contributed by aj_36?>
<script> // Javascript program to find the// Largest Coprime Divisor // Recursive function to// return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // function to find largest// coprime divisorfunction cpFact(x, y){ while (gcd(x, y) != 1) { x = x / gcd(x, y); } return x;} // Driver Codelet x = 15;let y = 3;document.write(cpFact(x, y) + "<br>");x = 14;y = 28;document.write(cpFact(x, y), "<br>");x = 7;y = 3;document.write(cpFact(x, y)); // This code is contributed by gfgking </script>
Output :
5
1
7
jit_t
gfgking
divisibility
GCD-LCM
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number
Program to find sum of elements in a given array | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 135,
"s": 52,
"text": "Given two positive numbers x and y. Find the maximum valued integer a such that: "
},
{
"code": null,
"e": 201,
"s": 135,
"text": "a divides x i.e. x % a = 0a and y are co-prime i.e. gcd(a, y) = 1"
},
{
"code": null,
"e": 228,
"s": 201,
"text": "a divides x i.e. x % a = 0"
},
{
"code": null,
"e": 268,
"s": 228,
"text": "a and y are co-prime i.e. gcd(a, y) = 1"
},
{
"code": null,
"e": 281,
"s": 268,
"text": "Examples : "
},
{
"code": null,
"e": 587,
"s": 281,
"text": "Input : x = 15\n y = 3 \nOutput : a = 5\nExplanation: 5 is the max integer \nwhich satisfies both the conditions.\n 15 % 5 =0\n gcd(5, 3) = 1\nHence, output is 5. \n\nInput : x = 14\n y = 28\nOutput : a = 1\nExplanation: 14 % 1 =0\n gcd(1, 28) = 1\nHence, output is 1. "
},
{
"code": null,
"e": 767,
"s": 589,
"text": "Approach: Here, first we will remove the common factors of x and y from x by finding the greatest common divisor (gcd) of x and y and dividing x with that gcd. Mathematically: "
},
{
"code": null,
"e": 796,
"s": 767,
"text": " x = x / gcd(x, y) —— STEP1 "
},
{
"code": null,
"e": 871,
"s": 796,
"text": "Now, we repeat STEP1 till we get gcd(x, y) = 1. At last, we return a = x "
},
{
"code": null,
"e": 875,
"s": 871,
"text": "C++"
},
{
"code": null,
"e": 880,
"s": 875,
"text": "Java"
},
{
"code": null,
"e": 888,
"s": 880,
"text": "Python3"
},
{
"code": null,
"e": 891,
"s": 888,
"text": "C#"
},
{
"code": null,
"e": 895,
"s": 891,
"text": "PHP"
},
{
"code": null,
"e": 906,
"s": 895,
"text": "Javascript"
},
{
"code": "// CPP program to find the// Largest Coprime Divisor #include <bits/stdc++.h>using namespace std; // Recursive function to return gcd// of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // function to find largest// coprime divisorint cpFact(int x, int y){ while (gcd(x, y) != 1) { x = x / gcd(x, y); } return x;} // divisor codeint main(){ int x = 15; int y = 3; cout << cpFact(x, y) << endl; x = 14; y = 28; cout << cpFact(x, y) << endl; x = 7; y = 3; cout << cpFact(x, y); return 0;}",
"e": 1629,
"s": 906,
"text": null
},
{
"code": "// java program to find the// Largest Coprime Divisorimport java.io.*; class GFG { // Recursive function to return gcd // of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // function to find largest // coprime divisor static int cpFact(int x, int y) { while (gcd(x, y) != 1) { x = x / gcd(x, y); } return x; } // divisor code public static void main(String[] args) { int x = 15; int y = 3; System.out.println(cpFact(x, y)); x = 14; y = 28; System.out.println(cpFact(x, y)); x = 7; y = 3; System.out.println(cpFact(x, y)); }} // This article is contributed by vt_m.",
"e": 2574,
"s": 1629,
"text": null
},
{
"code": "# Python3 code to find the# Largest Coprime Divisor # Recursive function to return# gcd of a and bdef gcd (a, b): # Everything divides 0 if a == 0 or b == 0: return 0 # base case if a == b: return a # a is greater if a > b: return gcd(a - b, b) return gcd(a, b - a) # function to find largest# coprime divisordef cpFact(x, y): while gcd(x, y) != 1: x = x / gcd(x, y) return int(x) # divisor codex = 15y = 3print(cpFact(x, y))x = 14y = 28print(cpFact(x, y))x = 7y = 3print(cpFact(x, y)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 3192,
"s": 2574,
"text": null
},
{
"code": "// C# program to find the// Largest Coprime Divisorusing System; class GFG { // Recursive function to return gcd // of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // function to find largest // coprime divisor static int cpFact(int x, int y) { while (gcd(x, y) != 1) { x = x / gcd(x, y); } return x; } // divisor code public static void Main() { int x = 15; int y = 3; Console.WriteLine(cpFact(x, y)); x = 14; y = 28; Console.WriteLine(cpFact(x, y)); x = 7; y = 3; Console.WriteLine(cpFact(x, y)); }} // This code is contributed by vt_m.",
"e": 4119,
"s": 3192,
"text": null
},
{
"code": "<?php// PHP program to find the// Largest Coprime Divisor // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if ($a == 0 || $b == 0) return 0; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return gcd($a - $b, $b); return gcd($a, $b - $a);} // function to find largest// coprime divisorfunction cpFact( $x, $y){ while (gcd($x, $y) != 1) { $x = $x / gcd($x, $y); } return $x;} // Driver Code$x = 15;$y = 3;echo cpFact($x, $y), \"\\n\";$x = 14;$y = 28;echo cpFact($x, $y), \"\\n\";$x = 7;$y = 3;echo cpFact($x, $y); // This code is contributed by aj_36?>",
"e": 4792,
"s": 4119,
"text": null
},
{
"code": "<script> // Javascript program to find the// Largest Coprime Divisor // Recursive function to// return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // function to find largest// coprime divisorfunction cpFact(x, y){ while (gcd(x, y) != 1) { x = x / gcd(x, y); } return x;} // Driver Codelet x = 15;let y = 3;document.write(cpFact(x, y) + \"<br>\");x = 14;y = 28;document.write(cpFact(x, y), \"<br>\");x = 7;y = 3;document.write(cpFact(x, y)); // This code is contributed by gfgking </script>",
"e": 5495,
"s": 4792,
"text": null
},
{
"code": null,
"e": 5505,
"s": 5495,
"text": "Output : "
},
{
"code": null,
"e": 5511,
"s": 5505,
"text": "5\n1\n7"
},
{
"code": null,
"e": 5519,
"s": 5513,
"text": "jit_t"
},
{
"code": null,
"e": 5527,
"s": 5519,
"text": "gfgking"
},
{
"code": null,
"e": 5540,
"s": 5527,
"text": "divisibility"
},
{
"code": null,
"e": 5548,
"s": 5540,
"text": "GCD-LCM"
},
{
"code": null,
"e": 5561,
"s": 5548,
"text": "Mathematical"
},
{
"code": null,
"e": 5574,
"s": 5561,
"text": "Mathematical"
},
{
"code": null,
"e": 5672,
"s": 5574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5693,
"s": 5672,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 5707,
"s": 5693,
"text": "Prime Numbers"
},
{
"code": null,
"e": 5760,
"s": 5707,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 5792,
"s": 5760,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 5829,
"s": 5792,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 5856,
"s": 5829,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 5899,
"s": 5856,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 5942,
"s": 5899,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 5976,
"s": 5942,
"text": "Program for factorial of a number"
}
] |
Virtual Function in C++ | 08 Jul, 2022
A virtual function is a member function which is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.
Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at runtime.
Rules for Virtual Functions
Virtual functions cannot be static.A virtual function can be a friend function of another class.Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism.The prototype of virtual functions should be the same in the base as well as derived class.They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.A class may have virtual destructor but it cannot have a virtual constructor.
Virtual functions cannot be static.
A virtual function can be a friend function of another class.
Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism.
The prototype of virtual functions should be the same in the base as well as derived class.
They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.
A class may have virtual destructor but it cannot have a virtual constructor.
Compile time (early binding) VS runtime (late binding) behavior of Virtual Functions
Consider the following simple program showing runtime behavior of virtual functions.
CPP
// CPP program to illustrate// concept of Virtual Functions #include<iostream>using namespace std; class base {public: virtual void print() { cout << "print base class\n"; } void show() { cout << "show base class\n"; }}; class derived : public base {public: void print() { cout << "print derived class\n"; } void show() { cout << "show derived class\n"; }}; int main(){ base *bptr; derived d; bptr = &d; // Virtual function, binded at runtime bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0;}
Output:
print derived class
show base class
Explanation: Runtime polymorphism is achieved only through a pointer (or reference) of base class type. Also, a base class pointer can point to the objects of base class as well as to the objects of derived class. In above code, base class pointer ‘bptr’ contains the address of object ‘d’ of derived class.Late binding (Runtime) is done in accordance with the content of pointer (i.e. location pointed to by pointer) and Early binding (Compile time) is done according to the type of pointer, since print() function is declared with virtual keyword so it will be bound at runtime (output is print derived class as pointer is pointing to object of derived class) and show() is non-virtual so it will be bound during compile time (output is show base class as pointer is of base type).NOTE: If we have created a virtual function in the base class and it is being overridden in the derived class then we don’t need virtual keyword in the derived class, functions are automatically considered as virtual functions in the derived class.
Working of virtual functions (concept of VTABLE and VPTR)As discussed here, if a class contains a virtual function then compiler itself does two things.
If object of that class is created then a virtual pointer (VPTR) is inserted as a data member of the class to point to VTABLE of that class. For each new object created, a new virtual pointer is inserted as a data member of that class.Irrespective of object is created or not, class contains as a member a static array of function pointers called VTABLE. Cells of this table store the address of each virtual function contained in that class.
If object of that class is created then a virtual pointer (VPTR) is inserted as a data member of the class to point to VTABLE of that class. For each new object created, a new virtual pointer is inserted as a data member of that class.
Irrespective of object is created or not, class contains as a member a static array of function pointers called VTABLE. Cells of this table store the address of each virtual function contained in that class.
Consider the example below:
CPP
// CPP program to illustrate// working of Virtual Functions#include<iostream>using namespace std; class base {public: void fun_1() { cout << "base-1\n"; } virtual void fun_2() { cout << "base-2\n"; } virtual void fun_3() { cout << "base-3\n"; } virtual void fun_4() { cout << "base-4\n"; }}; class derived : public base {public: void fun_1() { cout << "derived-1\n"; } void fun_2() { cout << "derived-2\n"; } void fun_4(int x) { cout << "derived-4\n"; }}; int main(){ base *p; derived obj1; p = &obj1; // Early binding because fun1() is non-virtual // in base p->fun_1(); // Late binding (RTP) p->fun_2(); // Late binding (RTP) p->fun_3(); // Late binding (RTP) p->fun_4(); // Early binding but this function call is // illegal (produces error) because pointer // is of base type and function is of // derived class // p->fun_4(5); return 0;}
Output:
base-1
derived-2
base-3
base-4
Explanation: Initially, we create a pointer of type base class and initialize it with the address of the derived class object. When we create an object of the derived class, the compiler creates a pointer as a data member of the class containing the address of VTABLE of the derived class.
Similar concept of Late and Early Binding is used as in above example. For fun_1() function call, base class version of function is called, fun_2() is overridden in derived class so derived class version is called, fun_3() is not overridden in derived class and is virtual function so base class version is called, similarly fun_4() is not overridden so base class version is called.
NOTE: fun_4(int) in derived class is different from virtual function fun_4() in base class as prototypes of both the functions are different.
Slower: The function call takes slightly longer due to the virtual mechanism and makes it more difficult for the compiler to optimize because it does not know exactly which function is going to be called at compile time.
Difficult to Debug: In a complex system, virtual functions can make it a little more difficult to figure out where a function is being called from.
This article is contributed by Yash Singla. 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.
Prashant Upadhyay 2
ArjunAshok
cheneaucn
priyanshulgovil
simmytarika5
surinderdawra388
kziemianfvt
itskawal2000
cpp-inheritance
cpp-virtual
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types
Templates in C++ with Examples
Multidimensional Arrays in C / C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 380,
"s": 54,
"text": "A virtual function is a member function which is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. "
},
{
"code": null,
"e": 529,
"s": 380,
"text": "Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call."
},
{
"code": null,
"e": 582,
"s": 529,
"text": "They are mainly used to achieve Runtime polymorphism"
},
{
"code": null,
"e": 643,
"s": 582,
"text": "Functions are declared with a virtual keyword in base class."
},
{
"code": null,
"e": 694,
"s": 643,
"text": "The resolving of function call is done at runtime."
},
{
"code": null,
"e": 722,
"s": 694,
"text": "Rules for Virtual Functions"
},
{
"code": null,
"e": 1331,
"s": 722,
"text": "Virtual functions cannot be static.A virtual function can be a friend function of another class.Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism.The prototype of virtual functions should be the same in the base as well as derived class.They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.A class may have virtual destructor but it cannot have a virtual constructor."
},
{
"code": null,
"e": 1367,
"s": 1331,
"text": "Virtual functions cannot be static."
},
{
"code": null,
"e": 1429,
"s": 1367,
"text": "A virtual function can be a friend function of another class."
},
{
"code": null,
"e": 1545,
"s": 1429,
"text": "Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism."
},
{
"code": null,
"e": 1637,
"s": 1545,
"text": "The prototype of virtual functions should be the same in the base as well as derived class."
},
{
"code": null,
"e": 1867,
"s": 1637,
"text": "They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used."
},
{
"code": null,
"e": 1945,
"s": 1867,
"text": "A class may have virtual destructor but it cannot have a virtual constructor."
},
{
"code": null,
"e": 2030,
"s": 1945,
"text": "Compile time (early binding) VS runtime (late binding) behavior of Virtual Functions"
},
{
"code": null,
"e": 2115,
"s": 2030,
"text": "Consider the following simple program showing runtime behavior of virtual functions."
},
{
"code": null,
"e": 2119,
"s": 2115,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// concept of Virtual Functions #include<iostream>using namespace std; class base {public: virtual void print() { cout << \"print base class\\n\"; } void show() { cout << \"show base class\\n\"; }}; class derived : public base {public: void print() { cout << \"print derived class\\n\"; } void show() { cout << \"show derived class\\n\"; }}; int main(){ base *bptr; derived d; bptr = &d; // Virtual function, binded at runtime bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0;}",
"e": 2754,
"s": 2119,
"text": null
},
{
"code": null,
"e": 2764,
"s": 2754,
"text": "Output: "
},
{
"code": null,
"e": 2800,
"s": 2764,
"text": "print derived class\nshow base class"
},
{
"code": null,
"e": 3833,
"s": 2800,
"text": "Explanation: Runtime polymorphism is achieved only through a pointer (or reference) of base class type. Also, a base class pointer can point to the objects of base class as well as to the objects of derived class. In above code, base class pointer ‘bptr’ contains the address of object ‘d’ of derived class.Late binding (Runtime) is done in accordance with the content of pointer (i.e. location pointed to by pointer) and Early binding (Compile time) is done according to the type of pointer, since print() function is declared with virtual keyword so it will be bound at runtime (output is print derived class as pointer is pointing to object of derived class) and show() is non-virtual so it will be bound during compile time (output is show base class as pointer is of base type).NOTE: If we have created a virtual function in the base class and it is being overridden in the derived class then we don’t need virtual keyword in the derived class, functions are automatically considered as virtual functions in the derived class. "
},
{
"code": null,
"e": 3986,
"s": 3833,
"text": "Working of virtual functions (concept of VTABLE and VPTR)As discussed here, if a class contains a virtual function then compiler itself does two things."
},
{
"code": null,
"e": 4429,
"s": 3986,
"text": "If object of that class is created then a virtual pointer (VPTR) is inserted as a data member of the class to point to VTABLE of that class. For each new object created, a new virtual pointer is inserted as a data member of that class.Irrespective of object is created or not, class contains as a member a static array of function pointers called VTABLE. Cells of this table store the address of each virtual function contained in that class."
},
{
"code": null,
"e": 4665,
"s": 4429,
"text": "If object of that class is created then a virtual pointer (VPTR) is inserted as a data member of the class to point to VTABLE of that class. For each new object created, a new virtual pointer is inserted as a data member of that class."
},
{
"code": null,
"e": 4873,
"s": 4665,
"text": "Irrespective of object is created or not, class contains as a member a static array of function pointers called VTABLE. Cells of this table store the address of each virtual function contained in that class."
},
{
"code": null,
"e": 4903,
"s": 4873,
"text": "Consider the example below: "
},
{
"code": null,
"e": 4907,
"s": 4903,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// working of Virtual Functions#include<iostream>using namespace std; class base {public: void fun_1() { cout << \"base-1\\n\"; } virtual void fun_2() { cout << \"base-2\\n\"; } virtual void fun_3() { cout << \"base-3\\n\"; } virtual void fun_4() { cout << \"base-4\\n\"; }}; class derived : public base {public: void fun_1() { cout << \"derived-1\\n\"; } void fun_2() { cout << \"derived-2\\n\"; } void fun_4(int x) { cout << \"derived-4\\n\"; }}; int main(){ base *p; derived obj1; p = &obj1; // Early binding because fun1() is non-virtual // in base p->fun_1(); // Late binding (RTP) p->fun_2(); // Late binding (RTP) p->fun_3(); // Late binding (RTP) p->fun_4(); // Early binding but this function call is // illegal (produces error) because pointer // is of base type and function is of // derived class // p->fun_4(5); return 0;}",
"e": 5842,
"s": 4907,
"text": null
},
{
"code": null,
"e": 5852,
"s": 5842,
"text": "Output: "
},
{
"code": null,
"e": 5883,
"s": 5852,
"text": "base-1\nderived-2\nbase-3\nbase-4"
},
{
"code": null,
"e": 6173,
"s": 5883,
"text": "Explanation: Initially, we create a pointer of type base class and initialize it with the address of the derived class object. When we create an object of the derived class, the compiler creates a pointer as a data member of the class containing the address of VTABLE of the derived class."
},
{
"code": null,
"e": 6557,
"s": 6173,
"text": "Similar concept of Late and Early Binding is used as in above example. For fun_1() function call, base class version of function is called, fun_2() is overridden in derived class so derived class version is called, fun_3() is not overridden in derived class and is virtual function so base class version is called, similarly fun_4() is not overridden so base class version is called."
},
{
"code": null,
"e": 6699,
"s": 6557,
"text": "NOTE: fun_4(int) in derived class is different from virtual function fun_4() in base class as prototypes of both the functions are different."
},
{
"code": null,
"e": 6920,
"s": 6699,
"text": "Slower: The function call takes slightly longer due to the virtual mechanism and makes it more difficult for the compiler to optimize because it does not know exactly which function is going to be called at compile time."
},
{
"code": null,
"e": 7068,
"s": 6920,
"text": "Difficult to Debug: In a complex system, virtual functions can make it a little more difficult to figure out where a function is being called from."
},
{
"code": null,
"e": 7488,
"s": 7068,
"text": "This article is contributed by Yash Singla. 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": 7508,
"s": 7488,
"text": "Prashant Upadhyay 2"
},
{
"code": null,
"e": 7519,
"s": 7508,
"text": "ArjunAshok"
},
{
"code": null,
"e": 7529,
"s": 7519,
"text": "cheneaucn"
},
{
"code": null,
"e": 7545,
"s": 7529,
"text": "priyanshulgovil"
},
{
"code": null,
"e": 7558,
"s": 7545,
"text": "simmytarika5"
},
{
"code": null,
"e": 7575,
"s": 7558,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7587,
"s": 7575,
"text": "kziemianfvt"
},
{
"code": null,
"e": 7600,
"s": 7587,
"text": "itskawal2000"
},
{
"code": null,
"e": 7616,
"s": 7600,
"text": "cpp-inheritance"
},
{
"code": null,
"e": 7628,
"s": 7616,
"text": "cpp-virtual"
},
{
"code": null,
"e": 7632,
"s": 7628,
"text": "C++"
},
{
"code": null,
"e": 7636,
"s": 7632,
"text": "CPP"
},
{
"code": null,
"e": 7734,
"s": 7636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7777,
"s": 7734,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7811,
"s": 7777,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 7828,
"s": 7811,
"text": "Substring in C++"
},
{
"code": null,
"e": 7853,
"s": 7828,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 7907,
"s": 7853,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7931,
"s": 7907,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 7971,
"s": 7931,
"text": "2D Vector In C++ With User Defined Size"
},
{
"code": null,
"e": 7986,
"s": 7971,
"text": "C++ Data Types"
},
{
"code": null,
"e": 8017,
"s": 7986,
"text": "Templates in C++ with Examples"
}
] |
Program for sum of geometric series | 22 Jun, 2022
A Geometric series is a series with a constant ratio between successive terms. The first term of the series is denoted by a and common ratio is denoted by r. The series looks like this :- a, ar, ar2, ar3, ar4, . . .. The task is to find the sum of such a series. Examples :
Input : a = 1
r = 0.5
n = 10
Output : 1.99805
Input : a = 2
r = 2
n = 15
Output : 65534
A Simple solution to calculate the sum of geometric series.
C++
Java
Python
C#
PHP
// A naive solution for calculating sum of// geometric series.#include<bits/stdc++.h>using namespace std; // function to calculate sum of// geometric seriesfloat sumOfGP(float a, float r, int n){ float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a * r; } return sum;} // driver functionint main(){ int a = 1; // first term float r = 0.5; // common ratio int n = 10; // number of terms cout << sumOfGP(a, r, n) << endl; return 0;}
// A naive solution for calculating sum of// geometric series.import java.io.*; class GFG{ // function to calculate sum of // geometric series static float sumOfGP(float a, float r, int n) { float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a * r; } return sum; } // driver function public static void main(String args[]) { int a = 1; // first term float r = (float)(1/2.0) ;// common ratio int n = 10 ; // number of terms System.out.printf("%.5f",(sumOfGP(a, r, n))); } } //This code is contributed by Nikita Tiwari
# A naive solution for calculating sum of# geometric series. # function to calculate sum of# geometric seriesdef sumOfGP(a, r, n) : sum = 0 i = 0 while i < n : sum = sum + a a = a * r i = i + 1 return sum #driver function a = 1 # first termr = (float)(1/2.0) # common ration = 10 # number of terms print("%.5f" %sumOfGP(a, r, n)), # This code is contributed by Nikita Tiwari
// A naive solution for calculating// sum of geometric series.using System; class GFG { // function to calculate // sum of geometric series static float sumOfGP(float a, float r, int n) { float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a * r; } return sum; } // Driver Code static public void Main () { // first term int a = 1; // common ratio float r = (float)(1/2.0) ; // number of terms int n = 10 ; Console.WriteLine((sumOfGP(a, r, n))); } } // This code is contributed by Ajit.
<?php// A naive solution for calculating// sum of geometric series. // function to calculate sum // of geometric seriesfunction sumOfGP($a, $r, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) { $sum = $sum + $a; $a = $a * $r; } return $sum;} // Driver Code // first term$a = 1; // common ratio$r = 0.5; // number of terms$n = 10; echo(sumOfGP($a, $r, $n)); // This code is contributed by Ajit.?>
Output :
1.99805
Time Complexity: O(n)
Auxiliary Space: O(1)
An Efficient solution to solve the sum of geometric series where first term is a and common ration is r is by the formula :- sum of series = a(1 – rn)/(1 – r). Where r = T2/T1 = T3/T2 = T4/T3 . . . and T1, T2, T3, T4 . . . ,Tn are the first, second, third, . . . ,nth terms respectively. For example – The series is 2, 4, 8, 16, 32, 64, . . . upto 15 elements. In the above series, find the sum of first 15 elements where first term a = 2 and common ration r = 4/2 = 2 or = 8/4 = 2 Then, sum = 2 * (1 – 215) / (1 – 2). sum = 65534
C++
Java
Python
C#
PHP
// An Efficient solution to solve sum of// geometric series.#include<bits/stdc++.h>using namespace std; // function to calculate sum of// geometric seriesfloat sumOfGP(float a, float r, int n){ // calculating and storing sum return (a * (1 - pow(r, n))) / (1 - r);} // driver codeint main(){ float a = 2; // first term float r = 2; // common ratio int n = 15; // number of terms cout << sumOfGP(a, r, n); return 0;}
// An Efficient solution to solve sum of// geometric series.import java.math.*; class GFG{ // function to calculate sum of // geometric series static float sumOfGP(float a, float r, int n) { // calculating and storing sum return (a * (1 - (int)(Math.pow(r, n)))) / (1 - r); } // driver code public static void main(String args[]) { float a = 2; // first term float r = 2; // common ratio int n = 15; // number of terms System.out.println((int)(sumOfGP(a, r, n))); }} //This code is contributed by Nikita Tiwari.
# An Efficient solution to solve sum of# geometric series. # function to calculate sum of# geometric seriesdef sumOfGP( a, r, n) : # calculating and storing sum return (a * (1 - pow(r, n))) / (1 - r) # driver codea = 2 # first termr = 2 # common ration = 15 # number of terms print sumOfGP(a, r, n) # This code is contributed by Nikita Tiwari.
// C# program to An Efficient solution// to solve sum of geometric series.using System; class GFG { // function to calculate sum of // geometric series static float sumOfGP(float a, float r, int n) { // calculating and storing sum return (a * (1 - (int)(Math.Pow(r, n)))) / (1 - r); } // Driver Code public static void Main() { float a = 2; // first term float r = 2; // common ratio int n = 15; // number of terms Console.Write((int)(sumOfGP(a, r, n))); }} // This code is contributed by Nitin Mittal.
<?php// An Efficient solution to solve// sum of geometric series. // function to calculate sum// of geometric seriesfunction sumOfGP($a, $r, $n){ // calculating and storing sum return ($a * (1 - pow($r, $n))) / (1 - $r);} // Driver Code // first term$a = 2; // common ratio$r = 2; // number of terms$n = 15; echo(sumOfGP($a, $r, $n)); // This code is contributed by Ajit.?>
Output :
65534
Time Complexity: Depends on implementation of pow() function in C/C++. In general, we can compute integer powers in O(Log n) time.
Space Complexity: O(1) since using constant variables
This article is contributed by Dharmendra kumar. 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.
nitin mittal
jit_t
kumargaurav97520
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 327,
"s": 53,
"text": "A Geometric series is a series with a constant ratio between successive terms. The first term of the series is denoted by a and common ratio is denoted by r. The series looks like this :- a, ar, ar2, ar3, ar4, . . .. The task is to find the sum of such a series. Examples :"
},
{
"code": null,
"e": 448,
"s": 327,
"text": "Input : a = 1\n r = 0.5\n n = 10\nOutput : 1.99805\n\nInput : a = 2\n r = 2\n n = 15\nOutput : 65534"
},
{
"code": null,
"e": 509,
"s": 448,
"text": "A Simple solution to calculate the sum of geometric series. "
},
{
"code": null,
"e": 513,
"s": 509,
"text": "C++"
},
{
"code": null,
"e": 518,
"s": 513,
"text": "Java"
},
{
"code": null,
"e": 525,
"s": 518,
"text": "Python"
},
{
"code": null,
"e": 528,
"s": 525,
"text": "C#"
},
{
"code": null,
"e": 532,
"s": 528,
"text": "PHP"
},
{
"code": "// A naive solution for calculating sum of// geometric series.#include<bits/stdc++.h>using namespace std; // function to calculate sum of// geometric seriesfloat sumOfGP(float a, float r, int n){ float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a * r; } return sum;} // driver functionint main(){ int a = 1; // first term float r = 0.5; // common ratio int n = 10; // number of terms cout << sumOfGP(a, r, n) << endl; return 0;}",
"e": 1021,
"s": 532,
"text": null
},
{
"code": "// A naive solution for calculating sum of// geometric series.import java.io.*; class GFG{ // function to calculate sum of // geometric series static float sumOfGP(float a, float r, int n) { float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a * r; } return sum; } // driver function public static void main(String args[]) { int a = 1; // first term float r = (float)(1/2.0) ;// common ratio int n = 10 ; // number of terms System.out.printf(\"%.5f\",(sumOfGP(a, r, n))); } } //This code is contributed by Nikita Tiwari",
"e": 1683,
"s": 1021,
"text": null
},
{
"code": "# A naive solution for calculating sum of# geometric series. # function to calculate sum of# geometric seriesdef sumOfGP(a, r, n) : sum = 0 i = 0 while i < n : sum = sum + a a = a * r i = i + 1 return sum #driver function a = 1 # first termr = (float)(1/2.0) # common ration = 10 # number of terms print(\"%.5f\" %sumOfGP(a, r, n)), # This code is contributed by Nikita Tiwari",
"e": 2117,
"s": 1683,
"text": null
},
{
"code": "// A naive solution for calculating// sum of geometric series.using System; class GFG { // function to calculate // sum of geometric series static float sumOfGP(float a, float r, int n) { float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a * r; } return sum; } // Driver Code static public void Main () { // first term int a = 1; // common ratio float r = (float)(1/2.0) ; // number of terms int n = 10 ; Console.WriteLine((sumOfGP(a, r, n))); } } // This code is contributed by Ajit.",
"e": 2843,
"s": 2117,
"text": null
},
{
"code": "<?php// A naive solution for calculating// sum of geometric series. // function to calculate sum // of geometric seriesfunction sumOfGP($a, $r, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) { $sum = $sum + $a; $a = $a * $r; } return $sum;} // Driver Code // first term$a = 1; // common ratio$r = 0.5; // number of terms$n = 10; echo(sumOfGP($a, $r, $n)); // This code is contributed by Ajit.?>",
"e": 3263,
"s": 2843,
"text": null
},
{
"code": null,
"e": 3272,
"s": 3263,
"text": "Output :"
},
{
"code": null,
"e": 3280,
"s": 3272,
"text": "1.99805"
},
{
"code": null,
"e": 3302,
"s": 3280,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 3324,
"s": 3302,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3856,
"s": 3324,
"text": "An Efficient solution to solve the sum of geometric series where first term is a and common ration is r is by the formula :- sum of series = a(1 – rn)/(1 – r). Where r = T2/T1 = T3/T2 = T4/T3 . . . and T1, T2, T3, T4 . . . ,Tn are the first, second, third, . . . ,nth terms respectively. For example – The series is 2, 4, 8, 16, 32, 64, . . . upto 15 elements. In the above series, find the sum of first 15 elements where first term a = 2 and common ration r = 4/2 = 2 or = 8/4 = 2 Then, sum = 2 * (1 – 215) / (1 – 2). sum = 65534 "
},
{
"code": null,
"e": 3860,
"s": 3856,
"text": "C++"
},
{
"code": null,
"e": 3865,
"s": 3860,
"text": "Java"
},
{
"code": null,
"e": 3872,
"s": 3865,
"text": "Python"
},
{
"code": null,
"e": 3875,
"s": 3872,
"text": "C#"
},
{
"code": null,
"e": 3879,
"s": 3875,
"text": "PHP"
},
{
"code": "// An Efficient solution to solve sum of// geometric series.#include<bits/stdc++.h>using namespace std; // function to calculate sum of// geometric seriesfloat sumOfGP(float a, float r, int n){ // calculating and storing sum return (a * (1 - pow(r, n))) / (1 - r);} // driver codeint main(){ float a = 2; // first term float r = 2; // common ratio int n = 15; // number of terms cout << sumOfGP(a, r, n); return 0;}",
"e": 4317,
"s": 3879,
"text": null
},
{
"code": "// An Efficient solution to solve sum of// geometric series.import java.math.*; class GFG{ // function to calculate sum of // geometric series static float sumOfGP(float a, float r, int n) { // calculating and storing sum return (a * (1 - (int)(Math.pow(r, n)))) / (1 - r); } // driver code public static void main(String args[]) { float a = 2; // first term float r = 2; // common ratio int n = 15; // number of terms System.out.println((int)(sumOfGP(a, r, n))); }} //This code is contributed by Nikita Tiwari.",
"e": 4948,
"s": 4317,
"text": null
},
{
"code": "# An Efficient solution to solve sum of# geometric series. # function to calculate sum of# geometric seriesdef sumOfGP( a, r, n) : # calculating and storing sum return (a * (1 - pow(r, n))) / (1 - r) # driver codea = 2 # first termr = 2 # common ration = 15 # number of terms print sumOfGP(a, r, n) # This code is contributed by Nikita Tiwari.",
"e": 5312,
"s": 4948,
"text": null
},
{
"code": "// C# program to An Efficient solution// to solve sum of geometric series.using System; class GFG { // function to calculate sum of // geometric series static float sumOfGP(float a, float r, int n) { // calculating and storing sum return (a * (1 - (int)(Math.Pow(r, n)))) / (1 - r); } // Driver Code public static void Main() { float a = 2; // first term float r = 2; // common ratio int n = 15; // number of terms Console.Write((int)(sumOfGP(a, r, n))); }} // This code is contributed by Nitin Mittal.",
"e": 5929,
"s": 5312,
"text": null
},
{
"code": "<?php// An Efficient solution to solve// sum of geometric series. // function to calculate sum// of geometric seriesfunction sumOfGP($a, $r, $n){ // calculating and storing sum return ($a * (1 - pow($r, $n))) / (1 - $r);} // Driver Code // first term$a = 2; // common ratio$r = 2; // number of terms$n = 15; echo(sumOfGP($a, $r, $n)); // This code is contributed by Ajit.?>",
"e": 6333,
"s": 5929,
"text": null
},
{
"code": null,
"e": 6342,
"s": 6333,
"text": "Output :"
},
{
"code": null,
"e": 6348,
"s": 6342,
"text": "65534"
},
{
"code": null,
"e": 6480,
"s": 6348,
"text": "Time Complexity: Depends on implementation of pow() function in C/C++. In general, we can compute integer powers in O(Log n) time. "
},
{
"code": null,
"e": 6534,
"s": 6480,
"text": "Space Complexity: O(1) since using constant variables"
},
{
"code": null,
"e": 6959,
"s": 6534,
"text": "This article is contributed by Dharmendra kumar. 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": 6972,
"s": 6959,
"text": "nitin mittal"
},
{
"code": null,
"e": 6978,
"s": 6972,
"text": "jit_t"
},
{
"code": null,
"e": 6995,
"s": 6978,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 7002,
"s": 6995,
"text": "series"
},
{
"code": null,
"e": 7015,
"s": 7002,
"text": "Mathematical"
},
{
"code": null,
"e": 7034,
"s": 7015,
"text": "School Programming"
},
{
"code": null,
"e": 7047,
"s": 7034,
"text": "Mathematical"
},
{
"code": null,
"e": 7054,
"s": 7047,
"text": "series"
}
] |
Python Program to Sort the list according to the column using lambda | 11 May, 2020
Given a list, the task is to sort the list according to the column using the lambda approach.
Examples:
Input :array = [[1, 3, 3], [2, 1, 2], [3, 2, 1]]Output :Sorted array specific to column 0, [[1, 3, 3], [2, 1, 2], [3, 2, 1]]Sorted array specific to column 1, [[2, 1, 2], [3, 2, 1], [1, 3, 3]]Sorted array specific to column 2, [[3, 2, 1], [2, 1, 2], [1, 3, 3]]
Input :array = [[‘java’, 1995], [‘c++’, 1983], [‘python’, 1989]]Output :Sorted array specific to column 0, [[‘c++’, 1983], [‘java’, 1995], [‘python’, 1989]]Sorted array specific to column 1, [[‘c++’, 1983], [‘python’, 1989], [‘java’, 1995]]
Approach:
sorted() built-in function in Python gives a new sorted list from an iterable.
key parameter to specify a function to be called on each list element prior to making comparisons.
lambda is used as a function to iterate on each element.
key = lambda x:x[i] here i is the column on which respect to sort the whole list.
Below is the implementation.
# Python code to sorting list # according to the column # sortarray function is defineddef sortarray(array): for i in range(len(array[0])): # sorting array in ascending # order specific to column i, # here i is the column index sortedcolumn = sorted(array, key = lambda x:x[i]) # After sorting array Column 1 print("Sorted array specific to column {}, \ {}".format(i, sortedcolumn)) # Driver code if __name__ == '__main__': # array of size 3 X 2 array = [['java', 1995], ['c++', 1983], ['python', 1989]] # passing array in sortarray function sortarray(array)
Sorted array specific to column 0, [[‘c++’, 1983], [‘java’, 1995], [‘python’, 1989]]Sorted array specific to column 1, [[‘c++’, 1983], [‘python’, 1989], [‘java’, 1995]]
Python list-programs
python-list
Python-sort
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 148,
"s": 54,
"text": "Given a list, the task is to sort the list according to the column using the lambda approach."
},
{
"code": null,
"e": 158,
"s": 148,
"text": "Examples:"
},
{
"code": null,
"e": 419,
"s": 158,
"text": "Input :array = [[1, 3, 3], [2, 1, 2], [3, 2, 1]]Output :Sorted array specific to column 0, [[1, 3, 3], [2, 1, 2], [3, 2, 1]]Sorted array specific to column 1, [[2, 1, 2], [3, 2, 1], [1, 3, 3]]Sorted array specific to column 2, [[3, 2, 1], [2, 1, 2], [1, 3, 3]]"
},
{
"code": null,
"e": 660,
"s": 419,
"text": "Input :array = [[‘java’, 1995], [‘c++’, 1983], [‘python’, 1989]]Output :Sorted array specific to column 0, [[‘c++’, 1983], [‘java’, 1995], [‘python’, 1989]]Sorted array specific to column 1, [[‘c++’, 1983], [‘python’, 1989], [‘java’, 1995]]"
},
{
"code": null,
"e": 670,
"s": 660,
"text": "Approach:"
},
{
"code": null,
"e": 749,
"s": 670,
"text": "sorted() built-in function in Python gives a new sorted list from an iterable."
},
{
"code": null,
"e": 848,
"s": 749,
"text": "key parameter to specify a function to be called on each list element prior to making comparisons."
},
{
"code": null,
"e": 905,
"s": 848,
"text": "lambda is used as a function to iterate on each element."
},
{
"code": null,
"e": 987,
"s": 905,
"text": "key = lambda x:x[i] here i is the column on which respect to sort the whole list."
},
{
"code": null,
"e": 1016,
"s": 987,
"text": "Below is the implementation."
},
{
"code": "# Python code to sorting list # according to the column # sortarray function is defineddef sortarray(array): for i in range(len(array[0])): # sorting array in ascending # order specific to column i, # here i is the column index sortedcolumn = sorted(array, key = lambda x:x[i]) # After sorting array Column 1 print(\"Sorted array specific to column {}, \\ {}\".format(i, sortedcolumn)) # Driver code if __name__ == '__main__': # array of size 3 X 2 array = [['java', 1995], ['c++', 1983], ['python', 1989]] # passing array in sortarray function sortarray(array)",
"e": 1698,
"s": 1016,
"text": null
},
{
"code": null,
"e": 1867,
"s": 1698,
"text": "Sorted array specific to column 0, [[‘c++’, 1983], [‘java’, 1995], [‘python’, 1989]]Sorted array specific to column 1, [[‘c++’, 1983], [‘python’, 1989], [‘java’, 1995]]"
},
{
"code": null,
"e": 1888,
"s": 1867,
"text": "Python list-programs"
},
{
"code": null,
"e": 1900,
"s": 1888,
"text": "python-list"
},
{
"code": null,
"e": 1912,
"s": 1900,
"text": "Python-sort"
},
{
"code": null,
"e": 1919,
"s": 1912,
"text": "Python"
},
{
"code": null,
"e": 1935,
"s": 1919,
"text": "Python Programs"
},
{
"code": null,
"e": 1947,
"s": 1935,
"text": "python-list"
},
{
"code": null,
"e": 2045,
"s": 1947,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2077,
"s": 2045,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2104,
"s": 2077,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2125,
"s": 2104,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2179,
"s": 2148,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2201,
"s": 2179,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2240,
"s": 2201,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2278,
"s": 2240,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2315,
"s": 2278,
"text": "Python Program for Fibonacci numbers"
}
] |
Python | shutil.chown() method | 12 Oct, 2021
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of chowning and removal of files and directories.shutil.chown() method in Python is used to change the owner and /or group of the specified path.
Syntax: shutil.chown(path, user = None, group = None)Parameters: path: A string value representing a valid path. user: A string value representing a system user group: A string value representing a group user and group can be also given by user id (uid) and group id (gid) respectively.Return Type: This method does not return any value.
Code #1: Use of shutil.chown() method to change owner and group of the specified path
Python3
# Python program to explain shutil.chown() method # importing shutil moduleimport shutil # importing Path class of pathlib modulefrom pathlib import Path # Pathpath = '/home/ihritik/Desktop/file.txt' # Get the owner and group# of the specified path# using Path.owner() and# Path.group() methodinfo = Path(path)user = info.owner()group = info.group() # Print owner and group# of the specified pathprint("Current owner and group of the specified path")print("Owner:", user)print("Group:", group) # Now, change the owner and group# of the specified pathuser = 'ihritik'group = 'ihritik'shutil.chown(path, user, group) print("\nOwner and group changed") # Print the owner and group# of the specified pathinfo = Path(path)user = info.owner()group = info.group()print("Current owner:", user)print("Current group:", group) # Change only group# of the specified path# and let owner as it isgroup = 'root' shutil.chown(path, group = group) print("\nOnly group changed") # Print the owner and# group of the specified pathinfo = Path(path)user = info.owner()group = info.group()print("Current owner:", user)print("Current group:", group) # Similarly, we can change# only owner of the# specified path and let# group as it is
Current owner and group of the specified path
Owner: root
Group: root
Owner and group changed
Current owner: ihritik
Current group: ihritik
Only group changed
Current owner: ihritik
Current group: root
Code #2: Use of shutil.chown() method
Python3
# Python program to explain shutil.chown() method # We can also change owner# and group of the specified path# by passing owner id (uid) and# group id (gid) as parameter# instead of passing name of# owner and / or group # importing shutil moduleimport shutil # importing Path class of pathlib modulefrom pathlib import Path # Pathpath = '/home/ihritik/Desktop/file.txt' # Get the owner user and# group of the specified path# using Path.owner() and# Path.group() methodinfo = Path(path)user = info.owner()group = info.group()print("Current owner and group of the specified path")print("Current owner:", user)print("Current group:", group) # Now, change the owner user# and group of the# specified path uid = 0gid = 0shutil.chown(path, uid, gid) print("\nOwner and group changed") # Print the owner user and# group of the specified pathinfo = Path(path)user = info.owner()group = info.group()print("Current owner:", user)print("Current group:", group)
Current owner and group of the specified path
Owner: ihritik
Group: ihritik
Owner and group changed
Current owner: root
Current group: root
Reference: https://docs.python.org/3/library/shutil.html
gabaa406
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Stack in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 374,
"s": 28,
"text": "Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of chowning and removal of files and directories.shutil.chown() method in Python is used to change the owner and /or group of the specified path. "
},
{
"code": null,
"e": 714,
"s": 374,
"text": "Syntax: shutil.chown(path, user = None, group = None)Parameters: path: A string value representing a valid path. user: A string value representing a system user group: A string value representing a group user and group can be also given by user id (uid) and group id (gid) respectively.Return Type: This method does not return any value. "
},
{
"code": null,
"e": 802,
"s": 714,
"text": "Code #1: Use of shutil.chown() method to change owner and group of the specified path "
},
{
"code": null,
"e": 810,
"s": 802,
"text": "Python3"
},
{
"code": "# Python program to explain shutil.chown() method # importing shutil moduleimport shutil # importing Path class of pathlib modulefrom pathlib import Path # Pathpath = '/home/ihritik/Desktop/file.txt' # Get the owner and group# of the specified path# using Path.owner() and# Path.group() methodinfo = Path(path)user = info.owner()group = info.group() # Print owner and group# of the specified pathprint(\"Current owner and group of the specified path\")print(\"Owner:\", user)print(\"Group:\", group) # Now, change the owner and group# of the specified pathuser = 'ihritik'group = 'ihritik'shutil.chown(path, user, group) print(\"\\nOwner and group changed\") # Print the owner and group# of the specified pathinfo = Path(path)user = info.owner()group = info.group()print(\"Current owner:\", user)print(\"Current group:\", group) # Change only group# of the specified path# and let owner as it isgroup = 'root' shutil.chown(path, group = group) print(\"\\nOnly group changed\") # Print the owner and# group of the specified pathinfo = Path(path)user = info.owner()group = info.group()print(\"Current owner:\", user)print(\"Current group:\", group) # Similarly, we can change# only owner of the# specified path and let# group as it is",
"e": 2031,
"s": 810,
"text": null
},
{
"code": null,
"e": 2235,
"s": 2031,
"text": "Current owner and group of the specified path\nOwner: root\nGroup: root\n\nOwner and group changed\nCurrent owner: ihritik\nCurrent group: ihritik\n\nOnly group changed\nCurrent owner: ihritik\nCurrent group: root"
},
{
"code": null,
"e": 2277,
"s": 2237,
"text": "Code #2: Use of shutil.chown() method "
},
{
"code": null,
"e": 2285,
"s": 2277,
"text": "Python3"
},
{
"code": "# Python program to explain shutil.chown() method # We can also change owner# and group of the specified path# by passing owner id (uid) and# group id (gid) as parameter# instead of passing name of# owner and / or group # importing shutil moduleimport shutil # importing Path class of pathlib modulefrom pathlib import Path # Pathpath = '/home/ihritik/Desktop/file.txt' # Get the owner user and# group of the specified path# using Path.owner() and# Path.group() methodinfo = Path(path)user = info.owner()group = info.group()print(\"Current owner and group of the specified path\")print(\"Current owner:\", user)print(\"Current group:\", group) # Now, change the owner user# and group of the# specified path uid = 0gid = 0shutil.chown(path, uid, gid) print(\"\\nOwner and group changed\") # Print the owner user and# group of the specified pathinfo = Path(path)user = info.owner()group = info.group()print(\"Current owner:\", user)print(\"Current group:\", group)",
"e": 3242,
"s": 2285,
"text": null
},
{
"code": null,
"e": 3383,
"s": 3242,
"text": "Current owner and group of the specified path\nOwner: ihritik\nGroup: ihritik\n\nOwner and group changed\nCurrent owner: root\nCurrent group: root"
},
{
"code": null,
"e": 3443,
"s": 3385,
"text": "Reference: https://docs.python.org/3/library/shutil.html "
},
{
"code": null,
"e": 3452,
"s": 3443,
"text": "gabaa406"
},
{
"code": null,
"e": 3467,
"s": 3452,
"text": "python-utility"
},
{
"code": null,
"e": 3474,
"s": 3467,
"text": "Python"
},
{
"code": null,
"e": 3572,
"s": 3474,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3602,
"s": 3572,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3647,
"s": 3602,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3669,
"s": 3647,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3687,
"s": 3669,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3708,
"s": 3687,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3750,
"s": 3708,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3779,
"s": 3750,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3806,
"s": 3779,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3829,
"s": 3806,
"text": "Introduction To PYTHON"
}
] |
What are jQuery string methods? | jQuery string methods helps in string manipulation and makes your work easier while using strings. String methods find the length of the string, a string in a string, extract string parts, etc. jQuery is a JavaScript library, so using JavaScript String functions in it is perfectly fine.
You can try to run the following code to learn how to find the length of a string with string method −
Live Demo
<!DOCTYPE html>
<html>
<body>
<p>Finding the number of characters in "Tutorialspoint"</p>
<button onclick="myFunc()">Get Length</button>
<p id="example"></p>
<script>
function myFunc() {
var str1 = "Tutorialspoint";
var num = str1.length;
document.getElementById("example").innerHTML = num;
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1350,
"s": 1062,
"text": "jQuery string methods helps in string manipulation and makes your work easier while using strings. String methods find the length of the string, a string in a string, extract string parts, etc. jQuery is a JavaScript library, so using JavaScript String functions in it is perfectly fine."
},
{
"code": null,
"e": 1453,
"s": 1350,
"text": "You can try to run the following code to learn how to find the length of a string with string method −"
},
{
"code": null,
"e": 1463,
"s": 1453,
"text": "Live Demo"
},
{
"code": null,
"e": 1799,
"s": 1463,
"text": "<!DOCTYPE html>\n<html>\n<body>\n\n<p>Finding the number of characters in \"Tutorialspoint\"</p>\n\n<button onclick=\"myFunc()\">Get Length</button>\n\n<p id=\"example\"></p>\n\n<script>\nfunction myFunc() {\n var str1 = \"Tutorialspoint\";\n var num = str1.length;\n document.getElementById(\"example\").innerHTML = num;\n}\n</script>\n\n</body>\n</html>"
}
] |
Extract Video Frames from Webcam and Save to Images using Python - GeeksforGeeks | 19 Aug, 2021
OpenCV library can be used to perform multiple operations on videos. Let’s try to do something interesting using CV2. Le’s record a video as form webcam and break the video into the frame by frame and save those frames.
This module does not come built-in with Python. To install it type the below command in the terminal.
pip install opencv-python
Steps Required.
Open the Video file using cv2.VideoCapture(<path_of_video>) or If you do not have any video you can directly use your inbuilt camera using cv2.VideoCapture(0) command.Read frame by frameSave each frame using cv2.imwrite()Release the VideoCapture and destroy all windows
Open the Video file using cv2.VideoCapture(<path_of_video>) or If you do not have any video you can directly use your inbuilt camera using cv2.VideoCapture(0) command.
Read frame by frame
Save each frame using cv2.imwrite()
Release the VideoCapture and destroy all windows
Below is the implementation.
Python3
import cv2 # Opens the inbuilt camera of laptop to capture video.cap = cv2.VideoCapture(0)i = 0 while(cap.isOpened()): ret, frame = cap.read() # This condition prevents from infinite looping # incase video ends. if ret == False: break # Save Frame by Frame into disk using imwrite method cv2.imwrite('Frame'+str(i)+'.jpg', frame) i += 1 cap.release()cv2.destroyAllWindows()
Output:
sagartomar9927
Picked
Python-OpenCV
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
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25665,
"s": 25637,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 25886,
"s": 25665,
"text": "OpenCV library can be used to perform multiple operations on videos. Let’s try to do something interesting using CV2. Le’s record a video as form webcam and break the video into the frame by frame and save those frames. "
},
{
"code": null,
"e": 25988,
"s": 25886,
"text": "This module does not come built-in with Python. To install it type the below command in the terminal."
},
{
"code": null,
"e": 26014,
"s": 25988,
"text": "pip install opencv-python"
},
{
"code": null,
"e": 26030,
"s": 26014,
"text": "Steps Required."
},
{
"code": null,
"e": 26302,
"s": 26030,
"text": "Open the Video file using cv2.VideoCapture(<path_of_video>) or If you do not have any video you can directly use your inbuilt camera using cv2.VideoCapture(0) command.Read frame by frameSave each frame using cv2.imwrite()Release the VideoCapture and destroy all windows"
},
{
"code": null,
"e": 26472,
"s": 26302,
"text": "Open the Video file using cv2.VideoCapture(<path_of_video>) or If you do not have any video you can directly use your inbuilt camera using cv2.VideoCapture(0) command."
},
{
"code": null,
"e": 26492,
"s": 26472,
"text": "Read frame by frame"
},
{
"code": null,
"e": 26528,
"s": 26492,
"text": "Save each frame using cv2.imwrite()"
},
{
"code": null,
"e": 26577,
"s": 26528,
"text": "Release the VideoCapture and destroy all windows"
},
{
"code": null,
"e": 26606,
"s": 26577,
"text": "Below is the implementation."
},
{
"code": null,
"e": 26614,
"s": 26606,
"text": "Python3"
},
{
"code": "import cv2 # Opens the inbuilt camera of laptop to capture video.cap = cv2.VideoCapture(0)i = 0 while(cap.isOpened()): ret, frame = cap.read() # This condition prevents from infinite looping # incase video ends. if ret == False: break # Save Frame by Frame into disk using imwrite method cv2.imwrite('Frame'+str(i)+'.jpg', frame) i += 1 cap.release()cv2.destroyAllWindows()",
"e": 27026,
"s": 26614,
"text": null
},
{
"code": null,
"e": 27035,
"s": 27026,
"text": "Output: "
},
{
"code": null,
"e": 27052,
"s": 27037,
"text": "sagartomar9927"
},
{
"code": null,
"e": 27059,
"s": 27052,
"text": "Picked"
},
{
"code": null,
"e": 27073,
"s": 27059,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 27080,
"s": 27073,
"text": "Python"
},
{
"code": null,
"e": 27178,
"s": 27080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27210,
"s": 27178,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27252,
"s": 27210,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27294,
"s": 27252,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27350,
"s": 27294,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27377,
"s": 27350,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27408,
"s": 27377,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27437,
"s": 27408,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27459,
"s": 27437,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27498,
"s": 27459,
"text": "Python | Get unique values from a list"
}
] |
How to plot a Histogram in MATLAB ? - GeeksforGeeks | 06 Sep, 2021
A Histogram is a diagrammatic representation of a group of data over user-specified ranges. Basically, the histogram contains several bins. Bins are non-overlapping intervals in which the data is spread. In MATLAB we have a function named hist() which allows us to plot a bar graph.
Syntax:
hist(X)
where X represents the data. The X is a vector.
The histogram function uses an algorithm that returns bins and bins width are equal. And these bins spread according to the data given in vector. The interesting thing is that the height of each bin represents the number of points in that bin.
Now let’s move to some examples.
Example 1: A simple Histogram:
MATLAB
% generate 10,000 random numbersy=randn(10000,1) % hist() function to plot the histogram% if the value of bins is not given then% this function choose appropriate numbers% of binhist(y)
Output:
Example 2: Histogram with a given number of bins:
MATLAB
% generate 10,000 random numbersy=randn(10000,1) % assign 50 to variable nbins for% number of binsnbins=50; % hist() function to plot the histogram% hist() function use the nbins variable% and spread the data in 50 binshist(y,nbins)
Output:
Example 3: Histogram of multiple columns:
MATLAB
% generate 10,000 random numbers in 4 groupsy=randn(10000,4) % hist() function to plot the histogram% hist() function use the nbins variable and% spread the data in 50 binshist(y)
Output :
Example 4: Make Histogram of image:
MATLAB
% read the imageI = imread('ngc6543a.jpg'); % display the imageimshow(I)
MATLAB
% imhist() function is used to% draw histogram of imageimhist(I)
Output :
kk9826225
MATLAB
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Boundary Extraction of image using MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Classes and Object in MATLAB
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
Double Integral in MATLAB
Adaptive Histogram Equalization in Image Processing Using MATLAB | [
{
"code": null,
"e": 25899,
"s": 25871,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 26183,
"s": 25899,
"text": "A Histogram is a diagrammatic representation of a group of data over user-specified ranges. Basically, the histogram contains several bins. Bins are non-overlapping intervals in which the data is spread. In MATLAB we have a function named hist() which allows us to plot a bar graph. "
},
{
"code": null,
"e": 26191,
"s": 26183,
"text": "Syntax:"
},
{
"code": null,
"e": 26247,
"s": 26191,
"text": "hist(X)\nwhere X represents the data. The X is a vector."
},
{
"code": null,
"e": 26491,
"s": 26247,
"text": "The histogram function uses an algorithm that returns bins and bins width are equal. And these bins spread according to the data given in vector. The interesting thing is that the height of each bin represents the number of points in that bin."
},
{
"code": null,
"e": 26524,
"s": 26491,
"text": "Now let’s move to some examples."
},
{
"code": null,
"e": 26555,
"s": 26524,
"text": "Example 1: A simple Histogram:"
},
{
"code": null,
"e": 26562,
"s": 26555,
"text": "MATLAB"
},
{
"code": "% generate 10,000 random numbersy=randn(10000,1) % hist() function to plot the histogram% if the value of bins is not given then% this function choose appropriate numbers% of binhist(y)",
"e": 26748,
"s": 26562,
"text": null
},
{
"code": null,
"e": 26761,
"s": 26752,
"text": "Output: "
},
{
"code": null,
"e": 26815,
"s": 26765,
"text": "Example 2: Histogram with a given number of bins:"
},
{
"code": null,
"e": 26824,
"s": 26817,
"text": "MATLAB"
},
{
"code": "% generate 10,000 random numbersy=randn(10000,1) % assign 50 to variable nbins for% number of binsnbins=50; % hist() function to plot the histogram% hist() function use the nbins variable% and spread the data in 50 binshist(y,nbins)",
"e": 27057,
"s": 26824,
"text": null
},
{
"code": null,
"e": 27069,
"s": 27061,
"text": "Output:"
},
{
"code": null,
"e": 27115,
"s": 27073,
"text": "Example 3: Histogram of multiple columns:"
},
{
"code": null,
"e": 27124,
"s": 27117,
"text": "MATLAB"
},
{
"code": "% generate 10,000 random numbers in 4 groupsy=randn(10000,4) % hist() function to plot the histogram% hist() function use the nbins variable and% spread the data in 50 binshist(y)",
"e": 27304,
"s": 27124,
"text": null
},
{
"code": null,
"e": 27318,
"s": 27308,
"text": "Output : "
},
{
"code": null,
"e": 27358,
"s": 27322,
"text": "Example 4: Make Histogram of image:"
},
{
"code": null,
"e": 27367,
"s": 27360,
"text": "MATLAB"
},
{
"code": "% read the imageI = imread('ngc6543a.jpg'); % display the imageimshow(I)",
"e": 27440,
"s": 27367,
"text": null
},
{
"code": null,
"e": 27452,
"s": 27445,
"text": "MATLAB"
},
{
"code": "% imhist() function is used to% draw histogram of imageimhist(I)",
"e": 27517,
"s": 27452,
"text": null
},
{
"code": null,
"e": 27530,
"s": 27521,
"text": "Output :"
},
{
"code": null,
"e": 27544,
"s": 27534,
"text": "kk9826225"
},
{
"code": null,
"e": 27551,
"s": 27544,
"text": "MATLAB"
},
{
"code": null,
"e": 27558,
"s": 27551,
"text": "Picked"
},
{
"code": null,
"e": 27565,
"s": 27558,
"text": "MATLAB"
},
{
"code": null,
"e": 27663,
"s": 27565,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27723,
"s": 27663,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 27796,
"s": 27723,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 27838,
"s": 27796,
"text": "Boundary Extraction of image using MATLAB"
},
{
"code": null,
"e": 27903,
"s": 27838,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 27943,
"s": 27903,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 28004,
"s": 27943,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
},
{
"code": null,
"e": 28033,
"s": 28004,
"text": "Classes and Object in MATLAB"
},
{
"code": null,
"e": 28112,
"s": 28033,
"text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?"
},
{
"code": null,
"e": 28138,
"s": 28112,
"text": "Double Integral in MATLAB"
}
] |
Python os.unlink() Method | Python method unlink() removes (deletes) the file path.If the path is a directory, OSError is raised.
Following is the syntax for unlink() method −
os.unlink(path)
path − This is the path, which is to be removed.
path − This is the path, which is to be removed.
This method does not return any value.
The following example shows the usage of unlink() method.
# !/usr/bin/python
import os, sys
# listing directories
print "The dir is: %s" %os.listdir(os.getcwd())
os.unlink("aa.txt")
# listing directories after removing path
print "The dir after removal of path : %s" %os.listdir(os.getcwd())
When we run above program, it produces following result −
The dir is:
[ 'a1.txt','aa.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
The dir after removal of path :
[ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2346,
"s": 2244,
"text": "Python method unlink() removes (deletes) the file path.If the path is a directory, OSError is raised."
},
{
"code": null,
"e": 2392,
"s": 2346,
"text": "Following is the syntax for unlink() method −"
},
{
"code": null,
"e": 2409,
"s": 2392,
"text": "os.unlink(path)\n"
},
{
"code": null,
"e": 2458,
"s": 2409,
"text": "path − This is the path, which is to be removed."
},
{
"code": null,
"e": 2507,
"s": 2458,
"text": "path − This is the path, which is to be removed."
},
{
"code": null,
"e": 2546,
"s": 2507,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2604,
"s": 2546,
"text": "The following example shows the usage of unlink() method."
},
{
"code": null,
"e": 2842,
"s": 2604,
"text": "# !/usr/bin/python\n\nimport os, sys\n\n# listing directories\nprint \"The dir is: %s\" %os.listdir(os.getcwd())\n\nos.unlink(\"aa.txt\")\n\n# listing directories after removing path\nprint \"The dir after removal of path : %s\" %os.listdir(os.getcwd())"
},
{
"code": null,
"e": 2900,
"s": 2842,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3084,
"s": 2900,
"text": "The dir is:\n [ 'a1.txt','aa.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]\nThe dir after removal of path : \n[ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]\n"
},
{
"code": null,
"e": 3121,
"s": 3084,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3137,
"s": 3121,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3170,
"s": 3137,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3189,
"s": 3170,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3224,
"s": 3189,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3246,
"s": 3224,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3280,
"s": 3246,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3308,
"s": 3280,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3343,
"s": 3308,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3357,
"s": 3343,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3390,
"s": 3357,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3407,
"s": 3390,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3414,
"s": 3407,
"text": " Print"
},
{
"code": null,
"e": 3425,
"s": 3414,
"text": " Add Notes"
}
] |
Program to print Reverse Floyd’s triangle in C | Floyd's triangle is a right-angled triangular array of natural numbers, used in computer science education. It is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner
1 15 14 13 12 11
2 3 10 9 8 7
4 5 6 6 5 4
7 8 9 10 3 2
11 12 13 14 15 1
Floyd's Triangle Reverse of Floyd's Triangle
To print the Floyd’s Triangle −
Accept the number of rows to print the Floyd’s Triangle
Print value 1 for the Row 1
Print two values 2 and 3 in the next row
Print three values 4, 5 and 6 in the next row
Repeat till the number of rows specified
To print the reverse of Floyd’s Triangle −
Accept the number of rows to print the reverse of Floyd’s Triangle
Print the values in the reverse order as specified in the reverse of Floyd’s Triangle
/*Program to print the Reverse of Floyd's Triangle*/
#include<stdio.h>
int main() {
int r,c=1;
int rows,revrows,r1,c1,d;
clrscr();
printf("Enter number of rows to print the Floyd's Triangle: ");
scanf("%d", &rows);
printf("\n");
for (r=1;r<=(rows*(rows+1))/2;r++){
printf("%d ",r);
if(r==(c*(c+1))/2){
printf("\n");
c++;
}
}
printf("\n\n");
/*Printing the Reverse of Floyd's Triangle*/
printf("Enter number of rows to print the reverse of Floyd's Triangle: ");
scanf("%d",&revrows);
printf("\n\n");
printf("Reverse of Floyd's Triangle\n");
printf("\n\n");
d = (revrows*(revrows+1))/2;
for(r1=revrows;r1>=1;r1--){
for(c1=r1;c1>=1;c1--,d--){
printf("%4d", d);
}
printf("\n");
}
getch();
return 0;
} | [
{
"code": null,
"e": 1319,
"s": 1062,
"text": "Floyd's triangle is a right-angled triangular array of natural numbers, used in computer science education. It is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner"
},
{
"code": null,
"e": 1571,
"s": 1319,
"text": "1 15 14 13 12 11\n2 3 10 9 8 7\n4 5 6 6 5 4\n7 8 9 10 3 2\n11 12 13 14 15 1\nFloyd's Triangle Reverse of Floyd's Triangle"
},
{
"code": null,
"e": 1603,
"s": 1571,
"text": "To print the Floyd’s Triangle −"
},
{
"code": null,
"e": 1815,
"s": 1603,
"text": "Accept the number of rows to print the Floyd’s Triangle\nPrint value 1 for the Row 1\nPrint two values 2 and 3 in the next row\nPrint three values 4, 5 and 6 in the next row\nRepeat till the number of rows specified"
},
{
"code": null,
"e": 1858,
"s": 1815,
"text": "To print the reverse of Floyd’s Triangle −"
},
{
"code": null,
"e": 2011,
"s": 1858,
"text": "Accept the number of rows to print the reverse of Floyd’s Triangle\nPrint the values in the reverse order as specified in the reverse of Floyd’s Triangle"
},
{
"code": null,
"e": 2832,
"s": 2011,
"text": "/*Program to print the Reverse of Floyd's Triangle*/\n#include<stdio.h>\nint main() {\n int r,c=1;\n int rows,revrows,r1,c1,d;\n clrscr();\n printf(\"Enter number of rows to print the Floyd's Triangle: \");\n scanf(\"%d\", &rows);\n printf(\"\\n\");\n for (r=1;r<=(rows*(rows+1))/2;r++){\n printf(\"%d \",r);\n if(r==(c*(c+1))/2){\n printf(\"\\n\");\n c++;\n }\n }\n printf(\"\\n\\n\");\n /*Printing the Reverse of Floyd's Triangle*/\n printf(\"Enter number of rows to print the reverse of Floyd's Triangle: \");\n scanf(\"%d\",&revrows);\n printf(\"\\n\\n\");\n printf(\"Reverse of Floyd's Triangle\\n\");\n printf(\"\\n\\n\");\n d = (revrows*(revrows+1))/2;\n for(r1=revrows;r1>=1;r1--){\n for(c1=r1;c1>=1;c1--,d--){\n printf(\"%4d\", d);\n }\n printf(\"\\n\");\n }\n getch();\n return 0;\n}\n"
}
] |
How to add, delete, change ownership (of files) of a group in Linux? | We know that Linux is a multiuser operating system so every file or directory belongs to an owner and group. To change ownership of files or directories we use chown (change ownership) command and to change the group ownership of files or directories we use the chgrp command.
The chgrp (change group) command is used to change group ownership of files or directories in the Linux/Unix operating system.
The general syntax of the chgrp command is as follow −
chgrp [OPTION]... GROUP FILE...
chgrp [OPTION]... --reference=RFILE FILE...
The brief description of options available in the chmod command:
To add a group in the Linux system, we need administrative permission or sudo privilege. If we want to add a new group, we use the addgroup command.
The general syntax of the addgroup command is as follows:
$ sudo addgroup <group name>...
Suppose we have to add a new group snow in the Linux system using the terminal.
$ sudo addgroup snow
To remove a group in the Linux system we need administrative permission or sudo privilege. If we want to remove an existing group, we use the groupdel command.
The general syntax of the groupdel command is as follows:
$ sudo groupdel <group name>...
Suppose we have to delete an existing group snow in the Linux system using the terminal.
$ sudo groupdel snow
To change the group ownership of a file using terminal, we use the chgrp command in the Linux system.
First, we will check the file associated with which group. To check this use below command.
$ ls -l <file name>
The below output is just an example output.
To change the group ownership of a file use below command.
$ sudo chgrp snow file.txt | [
{
"code": null,
"e": 1339,
"s": 1062,
"text": "We know that Linux is a multiuser operating system so every file or directory belongs to an owner and group. To change ownership of files or directories we use chown (change ownership) command and to change the group ownership of files or directories we use the chgrp command."
},
{
"code": null,
"e": 1466,
"s": 1339,
"text": "The chgrp (change group) command is used to change group ownership of files or directories in the Linux/Unix operating system."
},
{
"code": null,
"e": 1521,
"s": 1466,
"text": "The general syntax of the chgrp command is as follow −"
},
{
"code": null,
"e": 1597,
"s": 1521,
"text": "chgrp [OPTION]... GROUP FILE...\nchgrp [OPTION]... --reference=RFILE FILE..."
},
{
"code": null,
"e": 1662,
"s": 1597,
"text": "The brief description of options available in the chmod command:"
},
{
"code": null,
"e": 1811,
"s": 1662,
"text": "To add a group in the Linux system, we need administrative permission or sudo privilege. If we want to add a new group, we use the addgroup command."
},
{
"code": null,
"e": 1869,
"s": 1811,
"text": "The general syntax of the addgroup command is as follows:"
},
{
"code": null,
"e": 1901,
"s": 1869,
"text": "$ sudo addgroup <group name>..."
},
{
"code": null,
"e": 1981,
"s": 1901,
"text": "Suppose we have to add a new group snow in the Linux system using the terminal."
},
{
"code": null,
"e": 2002,
"s": 1981,
"text": "$ sudo addgroup snow"
},
{
"code": null,
"e": 2162,
"s": 2002,
"text": "To remove a group in the Linux system we need administrative permission or sudo privilege. If we want to remove an existing group, we use the groupdel command."
},
{
"code": null,
"e": 2220,
"s": 2162,
"text": "The general syntax of the groupdel command is as follows:"
},
{
"code": null,
"e": 2252,
"s": 2220,
"text": "$ sudo groupdel <group name>..."
},
{
"code": null,
"e": 2341,
"s": 2252,
"text": "Suppose we have to delete an existing group snow in the Linux system using the terminal."
},
{
"code": null,
"e": 2362,
"s": 2341,
"text": "$ sudo groupdel snow"
},
{
"code": null,
"e": 2464,
"s": 2362,
"text": "To change the group ownership of a file using terminal, we use the chgrp command in the Linux system."
},
{
"code": null,
"e": 2556,
"s": 2464,
"text": "First, we will check the file associated with which group. To check this use below command."
},
{
"code": null,
"e": 2576,
"s": 2556,
"text": "$ ls -l <file name>"
},
{
"code": null,
"e": 2620,
"s": 2576,
"text": "The below output is just an example output."
},
{
"code": null,
"e": 2679,
"s": 2620,
"text": "To change the group ownership of a file use below command."
},
{
"code": null,
"e": 2706,
"s": 2679,
"text": "$ sudo chgrp snow file.txt"
}
] |
How to Deploy Web Apps with Azure | by James Briggs | Towards Data Science | Azure — or any other cloud service — has made sharing the fruits of our creative labor easier than ever.
We can take an app built with Angular (an incredibly easy framework to pick-up) and deploy it to the world quicker than the time it takes to make coffee.
That, to me, is truly phenomenal; the ease and speed at which we can develop and deploy are mind-boggling. It unchains our innovative spirit — allowing us to share with the world in minutes.
This article will take us through the steps from lonely Angular app to highly available, hyper-connected Angular app.
All of the services we will use are free (thanks Microsoft) and — honestly — super easy to use. In short, we will cover:
> Preparing Our App
> Setting up our Azure App Service
> Create our Deployment Pipeline with Azure DevOps
Enjoy!
First, we need an app — if you don’t have one, no problem — we can use a Natural Language Generation app, which you can find on GitHub here.
The App Compilation step is repeated in our Azure pipeline. It can be skipped now — but it is useful to be aware of, and useful to confirm that our app compiles.
Azure needs a dist/ directory — which is an Angular-built distribution directory — containing our entire app compiled and ready for production.
To build dist/ we open the Angular CLI and navigate to our Angular app directory. We then tell Angular to build using the production configuration with ng build --prod — the app will then compile into the dist/ directory.
We need to make sure our ng build --prod command outputs our app directly into the dist/ directory. By default, Angular will distribute to dist/<app-name>/ — we change this in angular.json:
Now, inside the dist/ directory we should be able to see index.html — if it is not there, find where it is and adjust the "outputPath" value in angular.json accordingly.
First, we need to head over to the Azure portal — the front-page of the Azure cloud. If you need to sign up, go for it, it should only take a minute.
azure.microsoft.com
Now that we have signed in to the portal, we should be welcomed to the portal screen. If this is your first time in Azure, you will need to sign up for a free trial (we will be sticking to the free tier so that we won’t use any credit!).
We sign up by clicking the big square that says something like “Start with an Azure free trial”.
Once we’ve signed up, we create an App Services instance, like so:
Here we will need to key in a few details for our app. Most of these options will be specific to what you are building — but for Runtime stack select ASP.NET V4.7 and of-course choose the Region closest to you:
Following this, we need to select our Windows Plan — if you have no plan set-up already, we will need to create one. Select Create a resource group and press Dev / Test to find the Free option, like so:
Now we have created our App Service resource! We can view all of our resources by clicking the top-left button (the three horizontal lines) and clicking All Resources.
We can then navigate to our webpage by typing <app service name>.azurewebsites.net into our browser. Where we will see:
Now we need to set up our Azure DevOps project. To do this, head to Azure DevOps and sign in with the same Microsoft account you used in the Azure Portal.
After signing in, you should see the option to create a New organization in the top-right of your screen, click this.
We will then see another window where we name our organization and assign a geography for our organization’s projects. I’m based in Rome, so I chose West Europe.
On the next screen, we can create our project:
Now we have our project set-up, we need to connect our GitHub repository and set up a production build pipeline.
To connect to our GitHub repository, navigate to the Pipelines area with the right toolbar, and click Create Pipeline.
We will be taken to a new window where Azure will ask us where our code is — we are pulling in an existing GitHub repo, so we click GitHub.
We then Authorize AzurePipelines to access our GitHub account in the next window.
The next step is to select the repository we would like to use, for me that is jamescalam/nlg-project — you can use your own repo or simply fork this one.
Now we need to Approve & Install Azure Pipelines for our selected repository.
On the next step, we configure our pipeline to use Node.js with Angular which will generate the following YAML script:
In the script, we can see the steps of our pipeline YAML set-up. First, on line 6 is the trigger — set to master — meaning that whenever the master branch in our GitHub repo is updated, our YAML script will be triggered.
Next — on line 10 — we can see that this will be run on a virtual machine (VM) running Ubuntu. We then see on line 13 that the script will install Node.js to our VM.
Finally, our YAML script installs the Angular CLI and then builds our app using the same method we used earlier to create the dist/ directory — this performs the same function (we can skip this in the earlier stage too, but it is useful for confirming that the app compiles without error).
But we are missing one final step, the deployment to our Azure App Service.
To add this, find Show assistant in the top-right corner — click this. Now we will see a list of all the tasks we can add to our YAML script; we need Azure App Service deploy:
After clicking on this, a form will appear. All we need to do is add our Azure subscription (mine is this weird Russian text — I have no idea why), our App Service name and finally change the Package or folder to dist/.
Now we will get the Azure App Service deploy code added to our YAML script — make sure this is added at the end of the script. So our YAML script should consist of:
triggerpoolsteps- task (install Node.js)- script (npm install Angular CLI and build app)- task (deploy to Azure App Service)
We click save and commit changes to our repo. Finally, click Run.
The YAML pipeline will take a minute or so to run. If nothing seems to be happening and the Job status is stuck in Queued, refresh the page and permit the pipeline to use your description if prompted to do so.
Our job status will change to Success on completion — now we can navigate to our deployed web app using the same web address we used earlier — <app service name>.azurewebsites.net — for me, this is meditations-ai.azurewebsites.net.
That’s all — we now know how to deploy Angular apps with Azure App Services. There are a few skill sets that are not too difficult to learn but make an immense impact on what we can build — this is one of them.
Being able to take an app that we have built-in Angular, and share it with the world quicker than the time it takes to make coffee truly is phenomenal.
If that wasn’t enough, not only have we deployed an app — but we have hooked it directly to our GitHub.
So now, every time we want to push the newest release of our web app to the world, we simply type git push — to me, that is incredible.
I hope that this article is as useful to you as it is for me. I would love to hear your thoughts, questions, or comments — so feel free to get in touch via Twitter or in the comments below.
Thanks for reading!
Interested in more Angular? Feel free to check out this article I wrote on the basics behind building a TensorFlow-based Angular app: | [
{
"code": null,
"e": 277,
"s": 172,
"text": "Azure — or any other cloud service — has made sharing the fruits of our creative labor easier than ever."
},
{
"code": null,
"e": 431,
"s": 277,
"text": "We can take an app built with Angular (an incredibly easy framework to pick-up) and deploy it to the world quicker than the time it takes to make coffee."
},
{
"code": null,
"e": 622,
"s": 431,
"text": "That, to me, is truly phenomenal; the ease and speed at which we can develop and deploy are mind-boggling. It unchains our innovative spirit — allowing us to share with the world in minutes."
},
{
"code": null,
"e": 740,
"s": 622,
"text": "This article will take us through the steps from lonely Angular app to highly available, hyper-connected Angular app."
},
{
"code": null,
"e": 861,
"s": 740,
"text": "All of the services we will use are free (thanks Microsoft) and — honestly — super easy to use. In short, we will cover:"
},
{
"code": null,
"e": 881,
"s": 861,
"text": "> Preparing Our App"
},
{
"code": null,
"e": 916,
"s": 881,
"text": "> Setting up our Azure App Service"
},
{
"code": null,
"e": 967,
"s": 916,
"text": "> Create our Deployment Pipeline with Azure DevOps"
},
{
"code": null,
"e": 974,
"s": 967,
"text": "Enjoy!"
},
{
"code": null,
"e": 1115,
"s": 974,
"text": "First, we need an app — if you don’t have one, no problem — we can use a Natural Language Generation app, which you can find on GitHub here."
},
{
"code": null,
"e": 1277,
"s": 1115,
"text": "The App Compilation step is repeated in our Azure pipeline. It can be skipped now — but it is useful to be aware of, and useful to confirm that our app compiles."
},
{
"code": null,
"e": 1421,
"s": 1277,
"text": "Azure needs a dist/ directory — which is an Angular-built distribution directory — containing our entire app compiled and ready for production."
},
{
"code": null,
"e": 1643,
"s": 1421,
"text": "To build dist/ we open the Angular CLI and navigate to our Angular app directory. We then tell Angular to build using the production configuration with ng build --prod — the app will then compile into the dist/ directory."
},
{
"code": null,
"e": 1833,
"s": 1643,
"text": "We need to make sure our ng build --prod command outputs our app directly into the dist/ directory. By default, Angular will distribute to dist/<app-name>/ — we change this in angular.json:"
},
{
"code": null,
"e": 2003,
"s": 1833,
"text": "Now, inside the dist/ directory we should be able to see index.html — if it is not there, find where it is and adjust the \"outputPath\" value in angular.json accordingly."
},
{
"code": null,
"e": 2153,
"s": 2003,
"text": "First, we need to head over to the Azure portal — the front-page of the Azure cloud. If you need to sign up, go for it, it should only take a minute."
},
{
"code": null,
"e": 2173,
"s": 2153,
"text": "azure.microsoft.com"
},
{
"code": null,
"e": 2411,
"s": 2173,
"text": "Now that we have signed in to the portal, we should be welcomed to the portal screen. If this is your first time in Azure, you will need to sign up for a free trial (we will be sticking to the free tier so that we won’t use any credit!)."
},
{
"code": null,
"e": 2508,
"s": 2411,
"text": "We sign up by clicking the big square that says something like “Start with an Azure free trial”."
},
{
"code": null,
"e": 2575,
"s": 2508,
"text": "Once we’ve signed up, we create an App Services instance, like so:"
},
{
"code": null,
"e": 2786,
"s": 2575,
"text": "Here we will need to key in a few details for our app. Most of these options will be specific to what you are building — but for Runtime stack select ASP.NET V4.7 and of-course choose the Region closest to you:"
},
{
"code": null,
"e": 2989,
"s": 2786,
"text": "Following this, we need to select our Windows Plan — if you have no plan set-up already, we will need to create one. Select Create a resource group and press Dev / Test to find the Free option, like so:"
},
{
"code": null,
"e": 3157,
"s": 2989,
"text": "Now we have created our App Service resource! We can view all of our resources by clicking the top-left button (the three horizontal lines) and clicking All Resources."
},
{
"code": null,
"e": 3277,
"s": 3157,
"text": "We can then navigate to our webpage by typing <app service name>.azurewebsites.net into our browser. Where we will see:"
},
{
"code": null,
"e": 3432,
"s": 3277,
"text": "Now we need to set up our Azure DevOps project. To do this, head to Azure DevOps and sign in with the same Microsoft account you used in the Azure Portal."
},
{
"code": null,
"e": 3550,
"s": 3432,
"text": "After signing in, you should see the option to create a New organization in the top-right of your screen, click this."
},
{
"code": null,
"e": 3712,
"s": 3550,
"text": "We will then see another window where we name our organization and assign a geography for our organization’s projects. I’m based in Rome, so I chose West Europe."
},
{
"code": null,
"e": 3759,
"s": 3712,
"text": "On the next screen, we can create our project:"
},
{
"code": null,
"e": 3872,
"s": 3759,
"text": "Now we have our project set-up, we need to connect our GitHub repository and set up a production build pipeline."
},
{
"code": null,
"e": 3991,
"s": 3872,
"text": "To connect to our GitHub repository, navigate to the Pipelines area with the right toolbar, and click Create Pipeline."
},
{
"code": null,
"e": 4131,
"s": 3991,
"text": "We will be taken to a new window where Azure will ask us where our code is — we are pulling in an existing GitHub repo, so we click GitHub."
},
{
"code": null,
"e": 4213,
"s": 4131,
"text": "We then Authorize AzurePipelines to access our GitHub account in the next window."
},
{
"code": null,
"e": 4368,
"s": 4213,
"text": "The next step is to select the repository we would like to use, for me that is jamescalam/nlg-project — you can use your own repo or simply fork this one."
},
{
"code": null,
"e": 4446,
"s": 4368,
"text": "Now we need to Approve & Install Azure Pipelines for our selected repository."
},
{
"code": null,
"e": 4565,
"s": 4446,
"text": "On the next step, we configure our pipeline to use Node.js with Angular which will generate the following YAML script:"
},
{
"code": null,
"e": 4786,
"s": 4565,
"text": "In the script, we can see the steps of our pipeline YAML set-up. First, on line 6 is the trigger — set to master — meaning that whenever the master branch in our GitHub repo is updated, our YAML script will be triggered."
},
{
"code": null,
"e": 4952,
"s": 4786,
"text": "Next — on line 10 — we can see that this will be run on a virtual machine (VM) running Ubuntu. We then see on line 13 that the script will install Node.js to our VM."
},
{
"code": null,
"e": 5242,
"s": 4952,
"text": "Finally, our YAML script installs the Angular CLI and then builds our app using the same method we used earlier to create the dist/ directory — this performs the same function (we can skip this in the earlier stage too, but it is useful for confirming that the app compiles without error)."
},
{
"code": null,
"e": 5318,
"s": 5242,
"text": "But we are missing one final step, the deployment to our Azure App Service."
},
{
"code": null,
"e": 5494,
"s": 5318,
"text": "To add this, find Show assistant in the top-right corner — click this. Now we will see a list of all the tasks we can add to our YAML script; we need Azure App Service deploy:"
},
{
"code": null,
"e": 5714,
"s": 5494,
"text": "After clicking on this, a form will appear. All we need to do is add our Azure subscription (mine is this weird Russian text — I have no idea why), our App Service name and finally change the Package or folder to dist/."
},
{
"code": null,
"e": 5879,
"s": 5714,
"text": "Now we will get the Azure App Service deploy code added to our YAML script — make sure this is added at the end of the script. So our YAML script should consist of:"
},
{
"code": null,
"e": 6004,
"s": 5879,
"text": "triggerpoolsteps- task (install Node.js)- script (npm install Angular CLI and build app)- task (deploy to Azure App Service)"
},
{
"code": null,
"e": 6070,
"s": 6004,
"text": "We click save and commit changes to our repo. Finally, click Run."
},
{
"code": null,
"e": 6280,
"s": 6070,
"text": "The YAML pipeline will take a minute or so to run. If nothing seems to be happening and the Job status is stuck in Queued, refresh the page and permit the pipeline to use your description if prompted to do so."
},
{
"code": null,
"e": 6512,
"s": 6280,
"text": "Our job status will change to Success on completion — now we can navigate to our deployed web app using the same web address we used earlier — <app service name>.azurewebsites.net — for me, this is meditations-ai.azurewebsites.net."
},
{
"code": null,
"e": 6723,
"s": 6512,
"text": "That’s all — we now know how to deploy Angular apps with Azure App Services. There are a few skill sets that are not too difficult to learn but make an immense impact on what we can build — this is one of them."
},
{
"code": null,
"e": 6875,
"s": 6723,
"text": "Being able to take an app that we have built-in Angular, and share it with the world quicker than the time it takes to make coffee truly is phenomenal."
},
{
"code": null,
"e": 6979,
"s": 6875,
"text": "If that wasn’t enough, not only have we deployed an app — but we have hooked it directly to our GitHub."
},
{
"code": null,
"e": 7115,
"s": 6979,
"text": "So now, every time we want to push the newest release of our web app to the world, we simply type git push — to me, that is incredible."
},
{
"code": null,
"e": 7305,
"s": 7115,
"text": "I hope that this article is as useful to you as it is for me. I would love to hear your thoughts, questions, or comments — so feel free to get in touch via Twitter or in the comments below."
},
{
"code": null,
"e": 7325,
"s": 7305,
"text": "Thanks for reading!"
}
] |
Count ways to reach the nth stair using step 1, 2 or 3 in C++ | We are given a total number of steps in a staircase that is n. A person can reach the next floor by skipping 1, 2 or 3 steps at a time. The goal is to find the number of ways in which the next floor can be reached by doing so.
We will use the recursive method by keeping in mind that to reach any i’th step, a person has to jump from i-1th step ( skip 1 step) , i-2th step (skip 2 steps ) or i-3th step ( skip 3 steps ).
Let’s understand with examples.
Input
N=3 steps
Output
Count of ways to reach the nth stair using step 1, 2 or 3 are: 4
Explanation
There are total 3 steps
Jump from start ( skip 3 ) : 3 step
Jump from 1’st step (skip 2): 1+2
Jump from 2nd step (skip 1): 2+1
No skip 1+1+1
Input
N=6 steps
Output
Count of ways to reach the nth stair using step 1, 2 or 3 are: 24
Explanation
There are total 6 steps
Ways: 1+1+1+1+1+1, 2+1+1+1+1, 3+1+1+1, 3+1+2, 3+2+1, 3+3 and so on.
We are taking integer steps as a total number of steps.
We are taking integer steps as a total number of steps.
Function stairs_step(int steps) takes all steps as input and returns a number of ways to reach the next floor by taking jumps or not..
Function stairs_step(int steps) takes all steps as input and returns a number of ways to reach the next floor by taking jumps or not..
Take the initial variable count as 0 for such ways.
Take the initial variable count as 0 for such ways.
If the number is 0 return 1.
If the number is 0 return 1.
If step count is 1 only 1 way.
If step count is 1 only 1 way.
If step count is 2 only 2 ways ( 1+1 or 2 ).
If step count is 2 only 2 ways ( 1+1 or 2 ).
Else the ways = stairs_step (step-3)+stair_step(step-2)+stair_step(step-1).
Else the ways = stairs_step (step-3)+stair_step(step-2)+stair_step(step-1).
Live Demo
#include <iostream>
using namespace std;
int stairs_step(int steps){
if(steps == 0){
return 1;
}
else if(steps == 1){
return 1;
}
else if (steps == 2){
return 2;
}
else{
return stairs_step(steps - 3) + stairs_step(steps - 2) + stairs_step(steps - 1);
}
}
int main(){
int steps = 5;
cout<<"Count of ways to reach the nth stair using step 1, 2 or 3 are: "<<stairs_step(steps);
return 0;
}
If we run the above code it will generate the following output −
Count of ways to reach the nth stair using step 1, 2 or 3 are: 13 | [
{
"code": null,
"e": 1289,
"s": 1062,
"text": "We are given a total number of steps in a staircase that is n. A person can reach the next floor by skipping 1, 2 or 3 steps at a time. The goal is to find the number of ways in which the next floor can be reached by doing so."
},
{
"code": null,
"e": 1483,
"s": 1289,
"text": "We will use the recursive method by keeping in mind that to reach any i’th step, a person has to jump from i-1th step ( skip 1 step) , i-2th step (skip 2 steps ) or i-3th step ( skip 3 steps )."
},
{
"code": null,
"e": 1515,
"s": 1483,
"text": "Let’s understand with examples."
},
{
"code": null,
"e": 1522,
"s": 1515,
"text": "Input "
},
{
"code": null,
"e": 1532,
"s": 1522,
"text": "N=3 steps"
},
{
"code": null,
"e": 1540,
"s": 1532,
"text": "Output "
},
{
"code": null,
"e": 1605,
"s": 1540,
"text": "Count of ways to reach the nth stair using step 1, 2 or 3 are: 4"
},
{
"code": null,
"e": 1618,
"s": 1605,
"text": "Explanation "
},
{
"code": null,
"e": 1759,
"s": 1618,
"text": "There are total 3 steps\nJump from start ( skip 3 ) : 3 step\nJump from 1’st step (skip 2): 1+2\nJump from 2nd step (skip 1): 2+1\nNo skip 1+1+1"
},
{
"code": null,
"e": 1766,
"s": 1759,
"text": "Input "
},
{
"code": null,
"e": 1776,
"s": 1766,
"text": "N=6 steps"
},
{
"code": null,
"e": 1784,
"s": 1776,
"text": "Output "
},
{
"code": null,
"e": 1850,
"s": 1784,
"text": "Count of ways to reach the nth stair using step 1, 2 or 3 are: 24"
},
{
"code": null,
"e": 1863,
"s": 1850,
"text": "Explanation "
},
{
"code": null,
"e": 1955,
"s": 1863,
"text": "There are total 6 steps\nWays: 1+1+1+1+1+1, 2+1+1+1+1, 3+1+1+1, 3+1+2, 3+2+1, 3+3 and so on."
},
{
"code": null,
"e": 2011,
"s": 1955,
"text": "We are taking integer steps as a total number of steps."
},
{
"code": null,
"e": 2067,
"s": 2011,
"text": "We are taking integer steps as a total number of steps."
},
{
"code": null,
"e": 2202,
"s": 2067,
"text": "Function stairs_step(int steps) takes all steps as input and returns a number of ways to reach the next floor by taking jumps or not.."
},
{
"code": null,
"e": 2337,
"s": 2202,
"text": "Function stairs_step(int steps) takes all steps as input and returns a number of ways to reach the next floor by taking jumps or not.."
},
{
"code": null,
"e": 2389,
"s": 2337,
"text": "Take the initial variable count as 0 for such ways."
},
{
"code": null,
"e": 2441,
"s": 2389,
"text": "Take the initial variable count as 0 for such ways."
},
{
"code": null,
"e": 2470,
"s": 2441,
"text": "If the number is 0 return 1."
},
{
"code": null,
"e": 2499,
"s": 2470,
"text": "If the number is 0 return 1."
},
{
"code": null,
"e": 2530,
"s": 2499,
"text": "If step count is 1 only 1 way."
},
{
"code": null,
"e": 2561,
"s": 2530,
"text": "If step count is 1 only 1 way."
},
{
"code": null,
"e": 2606,
"s": 2561,
"text": "If step count is 2 only 2 ways ( 1+1 or 2 )."
},
{
"code": null,
"e": 2651,
"s": 2606,
"text": "If step count is 2 only 2 ways ( 1+1 or 2 )."
},
{
"code": null,
"e": 2727,
"s": 2651,
"text": "Else the ways = stairs_step (step-3)+stair_step(step-2)+stair_step(step-1)."
},
{
"code": null,
"e": 2803,
"s": 2727,
"text": "Else the ways = stairs_step (step-3)+stair_step(step-2)+stair_step(step-1)."
},
{
"code": null,
"e": 2814,
"s": 2803,
"text": " Live Demo"
},
{
"code": null,
"e": 3258,
"s": 2814,
"text": "#include <iostream>\nusing namespace std;\nint stairs_step(int steps){\n if(steps == 0){\n return 1;\n }\n else if(steps == 1){\n return 1;\n }\n else if (steps == 2){\n return 2;\n }\n else{\n return stairs_step(steps - 3) + stairs_step(steps - 2) + stairs_step(steps - 1);\n }\n}\nint main(){\n int steps = 5;\n cout<<\"Count of ways to reach the nth stair using step 1, 2 or 3 are: \"<<stairs_step(steps);\n return 0;\n}"
},
{
"code": null,
"e": 3323,
"s": 3258,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3389,
"s": 3323,
"text": "Count of ways to reach the nth stair using step 1, 2 or 3 are: 13"
}
] |
How to set the grid color of a table in Java? | To set the grid color of a table, use the setGridColor() method.
table.setGridColor(Color.yellow);
Above, we have used the Color class to set the color.
The following is an example to set the grid color of a table −
package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP));
String[][] rec = {
{ "1", "Steve", "AUS" },
{ "2", "Virat", "IND" },
{ "3", "Kane", "NZ" },
{ "4", "David", "AUS" },
{ "5", "Ben", "ENG" },
{ "6", "Eion", "ENG" },
};
String[] header = { "Rank", "Player", "Country" };
JTable table = new JTable(rec, header);
table.setGridColor(Color.magenta);
table.setRowSelectionAllowed(true);
table.setShowGrid(true);
panel.add(new JScrollPane(table));
frame.add(panel);
frame.setSize(550, 400);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "To set the grid color of a table, use the setGridColor() method."
},
{
"code": null,
"e": 1161,
"s": 1127,
"text": "table.setGridColor(Color.yellow);"
},
{
"code": null,
"e": 1215,
"s": 1161,
"text": "Above, we have used the Color class to set the color."
},
{
"code": null,
"e": 1278,
"s": 1215,
"text": "The following is an example to set the grid color of a table −"
},
{
"code": null,
"e": 2380,
"s": 1278,
"text": "package my;\nimport java.awt.Color;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createEtchedBorder(), \"ODI Rankings\", TitledBorder.CENTER, TitledBorder.TOP));\n String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n };\n String[] header = { \"Rank\", \"Player\", \"Country\" };\n JTable table = new JTable(rec, header);\n table.setGridColor(Color.magenta);\n table.setRowSelectionAllowed(true);\n table.setShowGrid(true);\n panel.add(new JScrollPane(table));\n frame.add(panel);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}"
}
] |
Multitenant DB Container Management | SAP HANA system can be configured in a single container database system or multiple container system. To set up tenant databases, your system should be configured in multiple container mode. You can also convert a single container mode to multiple container mode, before you create and configure tenant database.
When SAP HANA system is installed in multiple container mode, only the system database is created initially. Tenant databases are created by the administrator and then later it can be configured.
You can convert a SAP HANA system to support multitenant database containers using the SAP HANA Database Lifecycle Manager (HDBLCM) resident program in the graphical user interface.
When you convert a Single container system to multitenant database container using HDBLCM, it can’t be reversed.
You can open SAP HANA database lifecycle Manager using the following URL in a web browser.
https://hostname:1129/lmsl/HDBLCM/HDB/index.html
You can also open this browser from SAP HANA Studio. Right-click HANA system → Lifecycle Management → Platform Lifecycle Management → SAP HANA Platform Lifecycle Management.
You can also perform conversion of single container to multitenant database system using SAP HANA Cockpit. Navigate to SAP HANA Platform Lifecycle Manager.
Click Convert to Multitenant Database Containers as shown in the following screenshot.
You can create a tenant database in SAP HANA multiple container system using SAP HANA cockpit. A tenant database can be created from the system database as and when it is required. A tenant database contains all the data - including users, configuration, and connection properties of the original system.
Step 1 − To create a tenant database, you need to navigate to Manage Database app of SAP HANA Cockpit.
Step 2 − To access this tile in SAP HANA Cockpit, you must have the following role assigned: sap.hana.admin.cockpit.sysdb.roles::SysDBAdmin
Step 3 − In the footer toolbar, you have to navigate to Overflow menu → Create Tenant Database.
Step 4 − Enter the name of tenant database and the system user password. You can also specify OS user and group of tenant database.
You can select various optional fields while creating tenant database, such as creating OS user or to add tenant database to a group and many more.
Step 5 − Once you complete the wizard, click Create Tenant Database and it may take some time to complete the creation process.
New database that has been created has been added to manage database app in SAP HANA cockpit. You can also check newly created tenant database using database view command −
SELECT * FROM "PUBLIC"."M_DATABASES
A HANA database administrator can start or stop the tenant databases either individually or all in one go, by starting/stopping the whole system. A tenant database which is individually stopped can’t be started with the whole system and you need to start it individually.
Select the tenant database that you want to start and stop under manage database app in HANA Cockpit. Click Start Tenant database/Stop tenant database to perform a start and stop.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2637,
"s": 2324,
"text": "SAP HANA system can be configured in a single container database system or multiple container system. To set up tenant databases, your system should be configured in multiple container mode. You can also convert a single container mode to multiple container mode, before you create and configure tenant database."
},
{
"code": null,
"e": 2833,
"s": 2637,
"text": "When SAP HANA system is installed in multiple container mode, only the system database is created initially. Tenant databases are created by the administrator and then later it can be configured."
},
{
"code": null,
"e": 3015,
"s": 2833,
"text": "You can convert a SAP HANA system to support multitenant database containers using the SAP HANA Database Lifecycle Manager (HDBLCM) resident program in the graphical user interface."
},
{
"code": null,
"e": 3128,
"s": 3015,
"text": "When you convert a Single container system to multitenant database container using HDBLCM, it can’t be reversed."
},
{
"code": null,
"e": 3219,
"s": 3128,
"text": "You can open SAP HANA database lifecycle Manager using the following URL in a web browser."
},
{
"code": null,
"e": 3269,
"s": 3219,
"text": "https://hostname:1129/lmsl/HDBLCM/HDB/index.html "
},
{
"code": null,
"e": 3443,
"s": 3269,
"text": "You can also open this browser from SAP HANA Studio. Right-click HANA system → Lifecycle Management → Platform Lifecycle Management → SAP HANA Platform Lifecycle Management."
},
{
"code": null,
"e": 3599,
"s": 3443,
"text": "You can also perform conversion of single container to multitenant database system using SAP HANA Cockpit. Navigate to SAP HANA Platform Lifecycle Manager."
},
{
"code": null,
"e": 3686,
"s": 3599,
"text": "Click Convert to Multitenant Database Containers as shown in the following screenshot."
},
{
"code": null,
"e": 3991,
"s": 3686,
"text": "You can create a tenant database in SAP HANA multiple container system using SAP HANA cockpit. A tenant database can be created from the system database as and when it is required. A tenant database contains all the data - including users, configuration, and connection properties of the original system."
},
{
"code": null,
"e": 4094,
"s": 3991,
"text": "Step 1 − To create a tenant database, you need to navigate to Manage Database app of SAP HANA Cockpit."
},
{
"code": null,
"e": 4234,
"s": 4094,
"text": "Step 2 − To access this tile in SAP HANA Cockpit, you must have the following role assigned: sap.hana.admin.cockpit.sysdb.roles::SysDBAdmin"
},
{
"code": null,
"e": 4330,
"s": 4234,
"text": "Step 3 − In the footer toolbar, you have to navigate to Overflow menu → Create Tenant Database."
},
{
"code": null,
"e": 4462,
"s": 4330,
"text": "Step 4 − Enter the name of tenant database and the system user password. You can also specify OS user and group of tenant database."
},
{
"code": null,
"e": 4610,
"s": 4462,
"text": "You can select various optional fields while creating tenant database, such as creating OS user or to add tenant database to a group and many more."
},
{
"code": null,
"e": 4738,
"s": 4610,
"text": "Step 5 − Once you complete the wizard, click Create Tenant Database and it may take some time to complete the creation process."
},
{
"code": null,
"e": 4911,
"s": 4738,
"text": "New database that has been created has been added to manage database app in SAP HANA cockpit. You can also check newly created tenant database using database view command −"
},
{
"code": null,
"e": 4949,
"s": 4911,
"text": "SELECT * FROM \"PUBLIC\".\"M_DATABASES \n"
},
{
"code": null,
"e": 5221,
"s": 4949,
"text": "A HANA database administrator can start or stop the tenant databases either individually or all in one go, by starting/stopping the whole system. A tenant database which is individually stopped can’t be started with the whole system and you need to start it individually."
},
{
"code": null,
"e": 5401,
"s": 5221,
"text": "Select the tenant database that you want to start and stop under manage database app in HANA Cockpit. Click Start Tenant database/Stop tenant database to perform a start and stop."
},
{
"code": null,
"e": 5434,
"s": 5401,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5448,
"s": 5434,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 5481,
"s": 5448,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5493,
"s": 5481,
"text": " Neha Gupta"
},
{
"code": null,
"e": 5528,
"s": 5493,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5543,
"s": 5528,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 5576,
"s": 5543,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5591,
"s": 5576,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 5626,
"s": 5591,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5638,
"s": 5626,
"text": " Neha Malik"
},
{
"code": null,
"e": 5673,
"s": 5638,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5685,
"s": 5673,
"text": " Neha Malik"
},
{
"code": null,
"e": 5692,
"s": 5685,
"text": " Print"
},
{
"code": null,
"e": 5703,
"s": 5692,
"text": " Add Notes"
}
] |
How to change the figsize for matshow() in Jupyter notebook using Matplotlib? | To change the figsize for mathshow, we can use figsize in figure method argument and use fignum in
matshow() method.
Create a new figure or activate an existing figure using figure() method.
Create a dataframe using Pandas.
Use matshow() method to display an array as a matrix in a new figure window.
The argument fignum can take the values None, int, or FalseIf *None*, create a new figure window with automatic numbering.If a nonzero integer, draw into the figure with the given number. Create one, if it does not exist.If 0, use the current axes (or create one if it does not exist).
If *None*, create a new figure window with automatic numbering.
If a nonzero integer, draw into the figure with the given number. Create one, if it does not exist.
If 0, use the current axes (or create one if it does not exist).
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.figure()
df = pd.DataFrame({"col1": [1, 3, 5, 7, 1], "col2": [1, 5, 7, 9, 1]})
plt.matshow(df.corr(), fignum=1)
plt.show() | [
{
"code": null,
"e": 1179,
"s": 1062,
"text": "To change the figsize for mathshow, we can use figsize in figure method argument and use fignum in\nmatshow() method."
},
{
"code": null,
"e": 1253,
"s": 1179,
"text": "Create a new figure or activate an existing figure using figure() method."
},
{
"code": null,
"e": 1286,
"s": 1253,
"text": "Create a dataframe using Pandas."
},
{
"code": null,
"e": 1363,
"s": 1286,
"text": "Use matshow() method to display an array as a matrix in a new figure window."
},
{
"code": null,
"e": 1649,
"s": 1363,
"text": "The argument fignum can take the values None, int, or FalseIf *None*, create a new figure window with automatic numbering.If a nonzero integer, draw into the figure with the given number. Create one, if it does not exist.If 0, use the current axes (or create one if it does not exist)."
},
{
"code": null,
"e": 1713,
"s": 1649,
"text": "If *None*, create a new figure window with automatic numbering."
},
{
"code": null,
"e": 1813,
"s": 1713,
"text": "If a nonzero integer, draw into the figure with the given number. Create one, if it does not exist."
},
{
"code": null,
"e": 1878,
"s": 1813,
"text": "If 0, use the current axes (or create one if it does not exist)."
},
{
"code": null,
"e": 1920,
"s": 1878,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2191,
"s": 1920,
"text": "import pandas as pd\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nplt.figure()\ndf = pd.DataFrame({\"col1\": [1, 3, 5, 7, 1], \"col2\": [1, 5, 7, 9, 1]})\nplt.matshow(df.corr(), fignum=1)\nplt.show()"
}
] |
How to move a file into a different folder on the server using PHP? - GeeksforGeeks | 24 May, 2019
The move_uploaded_file() function and rename() function is used to move a file into a different folder on the server. In this case, we have a file already uploaded in the temp directory of server from where the new directory is assigned by the method. The file temp is fully moved to a new location. The move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved. Thus to move an already uploaded file we use the rename() method.
Syntax:
move_uploaded_file ( string $Sourcefilename, string $destination ) : bool
rename ( string $oldname, string $newname [, resource $context ] ) : bool
move_upload_file() method: This function checks to ensure that the source file or ‘$Sourcefilename’ in the syntax is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination or ‘$destination’ in the syntax.The sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system. Note that if in case the destination file already exists, it will be overwritten. Due to this reason, a file should be checked first for its availability and then the only action must be taken.
rename() method: This method attempts to rename oldname to newname, moving it between directories if necessary. If newname file exists then it will be overwritten. If renaming newname directory exists then this function will emit a warning.
Example: This example is a code which uploads a file in a directory names Uploads and then it changes its path to another directory named as New.
Upload.html
<!DOCTYPE html><html> <head> <title> Move a file into a different folder on the server </title></head> <body> <form action="upfile.php" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="file"> <br><br> <input type="submit" name="submit" value="Submit"> </form></body> </html>
upfile.php
<?php // The target directory of uploading is uploads$target_dir = "uploads/";$target_file = $target_dir . basename($_FILES["file"]["name"]);$uOk = 1; if(isset($_POST["submit"])) { // Check if file already exists if (file_exists($target_file)) { echo "file already exists.<br>"; $uOk = 0; } // Check if $uOk is set to 0 if ($uOk == 0) { echo "Your file was not uploaded.<br>"; } // if uOk=1 then try to upload file else { // $_FILES["file"]["tmp_name"] implies storage path // in tmp directory which is moved to uploads // directory using move_uploaded_file() method if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["file"]["name"]) . " has been uploaded.<br>"; // Moving file to New directory if(rename($target_file, "New/". basename( $_FILES["file"]["name"]))) { echo "File moving operation success<br>"; } else { echo "File moving operation failed..<br>"; } } else { echo "Sorry, there was an error uploading your file.<br>"; } }} ?>
Note: The directories Uploads and New are already existing once and thus you will have to make them if they are not available inside the server.
Code running:Code running with use of rename method (Moving to New)
Important methods:
file_exists($target_file): This method is used to check the existence of path. If it exists then it returns true else it returns false.
basename( $_FILES[“file”][“name”] ): This method is used to get the name of the chosen file and its specialty lies in the fact that it operates on the input string provided by the user and is unaware of the actual file system and provides usage of security feature provided by the browsers.
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
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 create admin login page using PHP?
How to generate PDF file using PHP ?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP | Ternary Operator
How to Install php-curl in Ubuntu ? | [
{
"code": null,
"e": 24972,
"s": 24944,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 25463,
"s": 24972,
"text": "The move_uploaded_file() function and rename() function is used to move a file into a different folder on the server. In this case, we have a file already uploaded in the temp directory of server from where the new directory is assigned by the method. The file temp is fully moved to a new location. The move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved. Thus to move an already uploaded file we use the rename() method."
},
{
"code": null,
"e": 25471,
"s": 25463,
"text": "Syntax:"
},
{
"code": null,
"e": 25620,
"s": 25471,
"text": "move_uploaded_file ( string $Sourcefilename, string $destination ) : bool\nrename ( string $oldname, string $newname [, resource $context ] ) : bool\n"
},
{
"code": null,
"e": 26316,
"s": 25620,
"text": "move_upload_file() method: This function checks to ensure that the source file or ‘$Sourcefilename’ in the syntax is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination or ‘$destination’ in the syntax.The sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system. Note that if in case the destination file already exists, it will be overwritten. Due to this reason, a file should be checked first for its availability and then the only action must be taken."
},
{
"code": null,
"e": 26557,
"s": 26316,
"text": "rename() method: This method attempts to rename oldname to newname, moving it between directories if necessary. If newname file exists then it will be overwritten. If renaming newname directory exists then this function will emit a warning."
},
{
"code": null,
"e": 26703,
"s": 26557,
"text": "Example: This example is a code which uploads a file in a directory names Uploads and then it changes its path to another directory named as New."
},
{
"code": null,
"e": 26715,
"s": 26703,
"text": "Upload.html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Move a file into a different folder on the server </title></head> <body> <form action=\"upfile.php\" method=\"post\" enctype=\"multipart/form-data\"> <input type=\"file\" name=\"file\" id=\"file\"> <br><br> <input type=\"submit\" name=\"submit\" value=\"Submit\"> </form></body> </html> ",
"e": 27134,
"s": 26715,
"text": null
},
{
"code": null,
"e": 27145,
"s": 27134,
"text": "upfile.php"
},
{
"code": "<?php // The target directory of uploading is uploads$target_dir = \"uploads/\";$target_file = $target_dir . basename($_FILES[\"file\"][\"name\"]);$uOk = 1; if(isset($_POST[\"submit\"])) { // Check if file already exists if (file_exists($target_file)) { echo \"file already exists.<br>\"; $uOk = 0; } // Check if $uOk is set to 0 if ($uOk == 0) { echo \"Your file was not uploaded.<br>\"; } // if uOk=1 then try to upload file else { // $_FILES[\"file\"][\"tmp_name\"] implies storage path // in tmp directory which is moved to uploads // directory using move_uploaded_file() method if (move_uploaded_file($_FILES[\"file\"][\"tmp_name\"], $target_file)) { echo \"The file \". basename( $_FILES[\"file\"][\"name\"]) . \" has been uploaded.<br>\"; // Moving file to New directory if(rename($target_file, \"New/\". basename( $_FILES[\"file\"][\"name\"]))) { echo \"File moving operation success<br>\"; } else { echo \"File moving operation failed..<br>\"; } } else { echo \"Sorry, there was an error uploading your file.<br>\"; } }} ?>",
"e": 28480,
"s": 27145,
"text": null
},
{
"code": null,
"e": 28625,
"s": 28480,
"text": "Note: The directories Uploads and New are already existing once and thus you will have to make them if they are not available inside the server."
},
{
"code": null,
"e": 28693,
"s": 28625,
"text": "Code running:Code running with use of rename method (Moving to New)"
},
{
"code": null,
"e": 28712,
"s": 28693,
"text": "Important methods:"
},
{
"code": null,
"e": 28848,
"s": 28712,
"text": "file_exists($target_file): This method is used to check the existence of path. If it exists then it returns true else it returns false."
},
{
"code": null,
"e": 29139,
"s": 28848,
"text": "basename( $_FILES[“file”][“name”] ): This method is used to get the name of the chosen file and its specialty lies in the fact that it operates on the input string provided by the user and is unaware of the actual file system and provides usage of security feature provided by the browsers."
},
{
"code": null,
"e": 29146,
"s": 29139,
"text": "Picked"
},
{
"code": null,
"e": 29150,
"s": 29146,
"text": "PHP"
},
{
"code": null,
"e": 29163,
"s": 29150,
"text": "PHP Programs"
},
{
"code": null,
"e": 29180,
"s": 29163,
"text": "Web Technologies"
},
{
"code": null,
"e": 29207,
"s": 29180,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29211,
"s": 29207,
"text": "PHP"
},
{
"code": null,
"e": 29309,
"s": 29211,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29391,
"s": 29309,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 29442,
"s": 29391,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 29516,
"s": 29442,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 29558,
"s": 29516,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 29595,
"s": 29558,
"text": "How to generate PDF file using PHP ?"
},
{
"code": null,
"e": 29647,
"s": 29595,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 29729,
"s": 29647,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 29771,
"s": 29729,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 29794,
"s": 29771,
"text": "PHP | Ternary Operator"
}
] |
How can we add a JSONArray within JSONObject in Java? | A JSONObject can parse text from a String to produce a map-like object and a JSONArray can parse text from a String to produce a vector-like object. We can also add a JSONArray within JSONObject by first creating a JSONArray with few items and add these array of items to the put() method of JSONObject class.
public JSONObject put(java.lang.String key, java.util.Collection<?> value) throws JSONException
import org.json.*;
public class AddJSONArrayTest {
public static void main(String[] args) throws JSONException {
JSONArray array = new JSONArray();
array.put("INDIA");
array.put("AUSTRALIA");
array.put("ENGLAND");
JSONObject obj = new JSONObject();
obj.put("COUNTRIES", array);
System.out.println(obj);
}
}
{"COUNTRIES":["INDIA","AUSTRALIA","ENGLAND"]} | [
{
"code": null,
"e": 1372,
"s": 1062,
"text": "A JSONObject can parse text from a String to produce a map-like object and a JSONArray can parse text from a String to produce a vector-like object. We can also add a JSONArray within JSONObject by first creating a JSONArray with few items and add these array of items to the put() method of JSONObject class."
},
{
"code": null,
"e": 1468,
"s": 1372,
"text": "public JSONObject put(java.lang.String key, java.util.Collection<?> value) throws JSONException"
},
{
"code": null,
"e": 1823,
"s": 1468,
"text": "import org.json.*;\npublic class AddJSONArrayTest {\n public static void main(String[] args) throws JSONException {\n JSONArray array = new JSONArray();\n array.put(\"INDIA\");\n array.put(\"AUSTRALIA\");\n array.put(\"ENGLAND\");\n JSONObject obj = new JSONObject();\n obj.put(\"COUNTRIES\", array);\n System.out.println(obj);\n }\n}"
},
{
"code": null,
"e": 1869,
"s": 1823,
"text": "{\"COUNTRIES\":[\"INDIA\",\"AUSTRALIA\",\"ENGLAND\"]}"
}
] |
Flatten a Stream of Map in Java using forEach loop - GeeksforGeeks | 11 Dec, 2018
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method.
Examples:
Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]}
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]}
Output: [G, e, e, k, s, F, o, r]
Approach:
Get the Map to be flattened.Create an empty list to collect the flattened elements.With the help of forEach loop, convert each elements of the Map values into stream and add it to the listThis list is the required flattened map.
Get the Map to be flattened.
Create an empty list to collect the flattened elements.
With the help of forEach loop, convert each elements of the Map values into stream and add it to the list
This list is the required flattened map.
Below is the implementation of the above approach:
Example 1: Using lists of integer.
// Java program to flatten a stream of map// using forEach() method import java.util.*;import java.util.stream.*; class GFG { // Function to flatten a Stream of Map public static <T> List<T> flattenStream(Collection<List<T> > lists) { // Create an empty list to collect the stream List<T> finalList = new ArrayList<>(); // Using forEach loop // convert each list into stream // and add the stream into list for (List<T> list : lists) { list.stream() .forEach(finalList::add); } // Return the final flattened list return finalList; } public static void main(String[] args) { // Get the map to be flattened. Map<Integer, List<Integer> > map = new HashMap<>(); map.put(1, Arrays.asList(1, 2)); map.put(2, Arrays.asList(3, 4, 5, 6)); map.put(3, Arrays.asList(7, 8, 9)); // Flatten the Stream List<Integer> flatList = flattenStream(map.values()); // Print the flattened list System.out.println(flatList); }}
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2: Using lists of Characters.
// Java program to flatten a stream of map// using forEach() method import java.util.*;import java.util.stream.*; class GFG { // Function to flatten a Stream of Map public static <T> List<T> flattenStream(Collection<List<T> > lists) { // Create an empty list to collect the stream List<T> finalList = new ArrayList<>(); // Using forEach loop // convert each list into stream // and add the stream into list for (List<T> list : lists) { list.stream() .forEach(finalList::add); } // Return the final flattened list return finalList; } public static void main(String[] args) { // Get the map to be flattened. Map<Integer, List<Character> > map = new HashMap<>(); map.put(1, Arrays.asList('G', 'e', 'e', 'k', 's')); map.put(2, Arrays.asList('F', 'o', 'r')); map.put(3, Arrays.asList('G', 'e', 'e', 'k', 's')); // Flatten the Stream List<Character> flatList = flattenStream(map.values()); // Print the flattened list System.out.println(flatList); }}
[G, e, e, k, s, F, o, r, G, e, e, k, s]
Java - util package
Java-Collections
java-map
Java-Map-Programs
Java-Stream-programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 25495,
"s": 25467,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 25584,
"s": 25495,
"text": "Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method."
},
{
"code": null,
"e": 25594,
"s": 25584,
"text": "Examples:"
},
{
"code": null,
"e": 25783,
"s": 25594,
"text": "Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]}\nOutput: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nInput: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]}\nOutput: [G, e, e, k, s, F, o, r]\n"
},
{
"code": null,
"e": 25793,
"s": 25783,
"text": "Approach:"
},
{
"code": null,
"e": 26022,
"s": 25793,
"text": "Get the Map to be flattened.Create an empty list to collect the flattened elements.With the help of forEach loop, convert each elements of the Map values into stream and add it to the listThis list is the required flattened map."
},
{
"code": null,
"e": 26051,
"s": 26022,
"text": "Get the Map to be flattened."
},
{
"code": null,
"e": 26107,
"s": 26051,
"text": "Create an empty list to collect the flattened elements."
},
{
"code": null,
"e": 26213,
"s": 26107,
"text": "With the help of forEach loop, convert each elements of the Map values into stream and add it to the list"
},
{
"code": null,
"e": 26254,
"s": 26213,
"text": "This list is the required flattened map."
},
{
"code": null,
"e": 26305,
"s": 26254,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26340,
"s": 26305,
"text": "Example 1: Using lists of integer."
},
{
"code": "// Java program to flatten a stream of map// using forEach() method import java.util.*;import java.util.stream.*; class GFG { // Function to flatten a Stream of Map public static <T> List<T> flattenStream(Collection<List<T> > lists) { // Create an empty list to collect the stream List<T> finalList = new ArrayList<>(); // Using forEach loop // convert each list into stream // and add the stream into list for (List<T> list : lists) { list.stream() .forEach(finalList::add); } // Return the final flattened list return finalList; } public static void main(String[] args) { // Get the map to be flattened. Map<Integer, List<Integer> > map = new HashMap<>(); map.put(1, Arrays.asList(1, 2)); map.put(2, Arrays.asList(3, 4, 5, 6)); map.put(3, Arrays.asList(7, 8, 9)); // Flatten the Stream List<Integer> flatList = flattenStream(map.values()); // Print the flattened list System.out.println(flatList); }}",
"e": 27434,
"s": 26340,
"text": null
},
{
"code": null,
"e": 27463,
"s": 27434,
"text": "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
},
{
"code": null,
"e": 27501,
"s": 27463,
"text": "Example 2: Using lists of Characters."
},
{
"code": "// Java program to flatten a stream of map// using forEach() method import java.util.*;import java.util.stream.*; class GFG { // Function to flatten a Stream of Map public static <T> List<T> flattenStream(Collection<List<T> > lists) { // Create an empty list to collect the stream List<T> finalList = new ArrayList<>(); // Using forEach loop // convert each list into stream // and add the stream into list for (List<T> list : lists) { list.stream() .forEach(finalList::add); } // Return the final flattened list return finalList; } public static void main(String[] args) { // Get the map to be flattened. Map<Integer, List<Character> > map = new HashMap<>(); map.put(1, Arrays.asList('G', 'e', 'e', 'k', 's')); map.put(2, Arrays.asList('F', 'o', 'r')); map.put(3, Arrays.asList('G', 'e', 'e', 'k', 's')); // Flatten the Stream List<Character> flatList = flattenStream(map.values()); // Print the flattened list System.out.println(flatList); }}",
"e": 28637,
"s": 27501,
"text": null
},
{
"code": null,
"e": 28678,
"s": 28637,
"text": "[G, e, e, k, s, F, o, r, G, e, e, k, s]\n"
},
{
"code": null,
"e": 28698,
"s": 28678,
"text": "Java - util package"
},
{
"code": null,
"e": 28715,
"s": 28698,
"text": "Java-Collections"
},
{
"code": null,
"e": 28724,
"s": 28715,
"text": "java-map"
},
{
"code": null,
"e": 28742,
"s": 28724,
"text": "Java-Map-Programs"
},
{
"code": null,
"e": 28763,
"s": 28742,
"text": "Java-Stream-programs"
},
{
"code": null,
"e": 28768,
"s": 28763,
"text": "Java"
},
{
"code": null,
"e": 28773,
"s": 28768,
"text": "Java"
},
{
"code": null,
"e": 28790,
"s": 28773,
"text": "Java-Collections"
},
{
"code": null,
"e": 28888,
"s": 28790,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28939,
"s": 28888,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28969,
"s": 28939,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28988,
"s": 28969,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29019,
"s": 28988,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29037,
"s": 29019,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29069,
"s": 29037,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29089,
"s": 29069,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29113,
"s": 29089,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29145,
"s": 29113,
"text": "Multidimensional Arrays in Java"
}
] |
Charset toString() method in Java with Examples - GeeksforGeeks | 28 Mar, 2019
The toString() method is a built-in method of the java.nio.charset returns a string which describes the charset involved.
Syntax:
public final String toString()
Parameters: The function does not accepts any parameter.
Return Value: The function returns a string describing this charset.
Below is the implementation of the above function:
Program 1:
// Java program to demonstrate// the above function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder; public class GFG { public static void main(String[] args) { // Gets charset Charset Charset1 = Charset.forName("UTF8"); // Print System.out.println(Charset1.toString()); }}
UTF-8
Program 2:
// Java program to demonstrate// the above function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder; public class GFG { public static void main(String[] args) { // Gets charset Charset Charset1 = Charset.forName("UTF16"); // Print System.out.println(Charset1.toString()); }}
UTF-16
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/charset/Charset.html#toString–
Java-Charset
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
How to iterate any Map in Java
ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Multidimensional Arrays in Java
Stack Class in Java
LinkedList in Java
Overriding in Java
Set in Java | [
{
"code": null,
"e": 24126,
"s": 24098,
"text": "\n28 Mar, 2019"
},
{
"code": null,
"e": 24248,
"s": 24126,
"text": "The toString() method is a built-in method of the java.nio.charset returns a string which describes the charset involved."
},
{
"code": null,
"e": 24256,
"s": 24248,
"text": "Syntax:"
},
{
"code": null,
"e": 24287,
"s": 24256,
"text": "public final String toString()"
},
{
"code": null,
"e": 24344,
"s": 24287,
"text": "Parameters: The function does not accepts any parameter."
},
{
"code": null,
"e": 24413,
"s": 24344,
"text": "Return Value: The function returns a string describing this charset."
},
{
"code": null,
"e": 24464,
"s": 24413,
"text": "Below is the implementation of the above function:"
},
{
"code": null,
"e": 24475,
"s": 24464,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// the above function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder; public class GFG { public static void main(String[] args) { // Gets charset Charset Charset1 = Charset.forName(\"UTF8\"); // Print System.out.println(Charset1.toString()); }}",
"e": 24856,
"s": 24475,
"text": null
},
{
"code": null,
"e": 24863,
"s": 24856,
"text": "UTF-8\n"
},
{
"code": null,
"e": 24874,
"s": 24863,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// the above function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder; public class GFG { public static void main(String[] args) { // Gets charset Charset Charset1 = Charset.forName(\"UTF16\"); // Print System.out.println(Charset1.toString()); }}",
"e": 25256,
"s": 24874,
"text": null
},
{
"code": null,
"e": 25264,
"s": 25256,
"text": "UTF-16\n"
},
{
"code": null,
"e": 25357,
"s": 25264,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/charset/Charset.html#toString–"
},
{
"code": null,
"e": 25370,
"s": 25357,
"text": "Java-Charset"
},
{
"code": null,
"e": 25385,
"s": 25370,
"text": "Java-Functions"
},
{
"code": null,
"e": 25402,
"s": 25385,
"text": "Java-NIO package"
},
{
"code": null,
"e": 25407,
"s": 25402,
"text": "Java"
},
{
"code": null,
"e": 25412,
"s": 25407,
"text": "Java"
},
{
"code": null,
"e": 25510,
"s": 25412,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25519,
"s": 25510,
"text": "Comments"
},
{
"code": null,
"e": 25532,
"s": 25519,
"text": "Old Comments"
},
{
"code": null,
"e": 25564,
"s": 25532,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 25594,
"s": 25564,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 25625,
"s": 25594,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 25643,
"s": 25625,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 25694,
"s": 25643,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 25726,
"s": 25694,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 25746,
"s": 25726,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 25765,
"s": 25746,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 25784,
"s": 25765,
"text": "Overriding in Java"
}
] |
C# program to Reverse words in a string | Let’s say the following is the string −
Hello World
After reversing the string, the words should be visible like −
olleH dlroW
Use the reverse() method and try the following code to reverse words in a string.
Live Demo
using System;
using System.Linq;
class Demo {
static void Main() {
// original string
string str = "Hello World";
// reverse the string
string res = string.Join(" ", str.Split(' ').Select(s => new String(s.Reverse().ToArray())));
Console.WriteLine(res);
}
}
olleH dlroW | [
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Let’s say the following is the string −"
},
{
"code": null,
"e": 1114,
"s": 1102,
"text": "Hello World"
},
{
"code": null,
"e": 1177,
"s": 1114,
"text": "After reversing the string, the words should be visible like −"
},
{
"code": null,
"e": 1189,
"s": 1177,
"text": "olleH dlroW"
},
{
"code": null,
"e": 1271,
"s": 1189,
"text": "Use the reverse() method and try the following code to reverse words in a string."
},
{
"code": null,
"e": 1281,
"s": 1271,
"text": "Live Demo"
},
{
"code": null,
"e": 1575,
"s": 1281,
"text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n // original string\n string str = \"Hello World\";\n // reverse the string\n string res = string.Join(\" \", str.Split(' ').Select(s => new String(s.Reverse().ToArray())));\n Console.WriteLine(res);\n }\n}"
},
{
"code": null,
"e": 1587,
"s": 1575,
"text": "olleH dlroW"
}
] |
XML DOM - Get Node | In this chapter, we will study about how to get the node value of a XML DOM object. XML documents have a hierarchy of informational units called nodes. Node object has a property nodeValue, which returns the value of the element.
In the following sections, we will discuss −
Getting node value of an element
Getting node value of an element
Getting attribute value of a node
Getting attribute value of a node
The node.xml used in all the following examples is as below −
<Company>
<Employee category = "Technical">
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>[email protected]</Email>
</Employee>
<Employee category = "Non-Technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
<Email>[email protected]</Email>
</Employee>
<Employee category = "Management">
<FirstName>Tanisha</FirstName>
<LastName>Sharma</LastName>
<ContactNo>1234562350</ContactNo>
<Email>[email protected]</Email>
</Employee>
</Company>
The method getElementsByTagName() returns a NodeList of all the Elements in document order with a given tag name.
The following example (getnode_example.htm) parses an XML document (node.xml) into an XML DOM object and extracts the node value of the child node Firstname (index at 0) −
<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/dom/node.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName('FirstName')[0]
y = x.childNodes[0];
document.write(y.nodeValue);
</script>
</body>
</html>
Save this file as getnode_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the node value as Tanmay.
Attributes are part of the XML node elements. A node element can have multiple unique attributes. Attribute gives more information about XML node elements. To be more precise, they define properties of the node elements. An XML attribute is always a name-value pair. This value of the attribute is called the attribute node.
The getAttribute() method retrieves an attribute value by element name.
The following example (get_attribute_example.htm) parses an XML document (node.xml) into an XML DOM object and extracts the attribute value of the category Employee (index at 2) −
<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/dom/node.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName('Employee')[2];
document.write(x.getAttribute('category'));
</script>
</body>
</html>
Save this file as get_attribute_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the attribute value as Management.
41 Lectures
5 hours
Abhishek And Pukhraj
33 Lectures
3.5 hours
Abhishek And Pukhraj
15 Lectures
1 hours
Zach Miller
15 Lectures
4 hours
Prof. Paul Cline, Ed.D
13 Lectures
4 hours
Prof. Paul Cline, Ed.D
17 Lectures
2 hours
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2518,
"s": 2288,
"text": "In this chapter, we will study about how to get the node value of a XML DOM object. XML documents have a hierarchy of informational units called nodes. Node object has a property nodeValue, which returns the value of the element."
},
{
"code": null,
"e": 2563,
"s": 2518,
"text": "In the following sections, we will discuss −"
},
{
"code": null,
"e": 2596,
"s": 2563,
"text": "Getting node value of an element"
},
{
"code": null,
"e": 2629,
"s": 2596,
"text": "Getting node value of an element"
},
{
"code": null,
"e": 2663,
"s": 2629,
"text": "Getting attribute value of a node"
},
{
"code": null,
"e": 2697,
"s": 2663,
"text": "Getting attribute value of a node"
},
{
"code": null,
"e": 2759,
"s": 2697,
"text": "The node.xml used in all the following examples is as below −"
},
{
"code": null,
"e": 3405,
"s": 2759,
"text": "<Company>\n <Employee category = \"Technical\">\n <FirstName>Tanmay</FirstName>\n <LastName>Patil</LastName>\n <ContactNo>1234567890</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n \n <Employee category = \"Non-Technical\">\n <FirstName>Taniya</FirstName>\n <LastName>Mishra</LastName>\n <ContactNo>1234667898</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n \n <Employee category = \"Management\">\n <FirstName>Tanisha</FirstName>\n <LastName>Sharma</LastName>\n <ContactNo>1234562350</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n</Company>"
},
{
"code": null,
"e": 3519,
"s": 3405,
"text": "The method getElementsByTagName() returns a NodeList of all the Elements in document order with a given tag name."
},
{
"code": null,
"e": 3691,
"s": 3519,
"text": "The following example (getnode_example.htm) parses an XML document (node.xml) into an XML DOM object and extracts the node value of the child node Firstname (index at 0) −"
},
{
"code": null,
"e": 4188,
"s": 3691,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n if (window.XMLHttpRequest) {\n xmlhttp = new XMLHttpRequest();\n } else{\n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xmlhttp.open(\"GET\",\"/dom/node.xml\",false);\n xmlhttp.send();\n xmlDoc = xmlhttp.responseXML;\n\n x = xmlDoc.getElementsByTagName('FirstName')[0]\n y = x.childNodes[0];\n document.write(y.nodeValue);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4361,
"s": 4188,
"text": "Save this file as getnode_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the node value as Tanmay."
},
{
"code": null,
"e": 4686,
"s": 4361,
"text": "Attributes are part of the XML node elements. A node element can have multiple unique attributes. Attribute gives more information about XML node elements. To be more precise, they define properties of the node elements. An XML attribute is always a name-value pair. This value of the attribute is called the attribute node."
},
{
"code": null,
"e": 4758,
"s": 4686,
"text": "The getAttribute() method retrieves an attribute value by element name."
},
{
"code": null,
"e": 4938,
"s": 4758,
"text": "The following example (get_attribute_example.htm) parses an XML document (node.xml) into an XML DOM object and extracts the attribute value of the category Employee (index at 2) −"
},
{
"code": null,
"e": 5421,
"s": 4938,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n if (window.XMLHttpRequest) {\n xmlhttp = new XMLHttpRequest();\n } else {\n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xmlhttp.open(\"GET\",\"/dom/node.xml\",false);\n xmlhttp.send();\n xmlDoc = xmlhttp.responseXML;\n\n x = xmlDoc.getElementsByTagName('Employee')[2];\n document.write(x.getAttribute('category'));\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 5609,
"s": 5421,
"text": "Save this file as get_attribute_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the attribute value as Management."
},
{
"code": null,
"e": 5642,
"s": 5609,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5664,
"s": 5642,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5699,
"s": 5664,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5721,
"s": 5699,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5754,
"s": 5721,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5767,
"s": 5754,
"text": " Zach Miller"
},
{
"code": null,
"e": 5800,
"s": 5767,
"text": "\n 15 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5824,
"s": 5800,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 5857,
"s": 5824,
"text": "\n 13 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5881,
"s": 5857,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 5914,
"s": 5881,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5931,
"s": 5914,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5938,
"s": 5931,
"text": " Print"
},
{
"code": null,
"e": 5949,
"s": 5938,
"text": " Add Notes"
}
] |
Modulus of two float or double numbers using C | Here we will see how to get the modulus of two floating or double type data in C. The modulus is basically finding the remainder. For this, we can use the remainder() function in C. The remainder() function is used to compute the floating point remainder of numerator/denominator.
So the remainder(x, y) will be like below.
remainder(x, y) = x – rquote * y
The rquote is the value of x/y. This is rounded towards the nearest integral value. This function takes two arguments of type double, float, long double, and returns the remainder of the same type, that was given as argument. The first argument is numerator, and the second argument is the denominator.
#include <stdio.h>
#include <math.h>
main() {
double x = 14.5, y = 4.1;
double res = remainder(x, y);
printf("Remainder of %lf/%lf is: %lf\n",x,y, res);
x = -34.50;
y = 4.0;
res = remainder(x, y);
printf("Remainder of %lf/%lf is: %lf\n",x,y, res);
x = 65.23;
y = 0;
res = remainder(x, y);
printf("Remainder of %lf/%lf is: %lf\n",x,y, res);
}
Remainder of 14.500000/4.100000 is: -1.900000
Remainder of -34.500000/4.000000 is: 1.500000
Remainder of 65.230000/0.000000 is: -1.#IND00 | [
{
"code": null,
"e": 1343,
"s": 1062,
"text": "Here we will see how to get the modulus of two floating or double type data in C. The modulus is basically finding the remainder. For this, we can use the remainder() function in C. The remainder() function is used to compute the floating point remainder of numerator/denominator."
},
{
"code": null,
"e": 1386,
"s": 1343,
"text": "So the remainder(x, y) will be like below."
},
{
"code": null,
"e": 1419,
"s": 1386,
"text": "remainder(x, y) = x – rquote * y"
},
{
"code": null,
"e": 1722,
"s": 1419,
"text": "The rquote is the value of x/y. This is rounded towards the nearest integral value. This function takes two arguments of type double, float, long double, and returns the remainder of the same type, that was given as argument. The first argument is numerator, and the second argument is the denominator."
},
{
"code": null,
"e": 2097,
"s": 1722,
"text": "#include <stdio.h>\n#include <math.h>\nmain() {\n double x = 14.5, y = 4.1;\n double res = remainder(x, y);\n printf(\"Remainder of %lf/%lf is: %lf\\n\",x,y, res);\n x = -34.50;\n y = 4.0;\n res = remainder(x, y);\n printf(\"Remainder of %lf/%lf is: %lf\\n\",x,y, res);\n x = 65.23;\n y = 0;\n res = remainder(x, y);\n printf(\"Remainder of %lf/%lf is: %lf\\n\",x,y, res);\n}"
},
{
"code": null,
"e": 2235,
"s": 2097,
"text": "Remainder of 14.500000/4.100000 is: -1.900000\nRemainder of -34.500000/4.000000 is: 1.500000\nRemainder of 65.230000/0.000000 is: -1.#IND00"
}
] |
Classes and Objects in C++ | Classes are the prime features of C++ as they support OOPS concepts and are user defined data types. Classes provide the specification for an object and contain data variables as well as functions to manipulate the data in a single package.
A class definition starts with the keyword class and then the class name. After that the class body is defined. It is enclosed by curly braces. A class definition should either contain a semicolon or a list of definitions after it.
An example of a class definition in C++ is as follows.
class student {
int rollno;
char name[50];
float marks;
};
The above class contains the details of a student, namely its roll number, name and marks.
When a class is defined, it is only a specification. There is no memory or storage allocated at that time. So the object is created from the class to access the data and functions defined in the class. A class can also be called the blueprint for an object.
The declaration of an object of class student is given as follows.
Student stu1;
A program that demonstrates classes and objects in C++ is given as follows.
Live Demo
#include <iostream>
using namespace std;
class Student {
public:
int rollno;
char name[50];
float marks;
void display() {
cout<<"Roll Number: "<< rollno <<endl;
cout<<"Name: "<< name <<endl;
cout<<"Marks: "<< marks <<endl;
}
};
int main() {
Student stu1 = {1, "Harry", 91.5};
stu1.display();
return 0;
}
Roll Number: 1
Name: Harry
Marks: 91.5
In the above program, first the class student is defined. It contains the details about the student such as roll number, name and marks. It also contains a member function display() that displays all the student details. The code snippet that demonstrates this is as follows.
class student {
public:
int rollno;
char name[50];
float marks;
void display() {
cout<<"Roll Number: "<< rollno <<endl;
cout<<"Name: "<< name <<endl;
cout<<"Marks: "<< marks <<endl;
}
};
In the function main(), the object of the class student is defined with the student details. Then these details are displayed with a function call to display(). This can be seen as follows.
student stu1 = {1, "Harry", 91.5};
stu1.display(); | [
{
"code": null,
"e": 1303,
"s": 1062,
"text": "Classes are the prime features of C++ as they support OOPS concepts and are user defined data types. Classes provide the specification for an object and contain data variables as well as functions to manipulate the data in a single package."
},
{
"code": null,
"e": 1535,
"s": 1303,
"text": "A class definition starts with the keyword class and then the class name. After that the class body is defined. It is enclosed by curly braces. A class definition should either contain a semicolon or a list of definitions after it."
},
{
"code": null,
"e": 1590,
"s": 1535,
"text": "An example of a class definition in C++ is as follows."
},
{
"code": null,
"e": 1658,
"s": 1590,
"text": "class student {\n int rollno;\n char name[50];\n float marks;\n};"
},
{
"code": null,
"e": 1749,
"s": 1658,
"text": "The above class contains the details of a student, namely its roll number, name and marks."
},
{
"code": null,
"e": 2007,
"s": 1749,
"text": "When a class is defined, it is only a specification. There is no memory or storage allocated at that time. So the object is created from the class to access the data and functions defined in the class. A class can also be called the blueprint for an object."
},
{
"code": null,
"e": 2074,
"s": 2007,
"text": "The declaration of an object of class student is given as follows."
},
{
"code": null,
"e": 2088,
"s": 2074,
"text": "Student stu1;"
},
{
"code": null,
"e": 2164,
"s": 2088,
"text": "A program that demonstrates classes and objects in C++ is given as follows."
},
{
"code": null,
"e": 2175,
"s": 2164,
"text": " Live Demo"
},
{
"code": null,
"e": 2524,
"s": 2175,
"text": "#include <iostream>\nusing namespace std;\nclass Student {\n public:\n int rollno;\n char name[50];\n float marks;\n void display() {\n cout<<\"Roll Number: \"<< rollno <<endl;\n cout<<\"Name: \"<< name <<endl;\n cout<<\"Marks: \"<< marks <<endl;\n }\n};\nint main() {\n Student stu1 = {1, \"Harry\", 91.5};\n stu1.display();\n return 0;\n}"
},
{
"code": null,
"e": 2563,
"s": 2524,
"text": "Roll Number: 1\nName: Harry\nMarks: 91.5"
},
{
"code": null,
"e": 2839,
"s": 2563,
"text": "In the above program, first the class student is defined. It contains the details about the student such as roll number, name and marks. It also contains a member function display() that displays all the student details. The code snippet that demonstrates this is as follows."
},
{
"code": null,
"e": 3062,
"s": 2839,
"text": "class student {\n public:\n int rollno;\n char name[50];\n float marks;\n void display() {\n cout<<\"Roll Number: \"<< rollno <<endl;\n cout<<\"Name: \"<< name <<endl;\n cout<<\"Marks: \"<< marks <<endl;\n }\n};"
},
{
"code": null,
"e": 3252,
"s": 3062,
"text": "In the function main(), the object of the class student is defined with the student details. Then these details are displayed with a function call to display(). This can be seen as follows."
},
{
"code": null,
"e": 3303,
"s": 3252,
"text": "student stu1 = {1, \"Harry\", 91.5};\nstu1.display();"
}
] |
Atbash cipher in Python | Suppose we have a lowercase alphabet string called text. We have to find a new string where every character in text is mapped to its reverse in the alphabet. As an example, a becomes z, b becomes y and so on.
So, if the input is like "abcdefg", then the output will be "zyxwvut"
To solve this, we will follow these steps −
N := ASCII of ('z') + ASCII of ('a')
N := ASCII of ('z') + ASCII of ('a')
return ans by joining each character from ASCII value (N - ASCII of s) for each character s in text
return ans by joining each character from ASCII value (N - ASCII of s) for each character s in text
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, text):
N = ord('z') + ord('a')
ans=''
return ans.join([chr(N - ord(s)) for s in text])
ob = Solution()
print(ob.solve("abcdefg"))
print(ob.solve("hello"))
"abcdefg"
"hello"
zyxwvut
svool | [
{
"code": null,
"e": 1271,
"s": 1062,
"text": "Suppose we have a lowercase alphabet string called text. We have to find a new string where every character in text is mapped to its reverse in the alphabet. As an example, a becomes z, b becomes y and so on."
},
{
"code": null,
"e": 1341,
"s": 1271,
"text": "So, if the input is like \"abcdefg\", then the output will be \"zyxwvut\""
},
{
"code": null,
"e": 1385,
"s": 1341,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1422,
"s": 1385,
"text": "N := ASCII of ('z') + ASCII of ('a')"
},
{
"code": null,
"e": 1459,
"s": 1422,
"text": "N := ASCII of ('z') + ASCII of ('a')"
},
{
"code": null,
"e": 1559,
"s": 1459,
"text": "return ans by joining each character from ASCII value (N - ASCII of s) for each character s in text"
},
{
"code": null,
"e": 1659,
"s": 1559,
"text": "return ans by joining each character from ASCII value (N - ASCII of s) for each character s in text"
},
{
"code": null,
"e": 1729,
"s": 1659,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1740,
"s": 1729,
"text": " Live Demo"
},
{
"code": null,
"e": 1948,
"s": 1740,
"text": "class Solution:\n def solve(self, text):\n N = ord('z') + ord('a')\n ans=''\n return ans.join([chr(N - ord(s)) for s in text])\nob = Solution()\nprint(ob.solve(\"abcdefg\"))\nprint(ob.solve(\"hello\"))"
},
{
"code": null,
"e": 1966,
"s": 1948,
"text": "\"abcdefg\"\n\"hello\""
},
{
"code": null,
"e": 1980,
"s": 1966,
"text": "zyxwvut\nsvool"
}
] |
Feature Engineering — Recursive Feature Elimination With Cross-Validation | by Kaushik Choudhury | Towards Data Science | During the survey and data collection step, we do not know which feature/attribute have a strong influence on the output and the ones which do not have that much effect. Due to this, we collect or measure as many logical attributes as possible in this stage.
The machine learning model becomes complex, and also computationally becomes expensive as the number of features in the training dataset increases.
The aim is to develop a trained machine learning model with the minimal required feature and which can predict the data points with acceptable accuracy. We should not oversimplify the model and lose the significant information by pruning important features, and at the same time have a complex model with too many redundant or lesser important features.
Scikit-Learn library provides several methods to simplify the model with the dimensional reduction of the training dataset and minimal impact on the prediction accuracy of the machine learning model.
In this article, I will discuss recursive feature elimination and cross-validated selection to identify the optimal independent variables and reduce the dimension of the training dataset.
We will be using the breast cancer dataset in Sckit_Learn in this article to explain Recursive Feature Elimination With Cross-Validation (RFECV).
from sklearn.datasets import load_breast_cancerfrom sklearn.feature_selection import RFECVfrom sklearn.ensemble import RandomForestClassifierimport matplotlib.pyplot as plt
Breast cancer dataset has 569 records with 30 independent variables ( features) and binary classes for the dependent variable.
X,y=load_breast_cancer(return_X_y=True,as_frame=True)print(X.shape)
We will be using feature_importances_ attribute in RandomForestClassifier to calculate the significance of the set of features in the iteration.
In RECV, feature importance is calculated based on the estimator selected, and one/few features are dropped in each iteration.
In the below code, the “step” parameter indicates the number of features to remove at each iteration. Here, we will drop one feature in each iteration to identify the right set of features which have maximum influences on the dependent variable. To split data into train/test sets and calculate the feature importance we have mentioned three-fold cross-validation with Stratified K-Folds cross-validator.
You can know more about StratifiedKFold in Scitkit-learn documentation
rfc = RandomForestClassifier(max_depth=8, random_state=0)clf = RFECV(rfc, step=1, cv=3)clf.fit(X, y)
“n_features_” provides the count of features which are crucial and have a strong influence in predicting the dependent variable.
print("Optimal number of features : %d" % clf.n_features_)print("Optimal number of features : ", clf.n_features_)
In Breast cancer dataset, we have 30 features. Based on “feature_importances_” RFECV recommended 16 features are significant in predicting the class of cancer.
“ranking_” attribute provides the importance order of each feature.
print(clf.ranking_)
The features ranked one is most important and has maximum influence on predicting the class of cancer. As the ranking of a feature gets higher, it is relatively lesser important.
Let us visualise the cross-validation score against the number of features to understand the variation in cross-validation scores.
plt.plot(range(1, 31), clf.grid_scores_)plt.xlabel("Number of features selected")plt.ylabel("Cross validation score")plt.show()
We can see that for the combination of 16 most important features the cross-validation scores tops. Increasing the dimension of the training dataset further doesn’t improve the prediction accuracy further.
Key Takeaways and Conclusion
Supervised machine learning aim is to have a generalised trained model with most important features.
We must target to reduce the number of dimensions (features) on which model is trained. It makes the model simpler and also computationally economical.
Recursive Feature Elimination With Cross-Validation indicates the features which are important with importance ranking. This enables us to build the model with optimal dimensions.
As RFECV identifies the best features by eliminating the lesser important or redundant features in steps along with cross-validation, hence it is computationally very expensive. It is one of the disadvantages of Recursive Feature Elimination With Cross-Validation.
Learn to select the independent variable with exploratory data analysis and statistics in the article How to identify the right independent variables for Machine Learning Supervised Algorithms? | [
{
"code": null,
"e": 431,
"s": 172,
"text": "During the survey and data collection step, we do not know which feature/attribute have a strong influence on the output and the ones which do not have that much effect. Due to this, we collect or measure as many logical attributes as possible in this stage."
},
{
"code": null,
"e": 579,
"s": 431,
"text": "The machine learning model becomes complex, and also computationally becomes expensive as the number of features in the training dataset increases."
},
{
"code": null,
"e": 933,
"s": 579,
"text": "The aim is to develop a trained machine learning model with the minimal required feature and which can predict the data points with acceptable accuracy. We should not oversimplify the model and lose the significant information by pruning important features, and at the same time have a complex model with too many redundant or lesser important features."
},
{
"code": null,
"e": 1133,
"s": 933,
"text": "Scikit-Learn library provides several methods to simplify the model with the dimensional reduction of the training dataset and minimal impact on the prediction accuracy of the machine learning model."
},
{
"code": null,
"e": 1321,
"s": 1133,
"text": "In this article, I will discuss recursive feature elimination and cross-validated selection to identify the optimal independent variables and reduce the dimension of the training dataset."
},
{
"code": null,
"e": 1467,
"s": 1321,
"text": "We will be using the breast cancer dataset in Sckit_Learn in this article to explain Recursive Feature Elimination With Cross-Validation (RFECV)."
},
{
"code": null,
"e": 1640,
"s": 1467,
"text": "from sklearn.datasets import load_breast_cancerfrom sklearn.feature_selection import RFECVfrom sklearn.ensemble import RandomForestClassifierimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1767,
"s": 1640,
"text": "Breast cancer dataset has 569 records with 30 independent variables ( features) and binary classes for the dependent variable."
},
{
"code": null,
"e": 1835,
"s": 1767,
"text": "X,y=load_breast_cancer(return_X_y=True,as_frame=True)print(X.shape)"
},
{
"code": null,
"e": 1980,
"s": 1835,
"text": "We will be using feature_importances_ attribute in RandomForestClassifier to calculate the significance of the set of features in the iteration."
},
{
"code": null,
"e": 2107,
"s": 1980,
"text": "In RECV, feature importance is calculated based on the estimator selected, and one/few features are dropped in each iteration."
},
{
"code": null,
"e": 2512,
"s": 2107,
"text": "In the below code, the “step” parameter indicates the number of features to remove at each iteration. Here, we will drop one feature in each iteration to identify the right set of features which have maximum influences on the dependent variable. To split data into train/test sets and calculate the feature importance we have mentioned three-fold cross-validation with Stratified K-Folds cross-validator."
},
{
"code": null,
"e": 2583,
"s": 2512,
"text": "You can know more about StratifiedKFold in Scitkit-learn documentation"
},
{
"code": null,
"e": 2684,
"s": 2583,
"text": "rfc = RandomForestClassifier(max_depth=8, random_state=0)clf = RFECV(rfc, step=1, cv=3)clf.fit(X, y)"
},
{
"code": null,
"e": 2813,
"s": 2684,
"text": "“n_features_” provides the count of features which are crucial and have a strong influence in predicting the dependent variable."
},
{
"code": null,
"e": 2927,
"s": 2813,
"text": "print(\"Optimal number of features : %d\" % clf.n_features_)print(\"Optimal number of features : \", clf.n_features_)"
},
{
"code": null,
"e": 3087,
"s": 2927,
"text": "In Breast cancer dataset, we have 30 features. Based on “feature_importances_” RFECV recommended 16 features are significant in predicting the class of cancer."
},
{
"code": null,
"e": 3155,
"s": 3087,
"text": "“ranking_” attribute provides the importance order of each feature."
},
{
"code": null,
"e": 3175,
"s": 3155,
"text": "print(clf.ranking_)"
},
{
"code": null,
"e": 3354,
"s": 3175,
"text": "The features ranked one is most important and has maximum influence on predicting the class of cancer. As the ranking of a feature gets higher, it is relatively lesser important."
},
{
"code": null,
"e": 3485,
"s": 3354,
"text": "Let us visualise the cross-validation score against the number of features to understand the variation in cross-validation scores."
},
{
"code": null,
"e": 3613,
"s": 3485,
"text": "plt.plot(range(1, 31), clf.grid_scores_)plt.xlabel(\"Number of features selected\")plt.ylabel(\"Cross validation score\")plt.show()"
},
{
"code": null,
"e": 3819,
"s": 3613,
"text": "We can see that for the combination of 16 most important features the cross-validation scores tops. Increasing the dimension of the training dataset further doesn’t improve the prediction accuracy further."
},
{
"code": null,
"e": 3848,
"s": 3819,
"text": "Key Takeaways and Conclusion"
},
{
"code": null,
"e": 3949,
"s": 3848,
"text": "Supervised machine learning aim is to have a generalised trained model with most important features."
},
{
"code": null,
"e": 4101,
"s": 3949,
"text": "We must target to reduce the number of dimensions (features) on which model is trained. It makes the model simpler and also computationally economical."
},
{
"code": null,
"e": 4281,
"s": 4101,
"text": "Recursive Feature Elimination With Cross-Validation indicates the features which are important with importance ranking. This enables us to build the model with optimal dimensions."
},
{
"code": null,
"e": 4546,
"s": 4281,
"text": "As RFECV identifies the best features by eliminating the lesser important or redundant features in steps along with cross-validation, hence it is computationally very expensive. It is one of the disadvantages of Recursive Feature Elimination With Cross-Validation."
}
] |
Using R for Exploratory Data Analysis (EDA) — Analyzing Golf Stats | by Jeff Griesemer | Towards Data Science | Whether you’re a Data Architect, Data Engineer, Data Analyst, or Data Scientist, we have to work with unfamiliar datasets when starting a new data project. It’s a little like having a blind date with a new dataset. You’ll want to get to know more about it before feeling comfortable.
So, how do we get there? The answer is Exploratory Data Analysis (EDA).
Exploratory Data Analysis is a term for initial analysis and findings done with data sets, usually early on in an analytical process.
As a data professional, we’ll sleep much better having gone through this process. Much time is wasted in future steps if this step is ignored.. re-work is needed to resolve data issues well after architecture foundations and data processing pipelines have been built.
Sample Dataset
With all the 4 majors done, and Tiger coming off his historic Master’s victory, why not look at some golf statistics. I found high-level stats for 2019 on the espn.com website http://www.espn.com/golf/statistics. I put the contents into a Googlesheet for easy access. As you will soon see, this is a very basic dataset but will allow us to focus on the EDA process.
Below are sample rows of our dataset.
We’ll load the dataset into R using the “googlesheets” library. (Googlesheet filename is “golf_stats_espn” and the sheetname is “2019_stats”).
library(googlesheets)googlesheet <- gs_title(“golf_stats_espn”)df_2019 <- googlesheet %>% gs_read(ws = “2019_stats”)
EDA Step 1 : Data Validation and Data Quality
The str() function will do a sanity check on the structure and show sample data for each variable.
str(df_2019)
If you have experience with R, you are probably familiar with the summary() function. It works well, but a more complete function is the skim() function from the “skimr” package. It breaks down the variables by type with relevant summary information, PLUS a small histogram for each numeric variable.
library(skimr)skim(df_2019)
Looks good except for the “AGE” variable. With R and many other analytics tools, data-types are assigned automatically as contents are read in, referred to as “schema-on-read”. For “AGE”, a character-type was assigned to our variable rather than a numeric-type. However, I’d like to treat AGE as a numeric-type to potentially apply numeric functions downstream. Why did R create the AGE variable as a character-type?
Let’s do more EDA and run a table() function on the AGE variable.
with(df_2019, table(AGE))
The table() function shows distinct values for the variable on the top line, and the number of occurrences in the line below it. For the AGE variable, we can see 1 occurrence of “--”. R had no choice but to define the variable as a “character” type.
We can fix that by using the “DPLYR” package. DPLYR specializes in “data wrangling”. You can efficiently accomplish a lot with this package — dataframe manipulation, transformations, filtering, aggregations, etc.
The R command below creates a new dataframe after performing the actions described by the bullets.
df_2019_filtered <- df_2019 %>% # create new dataframe mutate(AGE_numeric = !(is.na(as.numeric(AGE)))) %>% filter(AGE_numeric == TRUE) %>% mutate(AGE = as.numeric(AGE))
mutate → creates a new boolean variable identifying whether it’s value is numeric
filter → uses the new boolean variable created in the mutate line above it to filter off non-numeric
mutate → replaces the “AGE” variable; now defined as a numeric variable
Below is our new dataframe.
One more adjustment, I’m going to rename the column “RK” to a better name.
df_2019_filtered <- rename(df_2019_filtered, “RANK_DRV_ACC” = “RK”)
Let’s pause here for a minute.
Handling Dirty Data
For this article, the missing AGE rows were filtered out. In a real analytics project, we’ll have to look at the best course of action to take (filter the row, replace the character data, replace with NULL, etc).
Exploratory Data Analysis (EDA) — Part 2
With our dataset examined and cleaned...
Part 2 leans more toward Data Analysts and Data Scientists. You may be surprised at the insights that can be derived during this phase, even on this very basic dataset.
plot_histogram()
We’ll use the “DataExplorer” library to learn more about our dataset. The plot_histogram() function will return a separate bar chart for each of our numeric variables. It shows the frequency (number of occurrences) for each value in the variable.
library(DataExplorer)plot_histogram(df_2019_filtered)
For example, the “GREENS_REG” variable contains values roughly between 55 and 75. Based on the bar chart, we see most golfers are hitting Greens about 65–70% of the time.
plot_boxplot()
The boxplot (box and whisker diagram) displays the distribution of data for a variable. The box shows us a “five number summary” — minimum, first quartile, median, third quartile, and maximum.
The plot_boxplot() function below created 5 bins/partitions. We’ll focus first on the Yards-per-Drive (YDS_DRIVE) variable.
plot_boxplot(df_2019_filtered, by = “YDS_DRIVE”)
We can see some very interesting correlations look at the “AGE” variable compared with the “YDS per DRIVE”.
The older guys don’t hit as far.
There is one outlier. Someone in their mid-50’s is still hitting it quite far compared to the others in that age group.
Next, let’s do another boxplot from the “AGE” perspective.
plot_boxplot(df_2019_filtered, by = “AGE”)
The oldest group (48–55) in the upper left corner has a very low “Driving Accuracy” (DRIVING_ACC). I would expect the older players to hit the ball shorter, but more accurate... that is not true, the data does not lie.
The older group (48–55) also struggles with putting. They have the highest average putts per hole (PUTT_AVG).
Exploratory Data Analysis (EDA) — Part 3
Let’s take this analysis to another level.
ggcorrplot()
The functionality in this library gets closer to where a Data Scientist spends time.
The “ggcorrplot” provides us with a “heatmap” showing the significance (or lack of significance) between the relationships. A human cannot possibly stare at a spreadsheet and determine patterns/relationships between columns and rows of data.
Let’s put the “ggcorrplot” library to work. Sometimes it’s all about working smarter, not harder!
library(ggcorrplot)ggcorrplot(corr, type = “lower”, outline.col = “black”, lab=TRUE, ggtheme = ggplot2::theme_gray, colors = c(“#6D9EC1”, “white”, “#E46726”))
Running that function was much easier than staring at a spreadsheet, attempting to see relationships between rows and columns!
1 . The most significant relationship between our variables is “Yards per Drive” and “Greens Hit in Regulation”.
2 . On the opposite side, the most significant inverse relationship exists between “Age” and “Yard per Drive”.
If you like circles better than squares, below is the same data using the circle method.
ggcorrplot(corr, type = “lower”, outline.col = “black”, method=”circle”, ggtheme = ggplot2::theme_gray, colors = c(“#6D9EC1”, “white”, “#E46726”))
Conclusion
Although the EDA process is critically important, it is only the beginning of a typical data analytics project lifecycle. Most likely an organization’s valuable data will not be coming from a googlesheet, but will more likely be buried in disparate databases, or coming from a 3rd party vendor, or possibly even an IoT data stream.
Leveraging R and the EDA process will help pave the way toward a successful analytics project.
Jeff Griesemer is an Analytics Developer at Froedtert Health. | [
{
"code": null,
"e": 455,
"s": 171,
"text": "Whether you’re a Data Architect, Data Engineer, Data Analyst, or Data Scientist, we have to work with unfamiliar datasets when starting a new data project. It’s a little like having a blind date with a new dataset. You’ll want to get to know more about it before feeling comfortable."
},
{
"code": null,
"e": 527,
"s": 455,
"text": "So, how do we get there? The answer is Exploratory Data Analysis (EDA)."
},
{
"code": null,
"e": 661,
"s": 527,
"text": "Exploratory Data Analysis is a term for initial analysis and findings done with data sets, usually early on in an analytical process."
},
{
"code": null,
"e": 929,
"s": 661,
"text": "As a data professional, we’ll sleep much better having gone through this process. Much time is wasted in future steps if this step is ignored.. re-work is needed to resolve data issues well after architecture foundations and data processing pipelines have been built."
},
{
"code": null,
"e": 944,
"s": 929,
"text": "Sample Dataset"
},
{
"code": null,
"e": 1310,
"s": 944,
"text": "With all the 4 majors done, and Tiger coming off his historic Master’s victory, why not look at some golf statistics. I found high-level stats for 2019 on the espn.com website http://www.espn.com/golf/statistics. I put the contents into a Googlesheet for easy access. As you will soon see, this is a very basic dataset but will allow us to focus on the EDA process."
},
{
"code": null,
"e": 1348,
"s": 1310,
"text": "Below are sample rows of our dataset."
},
{
"code": null,
"e": 1491,
"s": 1348,
"text": "We’ll load the dataset into R using the “googlesheets” library. (Googlesheet filename is “golf_stats_espn” and the sheetname is “2019_stats”)."
},
{
"code": null,
"e": 1608,
"s": 1491,
"text": "library(googlesheets)googlesheet <- gs_title(“golf_stats_espn”)df_2019 <- googlesheet %>% gs_read(ws = “2019_stats”)"
},
{
"code": null,
"e": 1654,
"s": 1608,
"text": "EDA Step 1 : Data Validation and Data Quality"
},
{
"code": null,
"e": 1753,
"s": 1654,
"text": "The str() function will do a sanity check on the structure and show sample data for each variable."
},
{
"code": null,
"e": 1766,
"s": 1753,
"text": "str(df_2019)"
},
{
"code": null,
"e": 2067,
"s": 1766,
"text": "If you have experience with R, you are probably familiar with the summary() function. It works well, but a more complete function is the skim() function from the “skimr” package. It breaks down the variables by type with relevant summary information, PLUS a small histogram for each numeric variable."
},
{
"code": null,
"e": 2095,
"s": 2067,
"text": "library(skimr)skim(df_2019)"
},
{
"code": null,
"e": 2512,
"s": 2095,
"text": "Looks good except for the “AGE” variable. With R and many other analytics tools, data-types are assigned automatically as contents are read in, referred to as “schema-on-read”. For “AGE”, a character-type was assigned to our variable rather than a numeric-type. However, I’d like to treat AGE as a numeric-type to potentially apply numeric functions downstream. Why did R create the AGE variable as a character-type?"
},
{
"code": null,
"e": 2578,
"s": 2512,
"text": "Let’s do more EDA and run a table() function on the AGE variable."
},
{
"code": null,
"e": 2604,
"s": 2578,
"text": "with(df_2019, table(AGE))"
},
{
"code": null,
"e": 2854,
"s": 2604,
"text": "The table() function shows distinct values for the variable on the top line, and the number of occurrences in the line below it. For the AGE variable, we can see 1 occurrence of “--”. R had no choice but to define the variable as a “character” type."
},
{
"code": null,
"e": 3067,
"s": 2854,
"text": "We can fix that by using the “DPLYR” package. DPLYR specializes in “data wrangling”. You can efficiently accomplish a lot with this package — dataframe manipulation, transformations, filtering, aggregations, etc."
},
{
"code": null,
"e": 3166,
"s": 3067,
"text": "The R command below creates a new dataframe after performing the actions described by the bullets."
},
{
"code": null,
"e": 3346,
"s": 3166,
"text": "df_2019_filtered <- df_2019 %>% # create new dataframe mutate(AGE_numeric = !(is.na(as.numeric(AGE)))) %>% filter(AGE_numeric == TRUE) %>% mutate(AGE = as.numeric(AGE))"
},
{
"code": null,
"e": 3428,
"s": 3346,
"text": "mutate → creates a new boolean variable identifying whether it’s value is numeric"
},
{
"code": null,
"e": 3529,
"s": 3428,
"text": "filter → uses the new boolean variable created in the mutate line above it to filter off non-numeric"
},
{
"code": null,
"e": 3601,
"s": 3529,
"text": "mutate → replaces the “AGE” variable; now defined as a numeric variable"
},
{
"code": null,
"e": 3629,
"s": 3601,
"text": "Below is our new dataframe."
},
{
"code": null,
"e": 3704,
"s": 3629,
"text": "One more adjustment, I’m going to rename the column “RK” to a better name."
},
{
"code": null,
"e": 3772,
"s": 3704,
"text": "df_2019_filtered <- rename(df_2019_filtered, “RANK_DRV_ACC” = “RK”)"
},
{
"code": null,
"e": 3803,
"s": 3772,
"text": "Let’s pause here for a minute."
},
{
"code": null,
"e": 3823,
"s": 3803,
"text": "Handling Dirty Data"
},
{
"code": null,
"e": 4036,
"s": 3823,
"text": "For this article, the missing AGE rows were filtered out. In a real analytics project, we’ll have to look at the best course of action to take (filter the row, replace the character data, replace with NULL, etc)."
},
{
"code": null,
"e": 4077,
"s": 4036,
"text": "Exploratory Data Analysis (EDA) — Part 2"
},
{
"code": null,
"e": 4118,
"s": 4077,
"text": "With our dataset examined and cleaned..."
},
{
"code": null,
"e": 4287,
"s": 4118,
"text": "Part 2 leans more toward Data Analysts and Data Scientists. You may be surprised at the insights that can be derived during this phase, even on this very basic dataset."
},
{
"code": null,
"e": 4304,
"s": 4287,
"text": "plot_histogram()"
},
{
"code": null,
"e": 4551,
"s": 4304,
"text": "We’ll use the “DataExplorer” library to learn more about our dataset. The plot_histogram() function will return a separate bar chart for each of our numeric variables. It shows the frequency (number of occurrences) for each value in the variable."
},
{
"code": null,
"e": 4605,
"s": 4551,
"text": "library(DataExplorer)plot_histogram(df_2019_filtered)"
},
{
"code": null,
"e": 4776,
"s": 4605,
"text": "For example, the “GREENS_REG” variable contains values roughly between 55 and 75. Based on the bar chart, we see most golfers are hitting Greens about 65–70% of the time."
},
{
"code": null,
"e": 4791,
"s": 4776,
"text": "plot_boxplot()"
},
{
"code": null,
"e": 4984,
"s": 4791,
"text": "The boxplot (box and whisker diagram) displays the distribution of data for a variable. The box shows us a “five number summary” — minimum, first quartile, median, third quartile, and maximum."
},
{
"code": null,
"e": 5108,
"s": 4984,
"text": "The plot_boxplot() function below created 5 bins/partitions. We’ll focus first on the Yards-per-Drive (YDS_DRIVE) variable."
},
{
"code": null,
"e": 5157,
"s": 5108,
"text": "plot_boxplot(df_2019_filtered, by = “YDS_DRIVE”)"
},
{
"code": null,
"e": 5265,
"s": 5157,
"text": "We can see some very interesting correlations look at the “AGE” variable compared with the “YDS per DRIVE”."
},
{
"code": null,
"e": 5298,
"s": 5265,
"text": "The older guys don’t hit as far."
},
{
"code": null,
"e": 5418,
"s": 5298,
"text": "There is one outlier. Someone in their mid-50’s is still hitting it quite far compared to the others in that age group."
},
{
"code": null,
"e": 5477,
"s": 5418,
"text": "Next, let’s do another boxplot from the “AGE” perspective."
},
{
"code": null,
"e": 5520,
"s": 5477,
"text": "plot_boxplot(df_2019_filtered, by = “AGE”)"
},
{
"code": null,
"e": 5739,
"s": 5520,
"text": "The oldest group (48–55) in the upper left corner has a very low “Driving Accuracy” (DRIVING_ACC). I would expect the older players to hit the ball shorter, but more accurate... that is not true, the data does not lie."
},
{
"code": null,
"e": 5849,
"s": 5739,
"text": "The older group (48–55) also struggles with putting. They have the highest average putts per hole (PUTT_AVG)."
},
{
"code": null,
"e": 5890,
"s": 5849,
"text": "Exploratory Data Analysis (EDA) — Part 3"
},
{
"code": null,
"e": 5933,
"s": 5890,
"text": "Let’s take this analysis to another level."
},
{
"code": null,
"e": 5946,
"s": 5933,
"text": "ggcorrplot()"
},
{
"code": null,
"e": 6031,
"s": 5946,
"text": "The functionality in this library gets closer to where a Data Scientist spends time."
},
{
"code": null,
"e": 6273,
"s": 6031,
"text": "The “ggcorrplot” provides us with a “heatmap” showing the significance (or lack of significance) between the relationships. A human cannot possibly stare at a spreadsheet and determine patterns/relationships between columns and rows of data."
},
{
"code": null,
"e": 6371,
"s": 6273,
"text": "Let’s put the “ggcorrplot” library to work. Sometimes it’s all about working smarter, not harder!"
},
{
"code": null,
"e": 6530,
"s": 6371,
"text": "library(ggcorrplot)ggcorrplot(corr, type = “lower”, outline.col = “black”, lab=TRUE, ggtheme = ggplot2::theme_gray, colors = c(“#6D9EC1”, “white”, “#E46726”))"
},
{
"code": null,
"e": 6657,
"s": 6530,
"text": "Running that function was much easier than staring at a spreadsheet, attempting to see relationships between rows and columns!"
},
{
"code": null,
"e": 6770,
"s": 6657,
"text": "1 . The most significant relationship between our variables is “Yards per Drive” and “Greens Hit in Regulation”."
},
{
"code": null,
"e": 6881,
"s": 6770,
"text": "2 . On the opposite side, the most significant inverse relationship exists between “Age” and “Yard per Drive”."
},
{
"code": null,
"e": 6970,
"s": 6881,
"text": "If you like circles better than squares, below is the same data using the circle method."
},
{
"code": null,
"e": 7117,
"s": 6970,
"text": "ggcorrplot(corr, type = “lower”, outline.col = “black”, method=”circle”, ggtheme = ggplot2::theme_gray, colors = c(“#6D9EC1”, “white”, “#E46726”))"
},
{
"code": null,
"e": 7128,
"s": 7117,
"text": "Conclusion"
},
{
"code": null,
"e": 7460,
"s": 7128,
"text": "Although the EDA process is critically important, it is only the beginning of a typical data analytics project lifecycle. Most likely an organization’s valuable data will not be coming from a googlesheet, but will more likely be buried in disparate databases, or coming from a 3rd party vendor, or possibly even an IoT data stream."
},
{
"code": null,
"e": 7555,
"s": 7460,
"text": "Leveraging R and the EDA process will help pave the way toward a successful analytics project."
}
] |
Categorical encoding using Label-Encoding and One-Hot-Encoder | by Dinesh Yadav | Towards Data Science | In many Machine-learning or Data Science activities, the data set might contain text or categorical values (basically non-numerical values). For example, color feature having values like red, orange, blue, white etc. Meal plan having values like breakfast, lunch, snacks, dinner, tea etc. Few algorithms such as CATBOAST, decision-trees can handle categorical values very well but most of the algorithms expect numerical values to achieve state-of-the-art results.
Over your learning curve in AI and Machine Learning, one thing you would notice that most of the algorithms work better with numerical inputs. Therefore, the main challenge faced by an analyst is to convert text/categorical data into numerical data and still make an algorithm/model to make sense out of it. Neural networks, which is a base of deep-learning, expects input values to be numerical.
There are many ways to convert categorical values into numerical values. Each approach has its own trade-offs and impact on the feature set. Hereby, I would focus on 2 main methods: One-Hot-Encoding and Label-Encoder. Both of these encoders are part of SciKit-learn library (one of the most widely used Python library) and are used to convert text or categorical data into numerical data which the model expects and perform better with.
Code snippets in this article would be of Python since I am more comfortable with Python. If you need for R (another widely used Machine-Learning language) then say so in comments.
This approach is very simple and it involves converting each value in a column to a number. Consider a dataset of bridges having a column names bridge-types having below values. Though there will be many more columns in the dataset, to understand label-encoding, we will focus on one categorical column only.
BRIDGE-TYPEArchBeamTrussCantileverTied ArchSuspensionCable
We choose to encode the text values by putting a running sequence for each text values like below:
With this, we completed the label-encoding of variable bridge-type. That’s all label encoding is about. But depending upon the data values and type of data, label encoding induces a new problem since it uses number sequencing. The problem using the number is that they introduce relation/comparison between them. Apparently, there is no relation between various bridge type, but when looking at the number, one might think that ‘Cable’ bridge type has higher precedence over ‘Arch’ bridge type. The algorithm might misunderstand that data has some kind of hierarchy/order 0 < 1 < 2 ... < 6 and might give 6X more weight to ‘Cable’ in calculation then than ‘Arch’ bridge type.
Let’s consider another column named ‘Safety Level’. Performing label encoding of this column also induces order/precedence in number, but in the right way. Here the numerical order does not look out-of-box and it makes sense if the algorithm interprets safety order 0 < 1 < 2 < 3 < 4 i.e. none < low < medium < high < very high.
Using category codes approach:
This approach requires the category column to be of ‘category’ datatype. By default, a non-numerical column is of ‘object’ type. So you might have to change type to ‘category’ before using this approach.
# import required librariesimport pandas as pdimport numpy as np# creating initial dataframebridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')bridge_df = pd.DataFrame(bridge_types, columns=['Bridge_Types'])# converting type of columns to 'category'bridge_df['Bridge_Types'] = bridge_df['Bridge_Types'].astype('category')# Assigning numerical values and storing in another columnbridge_df['Bridge_Types_Cat'] = bridge_df['Bridge_Types'].cat.codesbridge_df
Using sci-kit learn library approach:
Another common approach which many data analyst perform label-encoding is by using SciKit learn library.
import pandas as pdimport numpy as npfrom sklearn.preprocessing import LabelEncoder# creating initial dataframebridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')bridge_df = pd.DataFrame(bridge_types, columns=['Bridge_Types'])# creating instance of labelencoderlabelencoder = LabelEncoder()# Assigning numerical values and storing in another columnbridge_df['Bridge_Types_Cat'] = labelencoder.fit_transform(bridge_df['Bridge_Types'])bridge_df
Though label encoding is straight but it has the disadvantage that the numeric values can be misinterpreted by algorithms as having some sort of hierarchy/order in them. This ordering issue is addressed in another common alternative approach called ‘One-Hot Encoding’. In this strategy, each category value is converted into a new column and assigned a 1 or 0 (notation for true/false) value to the column. Let’s consider the previous example of bridge type and safety levels with one-hot encoding.
Above are the one-hot encoded values of categorical column ‘Bridge-Type’. In the same way, let's check for ‘Safety-Level’ column.
Rows which have the first column value (Arch/None) will have ‘1’ (indicating true) and other value’s columns will have ‘0’ (indicating false). Similarly, for other rows matching value with column value.
Though this approach eliminates the hierarchy/order issues but does have the downside of adding more columns to the data set. It can cause the number of columns to expand greatly if you have many unique values in a category column. In the above example, it was manageable, but it will get really challenging to manage when encoding gives many columns.
Using sci-kit learn library approach:
OneHotEncoder from SciKit library only takes numerical categorical values, hence any value of string type should be label encoded before one hot encoded. So taking the dataframe from the previous example, we will apply OneHotEncoder on column Bridge_Types_Cat.
import pandas as pdimport numpy as npfrom sklearn.preprocessing import OneHotEncoder# creating instance of one-hot-encoderenc = OneHotEncoder(handle_unknown='ignore')# passing bridge-types-cat column (label encoded values of bridge_types)enc_df = pd.DataFrame(enc.fit_transform(bridge_df[['Bridge_Types_Cat']]).toarray())# merge with main df bridge_df on key valuesbridge_df = bridge_df.join(enc_df)bridge_df
Columns ‘Bridge_Types_Cat’ can be dropped from the dataframe.
Using dummies values approach:
This approach is more flexible because it allows encoding as many category columns as you would like and choose how to label the columns using a prefix. Proper naming will make the rest of the analysis just a little bit easier.
import pandas as pdimport numpy as np# creating initial dataframebridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')bridge_df = pd.DataFrame(bridge_types, columns=['Bridge_Types'])# generate binary values using get_dummiesdum_df = pd.get_dummies(bridge_df, columns=["Bridge_Types"], prefix=["Type_is"] )# merge with main df bridge_df on key valuesbridge_df = bridge_df.join(dum_df)bridge_df
It is important to understand various option for encoding categorical variables because each approach has its own pros and cons. In data science, it is an important step, so I really encourage you to keep these ideas in mind when dealing with categorical variables. For any suggestion or for more details on the code used in this article, feel free to comment. | [
{
"code": null,
"e": 636,
"s": 171,
"text": "In many Machine-learning or Data Science activities, the data set might contain text or categorical values (basically non-numerical values). For example, color feature having values like red, orange, blue, white etc. Meal plan having values like breakfast, lunch, snacks, dinner, tea etc. Few algorithms such as CATBOAST, decision-trees can handle categorical values very well but most of the algorithms expect numerical values to achieve state-of-the-art results."
},
{
"code": null,
"e": 1033,
"s": 636,
"text": "Over your learning curve in AI and Machine Learning, one thing you would notice that most of the algorithms work better with numerical inputs. Therefore, the main challenge faced by an analyst is to convert text/categorical data into numerical data and still make an algorithm/model to make sense out of it. Neural networks, which is a base of deep-learning, expects input values to be numerical."
},
{
"code": null,
"e": 1470,
"s": 1033,
"text": "There are many ways to convert categorical values into numerical values. Each approach has its own trade-offs and impact on the feature set. Hereby, I would focus on 2 main methods: One-Hot-Encoding and Label-Encoder. Both of these encoders are part of SciKit-learn library (one of the most widely used Python library) and are used to convert text or categorical data into numerical data which the model expects and perform better with."
},
{
"code": null,
"e": 1651,
"s": 1470,
"text": "Code snippets in this article would be of Python since I am more comfortable with Python. If you need for R (another widely used Machine-Learning language) then say so in comments."
},
{
"code": null,
"e": 1960,
"s": 1651,
"text": "This approach is very simple and it involves converting each value in a column to a number. Consider a dataset of bridges having a column names bridge-types having below values. Though there will be many more columns in the dataset, to understand label-encoding, we will focus on one categorical column only."
},
{
"code": null,
"e": 2019,
"s": 1960,
"text": "BRIDGE-TYPEArchBeamTrussCantileverTied ArchSuspensionCable"
},
{
"code": null,
"e": 2118,
"s": 2019,
"text": "We choose to encode the text values by putting a running sequence for each text values like below:"
},
{
"code": null,
"e": 2794,
"s": 2118,
"text": "With this, we completed the label-encoding of variable bridge-type. That’s all label encoding is about. But depending upon the data values and type of data, label encoding induces a new problem since it uses number sequencing. The problem using the number is that they introduce relation/comparison between them. Apparently, there is no relation between various bridge type, but when looking at the number, one might think that ‘Cable’ bridge type has higher precedence over ‘Arch’ bridge type. The algorithm might misunderstand that data has some kind of hierarchy/order 0 < 1 < 2 ... < 6 and might give 6X more weight to ‘Cable’ in calculation then than ‘Arch’ bridge type."
},
{
"code": null,
"e": 3123,
"s": 2794,
"text": "Let’s consider another column named ‘Safety Level’. Performing label encoding of this column also induces order/precedence in number, but in the right way. Here the numerical order does not look out-of-box and it makes sense if the algorithm interprets safety order 0 < 1 < 2 < 3 < 4 i.e. none < low < medium < high < very high."
},
{
"code": null,
"e": 3154,
"s": 3123,
"text": "Using category codes approach:"
},
{
"code": null,
"e": 3358,
"s": 3154,
"text": "This approach requires the category column to be of ‘category’ datatype. By default, a non-numerical column is of ‘object’ type. So you might have to change type to ‘category’ before using this approach."
},
{
"code": null,
"e": 3847,
"s": 3358,
"text": "# import required librariesimport pandas as pdimport numpy as np# creating initial dataframebridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')bridge_df = pd.DataFrame(bridge_types, columns=['Bridge_Types'])# converting type of columns to 'category'bridge_df['Bridge_Types'] = bridge_df['Bridge_Types'].astype('category')# Assigning numerical values and storing in another columnbridge_df['Bridge_Types_Cat'] = bridge_df['Bridge_Types'].cat.codesbridge_df"
},
{
"code": null,
"e": 3885,
"s": 3847,
"text": "Using sci-kit learn library approach:"
},
{
"code": null,
"e": 3990,
"s": 3885,
"text": "Another common approach which many data analyst perform label-encoding is by using SciKit learn library."
},
{
"code": null,
"e": 4466,
"s": 3990,
"text": "import pandas as pdimport numpy as npfrom sklearn.preprocessing import LabelEncoder# creating initial dataframebridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')bridge_df = pd.DataFrame(bridge_types, columns=['Bridge_Types'])# creating instance of labelencoderlabelencoder = LabelEncoder()# Assigning numerical values and storing in another columnbridge_df['Bridge_Types_Cat'] = labelencoder.fit_transform(bridge_df['Bridge_Types'])bridge_df"
},
{
"code": null,
"e": 4965,
"s": 4466,
"text": "Though label encoding is straight but it has the disadvantage that the numeric values can be misinterpreted by algorithms as having some sort of hierarchy/order in them. This ordering issue is addressed in another common alternative approach called ‘One-Hot Encoding’. In this strategy, each category value is converted into a new column and assigned a 1 or 0 (notation for true/false) value to the column. Let’s consider the previous example of bridge type and safety levels with one-hot encoding."
},
{
"code": null,
"e": 5095,
"s": 4965,
"text": "Above are the one-hot encoded values of categorical column ‘Bridge-Type’. In the same way, let's check for ‘Safety-Level’ column."
},
{
"code": null,
"e": 5298,
"s": 5095,
"text": "Rows which have the first column value (Arch/None) will have ‘1’ (indicating true) and other value’s columns will have ‘0’ (indicating false). Similarly, for other rows matching value with column value."
},
{
"code": null,
"e": 5650,
"s": 5298,
"text": "Though this approach eliminates the hierarchy/order issues but does have the downside of adding more columns to the data set. It can cause the number of columns to expand greatly if you have many unique values in a category column. In the above example, it was manageable, but it will get really challenging to manage when encoding gives many columns."
},
{
"code": null,
"e": 5688,
"s": 5650,
"text": "Using sci-kit learn library approach:"
},
{
"code": null,
"e": 5949,
"s": 5688,
"text": "OneHotEncoder from SciKit library only takes numerical categorical values, hence any value of string type should be label encoded before one hot encoded. So taking the dataframe from the previous example, we will apply OneHotEncoder on column Bridge_Types_Cat."
},
{
"code": null,
"e": 6358,
"s": 5949,
"text": "import pandas as pdimport numpy as npfrom sklearn.preprocessing import OneHotEncoder# creating instance of one-hot-encoderenc = OneHotEncoder(handle_unknown='ignore')# passing bridge-types-cat column (label encoded values of bridge_types)enc_df = pd.DataFrame(enc.fit_transform(bridge_df[['Bridge_Types_Cat']]).toarray())# merge with main df bridge_df on key valuesbridge_df = bridge_df.join(enc_df)bridge_df"
},
{
"code": null,
"e": 6420,
"s": 6358,
"text": "Columns ‘Bridge_Types_Cat’ can be dropped from the dataframe."
},
{
"code": null,
"e": 6451,
"s": 6420,
"text": "Using dummies values approach:"
},
{
"code": null,
"e": 6679,
"s": 6451,
"text": "This approach is more flexible because it allows encoding as many category columns as you would like and choose how to label the columns using a prefix. Proper naming will make the rest of the analysis just a little bit easier."
},
{
"code": null,
"e": 7103,
"s": 6679,
"text": "import pandas as pdimport numpy as np# creating initial dataframebridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')bridge_df = pd.DataFrame(bridge_types, columns=['Bridge_Types'])# generate binary values using get_dummiesdum_df = pd.get_dummies(bridge_df, columns=[\"Bridge_Types\"], prefix=[\"Type_is\"] )# merge with main df bridge_df on key valuesbridge_df = bridge_df.join(dum_df)bridge_df"
}
] |
Difference Between Scanner and BufferedReader Class in Java | 08 Apr, 2022
In Java, Scanner and BufferedReader class are sources that serve as ways of reading inputs. Scanner class is a simple text scanner that can parse primitive types and strings. It internally uses regular expressions to read different types while on the other hand BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of the sequence of characters
The eccentric difference lies in reading different ways of taking input via the next() method that is justified in the below programs over the similar input set.
Example 1:
Java
// Java Program to Illustrate Scanner Class // Importing Scanner class from// java.util packageimport java.util.Scanner; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating object of Scanner class to // read input from keyboard Scanner scn = new Scanner(System.in); System.out.println("Enter an integer"); // Using nextInt() to parse integer values int a = scn.nextInt(); System.out.println("Enter a String"); // Using nextLine() to parse string values String b = scn.nextLine(); // Display name and age entered above System.out.printf("You have entered:- " + a + " " + "and name as " + b); }}
Output:
Let us try the same using Buffer class and same Input below as follows:
Example 2:
Java
// Java Program to Illustrate BufferedReader Class // Importing required classimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String args[]) throws IOException { // Creating object of class inside main() method BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter an integer"); // Taking integer input int a = Integer.parseInt(br.readLine()); System.out.println("Enter a String"); String b = br.readLine(); // Printing input entities above System.out.printf("You have entered:- " + a + " and name as " + b); }}
Output:
Outputs explanation: In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine() does not read values from console and cursor will not come into console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().In BufferReader class there is no such type of problem. This problem occurs only for the Scanner class, due to nextXXX() methods ignoring newline character and nextLine() only reads till the first newline character. If we use one more call of nextLine() method between nextXXX() and nextLine(), then this problem will not occur because nextLine() will consume the newline character.
Tip: See this for the corrected program. This problem is same as scanf() followed by gets() in C/C++. This problem can also be solved by using next() instead of nextLine() for taking input of strings as shown here.
Following are the Major Differences between Scanner and BufferedReader Class in Java
BufferedReader is synchronous while Scanner is not. BufferedReader should be used if we are working with multiple threads.
BufferedReader has a significantly larger buffer memory than Scanner.
The Scanner has a little buffer (1KB char buffer) as opposed to the BufferedReader (8KB byte buffer), but it’s more than enough.
BufferedReader is a bit faster as compared to scanner because the scanner does the parsing of input data and BufferedReader simply reads a sequence of characters.
This article is contributed by Pranav Adarsh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
chachu
Arnav Srivastava 1
anuragbanerjee011
draghavgupta96
solankimayank
sk944795
simmytarika5
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 471,
"s": 52,
"text": "In Java, Scanner and BufferedReader class are sources that serve as ways of reading inputs. Scanner class is a simple text scanner that can parse primitive types and strings. It internally uses regular expressions to read different types while on the other hand BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of the sequence of characters"
},
{
"code": null,
"e": 633,
"s": 471,
"text": "The eccentric difference lies in reading different ways of taking input via the next() method that is justified in the below programs over the similar input set."
},
{
"code": null,
"e": 644,
"s": 633,
"text": "Example 1:"
},
{
"code": null,
"e": 649,
"s": 644,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Scanner Class // Importing Scanner class from// java.util packageimport java.util.Scanner; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating object of Scanner class to // read input from keyboard Scanner scn = new Scanner(System.in); System.out.println(\"Enter an integer\"); // Using nextInt() to parse integer values int a = scn.nextInt(); System.out.println(\"Enter a String\"); // Using nextLine() to parse string values String b = scn.nextLine(); // Display name and age entered above System.out.printf(\"You have entered:- \" + a + \" \" + \"and name as \" + b); }}",
"e": 1412,
"s": 649,
"text": null
},
{
"code": null,
"e": 1420,
"s": 1412,
"text": "Output:"
},
{
"code": null,
"e": 1493,
"s": 1420,
"text": "Let us try the same using Buffer class and same Input below as follows: "
},
{
"code": null,
"e": 1504,
"s": 1493,
"text": "Example 2:"
},
{
"code": null,
"e": 1509,
"s": 1504,
"text": "Java"
},
{
"code": "// Java Program to Illustrate BufferedReader Class // Importing required classimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String args[]) throws IOException { // Creating object of class inside main() method BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println(\"Enter an integer\"); // Taking integer input int a = Integer.parseInt(br.readLine()); System.out.println(\"Enter a String\"); String b = br.readLine(); // Printing input entities above System.out.printf(\"You have entered:- \" + a + \" and name as \" + b); }}",
"e": 2234,
"s": 1509,
"text": null
},
{
"code": null,
"e": 2242,
"s": 2234,
"text": "Output:"
},
{
"code": null,
"e": 2961,
"s": 2242,
"text": "Outputs explanation: In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine() does not read values from console and cursor will not come into console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().In BufferReader class there is no such type of problem. This problem occurs only for the Scanner class, due to nextXXX() methods ignoring newline character and nextLine() only reads till the first newline character. If we use one more call of nextLine() method between nextXXX() and nextLine(), then this problem will not occur because nextLine() will consume the newline character. "
},
{
"code": null,
"e": 3176,
"s": 2961,
"text": "Tip: See this for the corrected program. This problem is same as scanf() followed by gets() in C/C++. This problem can also be solved by using next() instead of nextLine() for taking input of strings as shown here."
},
{
"code": null,
"e": 3261,
"s": 3176,
"text": "Following are the Major Differences between Scanner and BufferedReader Class in Java"
},
{
"code": null,
"e": 3384,
"s": 3261,
"text": "BufferedReader is synchronous while Scanner is not. BufferedReader should be used if we are working with multiple threads."
},
{
"code": null,
"e": 3454,
"s": 3384,
"text": "BufferedReader has a significantly larger buffer memory than Scanner."
},
{
"code": null,
"e": 3583,
"s": 3454,
"text": "The Scanner has a little buffer (1KB char buffer) as opposed to the BufferedReader (8KB byte buffer), but it’s more than enough."
},
{
"code": null,
"e": 3746,
"s": 3583,
"text": "BufferedReader is a bit faster as compared to scanner because the scanner does the parsing of input data and BufferedReader simply reads a sequence of characters."
},
{
"code": null,
"e": 4139,
"s": 3746,
"text": "This article is contributed by Pranav Adarsh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4146,
"s": 4139,
"text": "chachu"
},
{
"code": null,
"e": 4165,
"s": 4146,
"text": "Arnav Srivastava 1"
},
{
"code": null,
"e": 4183,
"s": 4165,
"text": "anuragbanerjee011"
},
{
"code": null,
"e": 4198,
"s": 4183,
"text": "draghavgupta96"
},
{
"code": null,
"e": 4212,
"s": 4198,
"text": "solankimayank"
},
{
"code": null,
"e": 4221,
"s": 4212,
"text": "sk944795"
},
{
"code": null,
"e": 4234,
"s": 4221,
"text": "simmytarika5"
},
{
"code": null,
"e": 4243,
"s": 4234,
"text": "Java-I/O"
},
{
"code": null,
"e": 4248,
"s": 4243,
"text": "Java"
},
{
"code": null,
"e": 4253,
"s": 4248,
"text": "Java"
}
] |
Functional Programming Paradigm | 28 Jun, 2022
Introduction Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”. It uses expressions instead of statements. An expression is evaluated to produce a value whereas a statement is executed to assign variables. Those functions have some special features discussed below.
Functional Programming is based on Lambda Calculus: Lambda calculus is a framework developed by Alonzo Church to study computations with functions. It can be called as the smallest programming language in the world. It gives the definition of what is computable. Anything that can be computed by lambda calculus is computable. It is equivalent to Turing machine in its ability to compute. It provides a theoretical framework for describing functions and their evaluation. It forms the basis of almost all current functional programming languages. Fact: Alan Turing was a student of Alonzo Church who created Turing machine which laid the foundation of imperative programming style.
Programming Languages that support functional programming: Haskell, JavaScript, Python, Scala, Erlang, Lisp, ML, Clojure, OCaml, Common Lisp, Racket.
Concepts of functional programming:
Pure functions
Recursion
Referential transparency
Functions are First-Class and can be Higher-Order
Variables are Immutable
Pure functions: These functions have two main properties. First, they always produce the same output for same arguments irrespective of anything else. Secondly, they have no side-effects i.e. they do not modify any arguments or local/global variables or input/output streams. Later property is called immutability. The pure function’s only result is the value it returns. They are deterministic. Programs done using functional programming are easy to debug because pure functions have no side effects or hidden I/O. Pure functions also make it easier to write parallel/concurrent applications. When the code is written in this style, a smart compiler can do many things – it can parallelize the instructions, wait to evaluate results when needing them, and memorize the results since the results never change as long as the input doesn’t change. example of the pure function:
sum(x, y) // sum is function taking x and y as arguments
return x + y // sum is returning sum of x and y without changing them
Recursion: There are no “for” or “while” loop in functional languages. Iteration in functional languages is implemented through recursion. Recursive functions repeatedly call themselves, until it reaches the base case. example of the recursive function:
fib(n)
if (n <= 1)
return 1;
else
return fib(n - 1) + fib(n - 2);
Referential transparency: In functional programs variables once defined do not change their value throughout the program. Functional programs do not have assignment statements. If we have to store some value, we define new variables instead. This eliminates any chances of side effects because any variable can be replaced with its actual value at any point of execution. State of any variable is constant at any instant.
Example:
x = x + 1 // this changes the value assigned to the variable x.
// So the expression is not referentially transparent.
Functions are First-Class and can be Higher-Order: First-class functions are treated as first-class variable. The first class variables can be passed to functions as parameter, can be returned from functions or stored in data structures. Higher order functions are the functions that take other functions as arguments and they can also return functions.
Example:
show_output(f) // function show_output is declared taking argument f
// which are another function
f(); // calling passed function
print_gfg() // declaring another function
print("hello gfg");
show_output(print_gfg) // passing function in another function
Variables are Immutable: In functional programming, we can’t modify a variable after it’s been initialized. We can create new variables – but we can’t modify existing variables, and this really helps to maintain state throughout the runtime of a program. Once we create a variable and set its value, we can have full confidence knowing that the value of that variable will never change.
Advantages and Disadvantages of Functional programming
Advantages:
Pure functions are easier to understand because they don’t change any states and depend only on the input given to them. Whatever output they produce is the return value they give. Their function signature gives all the information about them i.e. their return type and their arguments.The ability of functional programming languages to treat functions as values and pass them to functions as parameters make the code more readable and easily understandable.Testing and debugging is easier. Since pure functions take only arguments and produce output, they don’t produce any changes don’t take input or produce some hidden output. They use immutable values, so it becomes easier to check some problems in programs written uses pure functions.It is used to implement concurrency/parallelism because pure functions don’t change variables or any other data outside of it.It adopts lazy evaluation which avoids repeated evaluation because the value is evaluated and stored only when it is needed.
Pure functions are easier to understand because they don’t change any states and depend only on the input given to them. Whatever output they produce is the return value they give. Their function signature gives all the information about them i.e. their return type and their arguments.
The ability of functional programming languages to treat functions as values and pass them to functions as parameters make the code more readable and easily understandable.
Testing and debugging is easier. Since pure functions take only arguments and produce output, they don’t produce any changes don’t take input or produce some hidden output. They use immutable values, so it becomes easier to check some problems in programs written uses pure functions.
It is used to implement concurrency/parallelism because pure functions don’t change variables or any other data outside of it.
It adopts lazy evaluation which avoids repeated evaluation because the value is evaluated and stored only when it is needed.
Disadvantages:
Sometimes writing pure functions can reduce the readability of code.Writing programs in recursive style instead of using loops can be bit intimidating.Writing pure functions are easy but combining them with the rest of the application and I/O operations is a difficult task.Immutable values and recursion can lead to decrease in performance.
Sometimes writing pure functions can reduce the readability of code.
Writing programs in recursive style instead of using loops can be bit intimidating.
Writing pure functions are easy but combining them with the rest of the application and I/O operations is a difficult task.
Immutable values and recursion can lead to decrease in performance.
Applications:
It is used in mathematical computations.
It is needed where concurrency or parallelism is required.
Fact: Whatsapp needs only 50 engineers for its 900M users because Erlang is used to implement its concurrency needs. Facebook uses Haskell in its anti-spam system.
KumariPoojaMandal
infoaamirkhan
ipudhruv
Computer Subject
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Checking in Compiler Design
Optimization of Basic Blocks
What is Transmission Control Protocol (TCP)?
Token, Patterns, and Lexems
Cloud Based Services
Difference Between NPDA and DPDA
Firewall Design Principles
ASCII Table
Introduction to Computer Graphics
What is the MD5 Algorithm? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 549,
"s": 52,
"text": "Introduction Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”. It uses expressions instead of statements. An expression is evaluated to produce a value whereas a statement is executed to assign variables. Those functions have some special features discussed below. "
},
{
"code": null,
"e": 1232,
"s": 549,
"text": "Functional Programming is based on Lambda Calculus: Lambda calculus is a framework developed by Alonzo Church to study computations with functions. It can be called as the smallest programming language in the world. It gives the definition of what is computable. Anything that can be computed by lambda calculus is computable. It is equivalent to Turing machine in its ability to compute. It provides a theoretical framework for describing functions and their evaluation. It forms the basis of almost all current functional programming languages. Fact: Alan Turing was a student of Alonzo Church who created Turing machine which laid the foundation of imperative programming style. "
},
{
"code": null,
"e": 1383,
"s": 1232,
"text": "Programming Languages that support functional programming: Haskell, JavaScript, Python, Scala, Erlang, Lisp, ML, Clojure, OCaml, Common Lisp, Racket. "
},
{
"code": null,
"e": 1420,
"s": 1383,
"text": "Concepts of functional programming: "
},
{
"code": null,
"e": 1435,
"s": 1420,
"text": "Pure functions"
},
{
"code": null,
"e": 1445,
"s": 1435,
"text": "Recursion"
},
{
"code": null,
"e": 1470,
"s": 1445,
"text": "Referential transparency"
},
{
"code": null,
"e": 1520,
"s": 1470,
"text": "Functions are First-Class and can be Higher-Order"
},
{
"code": null,
"e": 1544,
"s": 1520,
"text": "Variables are Immutable"
},
{
"code": null,
"e": 2421,
"s": 1544,
"text": "Pure functions: These functions have two main properties. First, they always produce the same output for same arguments irrespective of anything else. Secondly, they have no side-effects i.e. they do not modify any arguments or local/global variables or input/output streams. Later property is called immutability. The pure function’s only result is the value it returns. They are deterministic. Programs done using functional programming are easy to debug because pure functions have no side effects or hidden I/O. Pure functions also make it easier to write parallel/concurrent applications. When the code is written in this style, a smart compiler can do many things – it can parallelize the instructions, wait to evaluate results when needing them, and memorize the results since the results never change as long as the input doesn’t change. example of the pure function: "
},
{
"code": null,
"e": 2565,
"s": 2421,
"text": "sum(x, y) // sum is function taking x and y as arguments\n return x + y // sum is returning sum of x and y without changing them"
},
{
"code": null,
"e": 2821,
"s": 2565,
"text": "Recursion: There are no “for” or “while” loop in functional languages. Iteration in functional languages is implemented through recursion. Recursive functions repeatedly call themselves, until it reaches the base case. example of the recursive function: "
},
{
"code": null,
"e": 2911,
"s": 2821,
"text": "fib(n)\n if (n <= 1)\n return 1;\n else\n return fib(n - 1) + fib(n - 2);"
},
{
"code": null,
"e": 3334,
"s": 2911,
"text": "Referential transparency: In functional programs variables once defined do not change their value throughout the program. Functional programs do not have assignment statements. If we have to store some value, we define new variables instead. This eliminates any chances of side effects because any variable can be replaced with its actual value at any point of execution. State of any variable is constant at any instant. "
},
{
"code": null,
"e": 3345,
"s": 3334,
"text": "Example: "
},
{
"code": null,
"e": 3475,
"s": 3345,
"text": "x = x + 1 // this changes the value assigned to the variable x.\n // So the expression is not referentially transparent. "
},
{
"code": null,
"e": 3830,
"s": 3475,
"text": "Functions are First-Class and can be Higher-Order: First-class functions are treated as first-class variable. The first class variables can be passed to functions as parameter, can be returned from functions or stored in data structures. Higher order functions are the functions that take other functions as arguments and they can also return functions. "
},
{
"code": null,
"e": 3840,
"s": 3830,
"text": "Example: "
},
{
"code": null,
"e": 4175,
"s": 3840,
"text": "show_output(f) // function show_output is declared taking argument f \n // which are another function\n f(); // calling passed function\n\nprint_gfg() // declaring another function \n print(\"hello gfg\");\n\nshow_output(print_gfg) // passing function in another function"
},
{
"code": null,
"e": 4564,
"s": 4175,
"text": "Variables are Immutable: In functional programming, we can’t modify a variable after it’s been initialized. We can create new variables – but we can’t modify existing variables, and this really helps to maintain state throughout the runtime of a program. Once we create a variable and set its value, we can have full confidence knowing that the value of that variable will never change. "
},
{
"code": null,
"e": 4619,
"s": 4564,
"text": "Advantages and Disadvantages of Functional programming"
},
{
"code": null,
"e": 4633,
"s": 4619,
"text": "Advantages: "
},
{
"code": null,
"e": 5626,
"s": 4633,
"text": "Pure functions are easier to understand because they don’t change any states and depend only on the input given to them. Whatever output they produce is the return value they give. Their function signature gives all the information about them i.e. their return type and their arguments.The ability of functional programming languages to treat functions as values and pass them to functions as parameters make the code more readable and easily understandable.Testing and debugging is easier. Since pure functions take only arguments and produce output, they don’t produce any changes don’t take input or produce some hidden output. They use immutable values, so it becomes easier to check some problems in programs written uses pure functions.It is used to implement concurrency/parallelism because pure functions don’t change variables or any other data outside of it.It adopts lazy evaluation which avoids repeated evaluation because the value is evaluated and stored only when it is needed."
},
{
"code": null,
"e": 5913,
"s": 5626,
"text": "Pure functions are easier to understand because they don’t change any states and depend only on the input given to them. Whatever output they produce is the return value they give. Their function signature gives all the information about them i.e. their return type and their arguments."
},
{
"code": null,
"e": 6086,
"s": 5913,
"text": "The ability of functional programming languages to treat functions as values and pass them to functions as parameters make the code more readable and easily understandable."
},
{
"code": null,
"e": 6371,
"s": 6086,
"text": "Testing and debugging is easier. Since pure functions take only arguments and produce output, they don’t produce any changes don’t take input or produce some hidden output. They use immutable values, so it becomes easier to check some problems in programs written uses pure functions."
},
{
"code": null,
"e": 6498,
"s": 6371,
"text": "It is used to implement concurrency/parallelism because pure functions don’t change variables or any other data outside of it."
},
{
"code": null,
"e": 6623,
"s": 6498,
"text": "It adopts lazy evaluation which avoids repeated evaluation because the value is evaluated and stored only when it is needed."
},
{
"code": null,
"e": 6640,
"s": 6623,
"text": "Disadvantages: "
},
{
"code": null,
"e": 6982,
"s": 6640,
"text": "Sometimes writing pure functions can reduce the readability of code.Writing programs in recursive style instead of using loops can be bit intimidating.Writing pure functions are easy but combining them with the rest of the application and I/O operations is a difficult task.Immutable values and recursion can lead to decrease in performance."
},
{
"code": null,
"e": 7051,
"s": 6982,
"text": "Sometimes writing pure functions can reduce the readability of code."
},
{
"code": null,
"e": 7135,
"s": 7051,
"text": "Writing programs in recursive style instead of using loops can be bit intimidating."
},
{
"code": null,
"e": 7259,
"s": 7135,
"text": "Writing pure functions are easy but combining them with the rest of the application and I/O operations is a difficult task."
},
{
"code": null,
"e": 7327,
"s": 7259,
"text": "Immutable values and recursion can lead to decrease in performance."
},
{
"code": null,
"e": 7342,
"s": 7327,
"text": "Applications: "
},
{
"code": null,
"e": 7383,
"s": 7342,
"text": "It is used in mathematical computations."
},
{
"code": null,
"e": 7442,
"s": 7383,
"text": "It is needed where concurrency or parallelism is required."
},
{
"code": null,
"e": 7607,
"s": 7442,
"text": "Fact: Whatsapp needs only 50 engineers for its 900M users because Erlang is used to implement its concurrency needs. Facebook uses Haskell in its anti-spam system. "
},
{
"code": null,
"e": 7627,
"s": 7609,
"text": "KumariPoojaMandal"
},
{
"code": null,
"e": 7641,
"s": 7627,
"text": "infoaamirkhan"
},
{
"code": null,
"e": 7650,
"s": 7641,
"text": "ipudhruv"
},
{
"code": null,
"e": 7667,
"s": 7650,
"text": "Computer Subject"
},
{
"code": null,
"e": 7686,
"s": 7667,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7784,
"s": 7686,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7817,
"s": 7784,
"text": "Type Checking in Compiler Design"
},
{
"code": null,
"e": 7846,
"s": 7817,
"text": "Optimization of Basic Blocks"
},
{
"code": null,
"e": 7891,
"s": 7846,
"text": "What is Transmission Control Protocol (TCP)?"
},
{
"code": null,
"e": 7919,
"s": 7891,
"text": "Token, Patterns, and Lexems"
},
{
"code": null,
"e": 7940,
"s": 7919,
"text": "Cloud Based Services"
},
{
"code": null,
"e": 7973,
"s": 7940,
"text": "Difference Between NPDA and DPDA"
},
{
"code": null,
"e": 8000,
"s": 7973,
"text": "Firewall Design Principles"
},
{
"code": null,
"e": 8012,
"s": 8000,
"text": "ASCII Table"
},
{
"code": null,
"e": 8046,
"s": 8012,
"text": "Introduction to Computer Graphics"
}
] |
Ways to form a group from three groups with given constraints | 31 May, 2022
Given three numbers(x, y and z) which denote the number of people in the first group, the second group, and third group. We can form groups by selecting people from the first group, the second group and third group such that the following conditions are not void.
A minimum of one people has to be selected from every group.
The number of people selected from the first group has to be at least one more than the number of people selected from the third group.
The task is to find the number of ways of forming distinct groups. Examples:
Input: x = 3, y = 2, z = 1 Output: 9 Lets say x has people (a, b, c) Y has people (d, e) Z has people (f) Then the 9 ways are {a, b, d, f}, {a, b, e, f}, {a, c, d, f}, {a, c, e, f}, {b, c, d, f}, {b, c, e, f}, {a, b, c, d, f}, {a, b, c, e, f} and {a, b, c, d, e, f}Input: x = 4, y = 2, z = 1 Output: 27
The problem can be solved using combinatorics. There are three positions(in terms of people from different groups) which need to be filled. The first has to be filled with a number with one or greater than the second position. The third can be filled with any number. We know if we need to fill k positions with N people, then the number of ways of doing it is . Hence the following steps can be followed to solve the above problem.
The second position can be filled with i = 1 to i = y people.
The first position can be filled with j = i+1 to j = x people.
The third position can be filled with any number of k = 1 to k = z people.
Hence the common thing is filling the third position with k people. Hence we can take that portion as common.
Run two loops( i and j) for filling up the second position and first position respectively.
The number of ways of filling up the positions is * .
After calculation of all ways to fill up those two positions, we can simply multiply summation of + + ... since that was the common part in both.
can be pre-computed using Dynamic Programming to reduce time complexity. The method is discussed here. Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find the number of// ways to form the group of people#include <bits/stdc++.h>using namespace std; int C[1000][1000]; // Function to pre-compute the// Combination using DPvoid binomialCoeff(int n){ int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= i; j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // return C[n][k];} // Function to find the number of waysint numberOfWays(int x, int y, int z){ // Function to pre-compute binomialCoeff(max(x, max(y, z))); // Sum the Zci int sum = 0; for (int i = 1; i <= z; i++) { sum = (sum + C[z][i]); } // Iterate for second position int sum1 = 0; for (int i = 1; i <= y; i++) { // Iterate for first position for (int j = i + 1; j <= x; j++) { sum1 = (sum1 + (C[y][i] * C[x][j])); } } // Multiply the common Combination value sum1 = (sum * sum1); return sum1;} // Driver Codeint main(){ int x = 3; int y = 2; int z = 1; cout << numberOfWays(x, y, z); return 0;}
// Java program to find the number of// ways to form the group of peoplsclass GFG{ static int C[][] = new int [1000][1000]; // Function to pre-compute the// Combination using DPstatic void binomialCoeff(int n){ int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= i; j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // return C[n][k];} // Function to find the number of waysstatic int numberOfWays(int x, int y, int z){ // Function to pre-compute binomialCoeff(Math.max(x, Math.max(y, z))); // Sum the Zci int sum = 0; for (int i = 1; i <= z; i++) { sum = (sum + C[z][i]); } // Iterate for second position int sum1 = 0; for (int i = 1; i <= y; i++) { // Iterate for first position for (int j = i + 1; j <= x; j++) { sum1 = (sum1 + (C[y][i] * C[x][j])); } } // Multiply the common Combination value sum1 = (sum * sum1); return sum1;} // Driver Codepublic static void main(String args[]){ int x = 3; int y = 2; int z = 1; System.out.println(numberOfWays(x, y, z));}} // This code is contributed by Arnab Kundu
# Python3 program to find the number of# ways to form the group of peoplsC = [[0 for i in range(1000)] for i in range(1000)] # Function to pre-compute the# Combination using DPdef binomialCoeff(n): i, j = 0, 0 # Calculate value of Binomial Coefficient # in bottom up manner for i in range(n + 1): for j in range(i + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using previously # stored values else: C[i][j] = C[i - 1][j - 1] + \ C[i - 1][j] # return C[n][k] # Function to find the number of waysdef numberOfWays(x, y, z): # Function to pre-compute binomialCoeff(max(x, max(y, z))) # Sum the Zci sum = 0 for i in range(1, z + 1): sum = (sum + C[z][i]) # Iterate for second position sum1 = 0 for i in range(1, y + 1): # Iterate for first position for j in range(i + 1, x + 1): sum1 = (sum1 + (C[y][i] * C[x][j])) # Multiply the common Combination value sum1 = (sum * sum1) return sum1 # Driver Codex = 3y = 2z = 1 print(numberOfWays(x, y, z)) # This code is contributed by Mohit Kumar
// C# program to find the number of// ways to form the group of peoplsusing System; class GFG{ static int [,]C = new int [1000,1000]; // Function to pre-compute the// Combination using DPstatic void binomialCoeff(int n){ int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= i; j++) { // Base Cases if (j == 0 || j == i) C[i,j] = 1; // Calculate value using previously // stored values else C[i,j] = C[i - 1,j - 1] + C[i - 1,j]; } } // return C[n,k];} // Function to find the number of waysstatic int numberOfWays(int x, int y, int z){ // Function to pre-compute binomialCoeff(Math.Max(x, Math.Max(y, z))); // Sum the Zci int sum = 0; for (int i = 1; i <= z; i++) { sum = (sum + C[z,i]); } // Iterate for second position int sum1 = 0; for (int i = 1; i <= y; i++) { // Iterate for first position for (int j = i + 1; j <= x; j++) { sum1 = (sum1 + (C[y,i] * C[x,j])); } } // Multiply the common Combination value sum1 = (sum * sum1); return sum1;} // Driver Codepublic static void Main(String []args){ int x = 3; int y = 2; int z = 1; Console.WriteLine(numberOfWays(x, y, z));}} // This code is contributed by Rajput-Ji
<script>// javascript program to find the number of// ways to form the group of peopls var C = Array(1000).fill().map(()=>Array(1000).fill(0)); // Function to pre-compute the // Combination using DP function binomialCoeff(n) { var i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= i; j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // return C[n][k]; } // Function to find the number of ways function numberOfWays(x , y , z) { // Function to pre-compute binomialCoeff(Math.max(x, Math.max(y, z))); // Sum the Zci var sum = 0; for (i = 1; i <= z; i++) { sum = (sum + C[z][i]); } // Iterate for second position var sum1 = 0; for (i = 1; i <= y; i++) { // Iterate for first position for (j = i + 1; j <= x; j++) { sum1 = (sum1 + (C[y][i] * C[x][j])); } } // Multiply the common Combination value sum1 = (sum * sum1); return sum1; } // Driver Code var x = 3; var y = 2; var z = 1; document.write(numberOfWays(x, y, z)); // This code contributed by aashish1995</script>
9
Time Complexity: O(K * K ), where K is the max of (x, y and z).
Auxiliary Space: O(1)
andrew1234
Rajput-Ji
nidhi_biet
mohit kumar 29
aashish1995
prachisoda1234
shivamanandrj9
Combinatorial
Dynamic Programming
Dynamic Programming
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "Given three numbers(x, y and z) which denote the number of people in the first group, the second group, and third group. We can form groups by selecting people from the first group, the second group and third group such that the following conditions are not void. "
},
{
"code": null,
"e": 355,
"s": 294,
"text": "A minimum of one people has to be selected from every group."
},
{
"code": null,
"e": 491,
"s": 355,
"text": "The number of people selected from the first group has to be at least one more than the number of people selected from the third group."
},
{
"code": null,
"e": 570,
"s": 491,
"text": "The task is to find the number of ways of forming distinct groups. Examples: "
},
{
"code": null,
"e": 875,
"s": 570,
"text": "Input: x = 3, y = 2, z = 1 Output: 9 Lets say x has people (a, b, c) Y has people (d, e) Z has people (f) Then the 9 ways are {a, b, d, f}, {a, b, e, f}, {a, c, d, f}, {a, c, e, f}, {b, c, d, f}, {b, c, e, f}, {a, b, c, d, f}, {a, b, c, e, f} and {a, b, c, d, e, f}Input: x = 4, y = 2, z = 1 Output: 27 "
},
{
"code": null,
"e": 1312,
"s": 877,
"text": "The problem can be solved using combinatorics. There are three positions(in terms of people from different groups) which need to be filled. The first has to be filled with a number with one or greater than the second position. The third can be filled with any number. We know if we need to fill k positions with N people, then the number of ways of doing it is . Hence the following steps can be followed to solve the above problem. "
},
{
"code": null,
"e": 1374,
"s": 1312,
"text": "The second position can be filled with i = 1 to i = y people."
},
{
"code": null,
"e": 1437,
"s": 1374,
"text": "The first position can be filled with j = i+1 to j = x people."
},
{
"code": null,
"e": 1512,
"s": 1437,
"text": "The third position can be filled with any number of k = 1 to k = z people."
},
{
"code": null,
"e": 1622,
"s": 1512,
"text": "Hence the common thing is filling the third position with k people. Hence we can take that portion as common."
},
{
"code": null,
"e": 1714,
"s": 1622,
"text": "Run two loops( i and j) for filling up the second position and first position respectively."
},
{
"code": null,
"e": 1768,
"s": 1714,
"text": "The number of ways of filling up the positions is * ."
},
{
"code": null,
"e": 1914,
"s": 1768,
"text": "After calculation of all ways to fill up those two positions, we can simply multiply summation of + + ... since that was the common part in both."
},
{
"code": null,
"e": 2070,
"s": 1914,
"text": "can be pre-computed using Dynamic Programming to reduce time complexity. The method is discussed here. Below is the implementation of the above approach. "
},
{
"code": null,
"e": 2074,
"s": 2070,
"text": "C++"
},
{
"code": null,
"e": 2079,
"s": 2074,
"text": "Java"
},
{
"code": null,
"e": 2087,
"s": 2079,
"text": "Python3"
},
{
"code": null,
"e": 2090,
"s": 2087,
"text": "C#"
},
{
"code": null,
"e": 2101,
"s": 2090,
"text": "Javascript"
},
{
"code": "// C++ program to find the number of// ways to form the group of people#include <bits/stdc++.h>using namespace std; int C[1000][1000]; // Function to pre-compute the// Combination using DPvoid binomialCoeff(int n){ int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= i; j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // return C[n][k];} // Function to find the number of waysint numberOfWays(int x, int y, int z){ // Function to pre-compute binomialCoeff(max(x, max(y, z))); // Sum the Zci int sum = 0; for (int i = 1; i <= z; i++) { sum = (sum + C[z][i]); } // Iterate for second position int sum1 = 0; for (int i = 1; i <= y; i++) { // Iterate for first position for (int j = i + 1; j <= x; j++) { sum1 = (sum1 + (C[y][i] * C[x][j])); } } // Multiply the common Combination value sum1 = (sum * sum1); return sum1;} // Driver Codeint main(){ int x = 3; int y = 2; int z = 1; cout << numberOfWays(x, y, z); return 0;}",
"e": 3420,
"s": 2101,
"text": null
},
{
"code": "// Java program to find the number of// ways to form the group of peoplsclass GFG{ static int C[][] = new int [1000][1000]; // Function to pre-compute the// Combination using DPstatic void binomialCoeff(int n){ int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= i; j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // return C[n][k];} // Function to find the number of waysstatic int numberOfWays(int x, int y, int z){ // Function to pre-compute binomialCoeff(Math.max(x, Math.max(y, z))); // Sum the Zci int sum = 0; for (int i = 1; i <= z; i++) { sum = (sum + C[z][i]); } // Iterate for second position int sum1 = 0; for (int i = 1; i <= y; i++) { // Iterate for first position for (int j = i + 1; j <= x; j++) { sum1 = (sum1 + (C[y][i] * C[x][j])); } } // Multiply the common Combination value sum1 = (sum * sum1); return sum1;} // Driver Codepublic static void main(String args[]){ int x = 3; int y = 2; int z = 1; System.out.println(numberOfWays(x, y, z));}} // This code is contributed by Arnab Kundu",
"e": 4849,
"s": 3420,
"text": null
},
{
"code": "# Python3 program to find the number of# ways to form the group of peoplsC = [[0 for i in range(1000)] for i in range(1000)] # Function to pre-compute the# Combination using DPdef binomialCoeff(n): i, j = 0, 0 # Calculate value of Binomial Coefficient # in bottom up manner for i in range(n + 1): for j in range(i + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using previously # stored values else: C[i][j] = C[i - 1][j - 1] + \\ C[i - 1][j] # return C[n][k] # Function to find the number of waysdef numberOfWays(x, y, z): # Function to pre-compute binomialCoeff(max(x, max(y, z))) # Sum the Zci sum = 0 for i in range(1, z + 1): sum = (sum + C[z][i]) # Iterate for second position sum1 = 0 for i in range(1, y + 1): # Iterate for first position for j in range(i + 1, x + 1): sum1 = (sum1 + (C[y][i] * C[x][j])) # Multiply the common Combination value sum1 = (sum * sum1) return sum1 # Driver Codex = 3y = 2z = 1 print(numberOfWays(x, y, z)) # This code is contributed by Mohit Kumar",
"e": 6076,
"s": 4849,
"text": null
},
{
"code": "// C# program to find the number of// ways to form the group of peoplsusing System; class GFG{ static int [,]C = new int [1000,1000]; // Function to pre-compute the// Combination using DPstatic void binomialCoeff(int n){ int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= i; j++) { // Base Cases if (j == 0 || j == i) C[i,j] = 1; // Calculate value using previously // stored values else C[i,j] = C[i - 1,j - 1] + C[i - 1,j]; } } // return C[n,k];} // Function to find the number of waysstatic int numberOfWays(int x, int y, int z){ // Function to pre-compute binomialCoeff(Math.Max(x, Math.Max(y, z))); // Sum the Zci int sum = 0; for (int i = 1; i <= z; i++) { sum = (sum + C[z,i]); } // Iterate for second position int sum1 = 0; for (int i = 1; i <= y; i++) { // Iterate for first position for (int j = i + 1; j <= x; j++) { sum1 = (sum1 + (C[y,i] * C[x,j])); } } // Multiply the common Combination value sum1 = (sum * sum1); return sum1;} // Driver Codepublic static void Main(String []args){ int x = 3; int y = 2; int z = 1; Console.WriteLine(numberOfWays(x, y, z));}} // This code is contributed by Rajput-Ji",
"e": 7508,
"s": 6076,
"text": null
},
{
"code": "<script>// javascript program to find the number of// ways to form the group of peopls var C = Array(1000).fill().map(()=>Array(1000).fill(0)); // Function to pre-compute the // Combination using DP function binomialCoeff(n) { var i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= i; j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // return C[n][k]; } // Function to find the number of ways function numberOfWays(x , y , z) { // Function to pre-compute binomialCoeff(Math.max(x, Math.max(y, z))); // Sum the Zci var sum = 0; for (i = 1; i <= z; i++) { sum = (sum + C[z][i]); } // Iterate for second position var sum1 = 0; for (i = 1; i <= y; i++) { // Iterate for first position for (j = i + 1; j <= x; j++) { sum1 = (sum1 + (C[y][i] * C[x][j])); } } // Multiply the common Combination value sum1 = (sum * sum1); return sum1; } // Driver Code var x = 3; var y = 2; var z = 1; document.write(numberOfWays(x, y, z)); // This code contributed by aashish1995</script>",
"e": 9050,
"s": 7508,
"text": null
},
{
"code": null,
"e": 9052,
"s": 9050,
"text": "9"
},
{
"code": null,
"e": 9118,
"s": 9054,
"text": "Time Complexity: O(K * K ), where K is the max of (x, y and z)."
},
{
"code": null,
"e": 9141,
"s": 9118,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 9152,
"s": 9141,
"text": "andrew1234"
},
{
"code": null,
"e": 9162,
"s": 9152,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9173,
"s": 9162,
"text": "nidhi_biet"
},
{
"code": null,
"e": 9188,
"s": 9173,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 9200,
"s": 9188,
"text": "aashish1995"
},
{
"code": null,
"e": 9215,
"s": 9200,
"text": "prachisoda1234"
},
{
"code": null,
"e": 9230,
"s": 9215,
"text": "shivamanandrj9"
},
{
"code": null,
"e": 9244,
"s": 9230,
"text": "Combinatorial"
},
{
"code": null,
"e": 9264,
"s": 9244,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9284,
"s": 9264,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9298,
"s": 9284,
"text": "Combinatorial"
}
] |
Sending HTTP Request Using cURL Set-1 | 01 Aug, 2021
Whenever we are dealing with HTTP requests, cURL simplifies our tasks to a great extent and is the easiest tool to get our hands dirty on.
cURL: It stands for “client URL” and is used in command line or scripts to transfer data. It is a great tool for dealing with HTTP requests like GET, POST, PUT, DELETE, etc. Although it provides us with the support of other internet protocols like HTTPS, FTP, SMTP, TELNET, we will be limiting it to HTTP in this article.
Pre-requisite: Install cURL properly as per your underlying operating system.
To check if it’s installed in your system or to know its version, the following command is executed in the command prompt
Syntax:
curl --version
Output:
curl 7.67.0 (x86_64-pc-linux-gnu) libcurl/7.67.0 OpenSSL/1.1.1d zlib/1.2.11 brotli/1.0.7 libidn2/2.2.0 libpsl/0.20.2 (+libidn2/2.0.5) libssh2/1.8.0 nghttp2/1.41.0 librtmp/2.3 Release-Date: 2019-11-06 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smb smbs smtp smtps telnet tftp Features: AsynchDNS brotli GSS-API HTTP2 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM NTLM_WB PSL SPNEGO SSL TLS-SRP UnixSockets
We can see that the output states the version, release date, protocols, and other features of curl as –version flag was used.
Note: The output may differ based on the version and the underlying operating system.
GET request using cURL: Get request is the most commonly used HTTP request as it is used to request the data from the server about a particular target i.e website. Let’s start by executing a simple Get request.
curl http://138.68.158.87:30954/login.php
Note that instead of http://138.68.158.87:30954/login.php, you can specify the target on which you want to request the data.
Example :
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="./style.css"></head> <body> <hgroup> <h1>Admin panel</h1> </hgroup> <form action="" method="post"> <div class="group"> <input name="username" type="text"> <span class="highlight"></span> <span class="bar"></span> <label>Username</label> </div> <div class="group"> <input name="password" type="password"> <span class="highlight"></span> <span class="bar"></span> <label>Password</label> </div> <button type="submit" class="button buttonBlue"> Login <div class="ripples buttonRipples"> <span class="ripplesCircle"></span> </div> </button> </form> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'> </script> <script src="./script.js"></script></body> </html>
In this manner, you will get the entire output which will be the same if your query through the browser and the response from the server is rendered by your client browser and then shown to you in a simplified manner.
Note: If you will view the target source code, you will find the same output.
Many other flags can be used with the above query.
-v: It is used to get verbose output.
curl http://138.68.158.87:30954/login.php -v
-u: Server user and password.
curl -u username:password http://138.68.158.87:30954/login.php -v
-L: Follow redirects.
curl -u username:password -L http://138.68.158.87:30954/login.php -v
-X: Specify request command to use.
curl -X GET http://138.68.158.87:30954/login.php -v
Note: By default curl uses GET request if we don’t specify the request command.
-s: Silent mode.
curl -u username:password -s -L http://138.68.158.87:30954/login.php -v
You can dive deeply into using different flags as per the need with the help of the -h flag.
curl -h
umangthakkar
PHP-cURL
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Whenever we are dealing with HTTP requests, cURL simplifies our tasks to a great extent and is the easiest tool to get our hands dirty on."
},
{
"code": null,
"e": 489,
"s": 167,
"text": "cURL: It stands for “client URL” and is used in command line or scripts to transfer data. It is a great tool for dealing with HTTP requests like GET, POST, PUT, DELETE, etc. Although it provides us with the support of other internet protocols like HTTPS, FTP, SMTP, TELNET, we will be limiting it to HTTP in this article."
},
{
"code": null,
"e": 568,
"s": 489,
"text": "Pre-requisite: Install cURL properly as per your underlying operating system. "
},
{
"code": null,
"e": 690,
"s": 568,
"text": "To check if it’s installed in your system or to know its version, the following command is executed in the command prompt"
},
{
"code": null,
"e": 698,
"s": 690,
"text": "Syntax:"
},
{
"code": null,
"e": 714,
"s": 698,
"text": " curl --version"
},
{
"code": null,
"e": 722,
"s": 714,
"text": "Output:"
},
{
"code": null,
"e": 1190,
"s": 722,
"text": "curl 7.67.0 (x86_64-pc-linux-gnu) libcurl/7.67.0 OpenSSL/1.1.1d zlib/1.2.11 brotli/1.0.7 libidn2/2.2.0 libpsl/0.20.2 (+libidn2/2.0.5) libssh2/1.8.0 nghttp2/1.41.0 librtmp/2.3 Release-Date: 2019-11-06 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smb smbs smtp smtps telnet tftp Features: AsynchDNS brotli GSS-API HTTP2 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM NTLM_WB PSL SPNEGO SSL TLS-SRP UnixSockets "
},
{
"code": null,
"e": 1316,
"s": 1190,
"text": "We can see that the output states the version, release date, protocols, and other features of curl as –version flag was used."
},
{
"code": null,
"e": 1402,
"s": 1316,
"text": "Note: The output may differ based on the version and the underlying operating system."
},
{
"code": null,
"e": 1613,
"s": 1402,
"text": "GET request using cURL: Get request is the most commonly used HTTP request as it is used to request the data from the server about a particular target i.e website. Let’s start by executing a simple Get request."
},
{
"code": null,
"e": 1656,
"s": 1613,
"text": " curl http://138.68.158.87:30954/login.php"
},
{
"code": null,
"e": 1781,
"s": 1656,
"text": "Note that instead of http://138.68.158.87:30954/login.php, you can specify the target on which you want to request the data."
},
{
"code": null,
"e": 1791,
"s": 1781,
"text": "Example :"
},
{
"code": null,
"e": 1796,
"s": 1791,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <link rel=\"stylesheet\" href=\"./style.css\"></head> <body> <hgroup> <h1>Admin panel</h1> </hgroup> <form action=\"\" method=\"post\"> <div class=\"group\"> <input name=\"username\" type=\"text\"> <span class=\"highlight\"></span> <span class=\"bar\"></span> <label>Username</label> </div> <div class=\"group\"> <input name=\"password\" type=\"password\"> <span class=\"highlight\"></span> <span class=\"bar\"></span> <label>Password</label> </div> <button type=\"submit\" class=\"button buttonBlue\"> Login <div class=\"ripples buttonRipples\"> <span class=\"ripplesCircle\"></span> </div> </button> </form> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'> </script> <script src=\"./script.js\"></script></body> </html>",
"e": 2791,
"s": 1796,
"text": null
},
{
"code": null,
"e": 3009,
"s": 2791,
"text": "In this manner, you will get the entire output which will be the same if your query through the browser and the response from the server is rendered by your client browser and then shown to you in a simplified manner."
},
{
"code": null,
"e": 3087,
"s": 3009,
"text": "Note: If you will view the target source code, you will find the same output."
},
{
"code": null,
"e": 3140,
"s": 3087,
"text": "Many other flags can be used with the above query. "
},
{
"code": null,
"e": 3180,
"s": 3140,
"text": "-v: It is used to get verbose output. "
},
{
"code": null,
"e": 3225,
"s": 3180,
"text": "curl http://138.68.158.87:30954/login.php -v"
},
{
"code": null,
"e": 3257,
"s": 3225,
"text": "-u: Server user and password. "
},
{
"code": null,
"e": 3324,
"s": 3257,
"text": " curl -u username:password http://138.68.158.87:30954/login.php -v"
},
{
"code": null,
"e": 3348,
"s": 3324,
"text": "-L: Follow redirects. "
},
{
"code": null,
"e": 3417,
"s": 3348,
"text": "curl -u username:password -L http://138.68.158.87:30954/login.php -v"
},
{
"code": null,
"e": 3455,
"s": 3417,
"text": "-X: Specify request command to use. "
},
{
"code": null,
"e": 3507,
"s": 3455,
"text": "curl -X GET http://138.68.158.87:30954/login.php -v"
},
{
"code": null,
"e": 3587,
"s": 3507,
"text": "Note: By default curl uses GET request if we don’t specify the request command."
},
{
"code": null,
"e": 3606,
"s": 3587,
"text": "-s: Silent mode. "
},
{
"code": null,
"e": 3678,
"s": 3606,
"text": "curl -u username:password -s -L http://138.68.158.87:30954/login.php -v"
},
{
"code": null,
"e": 3771,
"s": 3678,
"text": "You can dive deeply into using different flags as per the need with the help of the -h flag."
},
{
"code": null,
"e": 3779,
"s": 3771,
"text": "curl -h"
},
{
"code": null,
"e": 3794,
"s": 3781,
"text": "umangthakkar"
},
{
"code": null,
"e": 3803,
"s": 3794,
"text": "PHP-cURL"
},
{
"code": null,
"e": 3817,
"s": 3803,
"text": "PHP-Questions"
},
{
"code": null,
"e": 3821,
"s": 3817,
"text": "PHP"
},
{
"code": null,
"e": 3838,
"s": 3821,
"text": "Web Technologies"
},
{
"code": null,
"e": 3842,
"s": 3838,
"text": "PHP"
}
] |
Iterative Fast Fourier Transformation for polynomial multiplication | 08 Jun, 2022
Given two polynomials, A(x) and B(x), find the product C(x) = A(x)*B(x). In the previous post, we discussed the recursive approach to solve this problem which has O(nlogn) complexity. Examples:
Input :
A[] = {9, -10, 7, 6}
B[] = {-5, 4, 0, -2}
Output :
C(x) =
In real-life applications such as signal processing, speed matters a lot, this article examines an efficient FFT implementation. This article focuses on the iterative version of the FFT algorithm that runs in O(nlogn) time but can have a lower constant hidden than the recursive version plus it saves the recursion stack space. Pre-requisite: recursive algorithm of FFT. Recall the recursive-FFT pseudo code from previous post, in the for loop evaluation of , is calculated twice. We can change the loop to compute it only once, storing it in a temporary variable t. So, it becomes, for k 0 to n/2 – 1 do tThe operation in this loop, multiplying the twiddle factor w = by , storing the product into t, and adding and subtracting t from , is known as a butterfly operation. Pictorially, this is what a butterfly operation looks like:
Let us take for n=8 and proceed with the formation of the iterative FFT algorithm. Looking at the recursion tree above, we find that if we arrange the elements of the initial coefficient vector into the order in which they appear in the leaves, we could trace the execution of the Recursive-FFT procedure, but bottom-up instead of top-down. First, we take the elements in pairs, compute the DFT of each pair using one butterfly operation, and replace the pair with its DFT. The vector then holds n/2 2-element DFTs. Next, we take these n/2 DFTs in pairs and compute the DFT of the four-vector elements they come from by executing two butterfly operations, replacing two 2-element DFTs with one 4-element DFT. The vector then holds n/4 4-element DFTs. We continue in this manner until the vector holds two (n/2) element DFTs, which we combine using n/2 butterfly operations into the final n-element DFT.
To turn this bottom-up approach into code, we use an array A[0...n] that initially holds the elements of the input vector a in the order in which they appear in the leaves of the tree. Because we have to combine DFT so n each level of the tree, we introduce a variable s to count the levels, ranging from 1 (at the bottom, when we are combining pairs to form 2-element DFTs) to lgn (at the top, when we are combining two n/2 element DFTs to produce the final result). The algorithm therefore is:
1. for s=1 to lgn
2. do for k=0 to n-1 by 3. do combine the two -element DFTs in A[k...k+-1] and A[k+...k+-1] into one 2s-element DFT in A[k...k+-1]
Now for generating the code, we arrange the coefficient vector elements in the order of leaves. Example- The order in leaves 0, 4, 2, 6, 1, 5, 3, 7 is a bit reversal of the indices. Start with 000, 001, 010, 011, 100, 101, 110, 111 and reverse the bits of each binary number to obtain 000, 100, 010, 110, 001, 101, 011, 111.Pseudocode for iterative FFT :
BIT-REVERSE-COPY(a, A)
n = length [a]
for k = 0 to n-1
do A[rev(k)] = a[k]
ITERATIVE-FFT
BIT-REVERSE-COPY(a, A)
n = length(a)
for s = 1 to log n
do m= = for j = 0 to m/2-1 do for k = j to n-1 by m do t = A[k+m/2] u = A[k] A[k] = u+t A[k+m/2] = u-t return A
It will be more clear from the below parallel FFT circuit :
CPP
// CPP program to implement iterative// fast Fourier transform.#include <bits/stdc++.h>using namespace std; typedef complex<double> cd;const double PI = 3.1415926536; // Utility function for reversing the bits// of given index xunsigned int bitReverse(unsigned int x, int log2n){ int n = 0; for (int i = 0; i < log2n; i++) { n <<= 1; n |= (x & 1); x >>= 1; } return n;} // Iterative FFT function to compute the DFT// of given coefficient vectorvoid fft(vector<cd>& a, vector<cd>& A, int log2n){ int n = 4; // bit reversal of the given array for (unsigned int i = 0; i < n; ++i) { int rev = bitReverse(i, log2n); A[i] = a[rev]; } // j is iota const complex<double> J(0, 1); for (int s = 1; s <= log2n; ++s) { int m = 1 << s; // 2 power s int m2 = m >> 1; // m2 = m/2 -1 cd w(1, 0); // principle root of nth complex // root of unity. cd wm = exp(J * (PI / m2)); for (int j = 0; j < m2; ++j) { for (int k = j; k < n; k += m) { // t = twiddle factor cd t = w * A[k + m2]; cd u = A[k]; // similar calculating y[k] A[k] = u + t; // similar calculating y[k+n/2] A[k + m2] = u - t; } w *= wm; } }} int main(){ vector<cd> a{ 1, 2, 3, 4 }; vector<cd> A(4); fft(a, A, 2); for (int i = 0; i < 4; ++i) cout << A[i] << "\n";}
Input: 1 2 3 4
Output:
(10, 0)
(-2, -2)
(-2, 0)
(-2, 2)
Time complexity Analysis: The complexity is O(nlgn). To show this we show the innermost loop runs in O(nlgn) time as :
akshaysingh98088
surinderdawra388
harshmaster07705
Divide and Conquer
Divide and Conquer
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge Sort
QuickSort
Binary Search
Count Inversions in an array | Set 1 (Using Merge Sort)
Median of two sorted arrays of different sizes
Find a peak element
Median of two sorted arrays of same size
Allocate minimum number of pages
Quick Sort vs Merge Sort
Square root of an integer | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 250,
"s": 54,
"text": "Given two polynomials, A(x) and B(x), find the product C(x) = A(x)*B(x). In the previous post, we discussed the recursive approach to solve this problem which has O(nlogn) complexity. Examples: "
},
{
"code": null,
"e": 321,
"s": 250,
"text": "Input : \n A[] = {9, -10, 7, 6}\n B[] = {-5, 4, 0, -2}\nOutput :\n C(x) = "
},
{
"code": null,
"e": 1158,
"s": 323,
"text": "In real-life applications such as signal processing, speed matters a lot, this article examines an efficient FFT implementation. This article focuses on the iterative version of the FFT algorithm that runs in O(nlogn) time but can have a lower constant hidden than the recursive version plus it saves the recursion stack space. Pre-requisite: recursive algorithm of FFT. Recall the recursive-FFT pseudo code from previous post, in the for loop evaluation of , is calculated twice. We can change the loop to compute it only once, storing it in a temporary variable t. So, it becomes, for k 0 to n/2 – 1 do tThe operation in this loop, multiplying the twiddle factor w = by , storing the product into t, and adding and subtracting t from , is known as a butterfly operation. Pictorially, this is what a butterfly operation looks like: "
},
{
"code": null,
"e": 2063,
"s": 1158,
"text": "Let us take for n=8 and proceed with the formation of the iterative FFT algorithm. Looking at the recursion tree above, we find that if we arrange the elements of the initial coefficient vector into the order in which they appear in the leaves, we could trace the execution of the Recursive-FFT procedure, but bottom-up instead of top-down. First, we take the elements in pairs, compute the DFT of each pair using one butterfly operation, and replace the pair with its DFT. The vector then holds n/2 2-element DFTs. Next, we take these n/2 DFTs in pairs and compute the DFT of the four-vector elements they come from by executing two butterfly operations, replacing two 2-element DFTs with one 4-element DFT. The vector then holds n/4 4-element DFTs. We continue in this manner until the vector holds two (n/2) element DFTs, which we combine using n/2 butterfly operations into the final n-element DFT. "
},
{
"code": null,
"e": 2561,
"s": 2063,
"text": "To turn this bottom-up approach into code, we use an array A[0...n] that initially holds the elements of the input vector a in the order in which they appear in the leaves of the tree. Because we have to combine DFT so n each level of the tree, we introduce a variable s to count the levels, ranging from 1 (at the bottom, when we are combining pairs to form 2-element DFTs) to lgn (at the top, when we are combining two n/2 element DFTs to produce the final result). The algorithm therefore is: "
},
{
"code": null,
"e": 2755,
"s": 2561,
"text": "1. for s=1 to lgn\n2. do for k=0 to n-1 by 3. do combine the two -element DFTs in A[k...k+-1] and A[k+...k+-1] into one 2s-element DFT in A[k...k+-1]"
},
{
"code": null,
"e": 3112,
"s": 2755,
"text": "Now for generating the code, we arrange the coefficient vector elements in the order of leaves. Example- The order in leaves 0, 4, 2, 6, 1, 5, 3, 7 is a bit reversal of the indices. Start with 000, 001, 010, 011, 100, 101, 110, 111 and reverse the bits of each binary number to obtain 000, 100, 010, 110, 001, 101, 011, 111.Pseudocode for iterative FFT : "
},
{
"code": null,
"e": 3515,
"s": 3112,
"text": "BIT-REVERSE-COPY(a, A)\nn = length [a]\nfor k = 0 to n-1\n do A[rev(k)] = a[k]\n \nITERATIVE-FFT\nBIT-REVERSE-COPY(a, A)\nn = length(a)\nfor s = 1 to log n\n do m= = for j = 0 to m/2-1 do for k = j to n-1 by m do t = A[k+m/2] u = A[k] A[k] = u+t A[k+m/2] = u-t return A"
},
{
"code": null,
"e": 3577,
"s": 3515,
"text": "It will be more clear from the below parallel FFT circuit : "
},
{
"code": null,
"e": 3583,
"s": 3579,
"text": "CPP"
},
{
"code": "// CPP program to implement iterative// fast Fourier transform.#include <bits/stdc++.h>using namespace std; typedef complex<double> cd;const double PI = 3.1415926536; // Utility function for reversing the bits// of given index xunsigned int bitReverse(unsigned int x, int log2n){ int n = 0; for (int i = 0; i < log2n; i++) { n <<= 1; n |= (x & 1); x >>= 1; } return n;} // Iterative FFT function to compute the DFT// of given coefficient vectorvoid fft(vector<cd>& a, vector<cd>& A, int log2n){ int n = 4; // bit reversal of the given array for (unsigned int i = 0; i < n; ++i) { int rev = bitReverse(i, log2n); A[i] = a[rev]; } // j is iota const complex<double> J(0, 1); for (int s = 1; s <= log2n; ++s) { int m = 1 << s; // 2 power s int m2 = m >> 1; // m2 = m/2 -1 cd w(1, 0); // principle root of nth complex // root of unity. cd wm = exp(J * (PI / m2)); for (int j = 0; j < m2; ++j) { for (int k = j; k < n; k += m) { // t = twiddle factor cd t = w * A[k + m2]; cd u = A[k]; // similar calculating y[k] A[k] = u + t; // similar calculating y[k+n/2] A[k + m2] = u - t; } w *= wm; } }} int main(){ vector<cd> a{ 1, 2, 3, 4 }; vector<cd> A(4); fft(a, A, 2); for (int i = 0; i < 4; ++i) cout << A[i] << \"\\n\";}",
"e": 5088,
"s": 3583,
"text": null
},
{
"code": null,
"e": 5145,
"s": 5088,
"text": "Input: 1 2 3 4\nOutput:\n(10, 0)\n(-2, -2)\n(-2, 0)\n(-2, 2)"
},
{
"code": null,
"e": 5266,
"s": 5145,
"text": "Time complexity Analysis: The complexity is O(nlgn). To show this we show the innermost loop runs in O(nlgn) time as : "
},
{
"code": null,
"e": 5283,
"s": 5266,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 5300,
"s": 5283,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5317,
"s": 5300,
"text": "harshmaster07705"
},
{
"code": null,
"e": 5336,
"s": 5317,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5355,
"s": 5336,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5453,
"s": 5355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5464,
"s": 5453,
"text": "Merge Sort"
},
{
"code": null,
"e": 5474,
"s": 5464,
"text": "QuickSort"
},
{
"code": null,
"e": 5488,
"s": 5474,
"text": "Binary Search"
},
{
"code": null,
"e": 5544,
"s": 5488,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 5591,
"s": 5544,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 5611,
"s": 5591,
"text": "Find a peak element"
},
{
"code": null,
"e": 5652,
"s": 5611,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 5685,
"s": 5652,
"text": "Allocate minimum number of pages"
},
{
"code": null,
"e": 5710,
"s": 5685,
"text": "Quick Sort vs Merge Sort"
}
] |
XML full form | 19 Oct, 2021
XML stands for Extensible Markup Language that is used to encode the document that can be understandable by humans and machines both. A data is stored in XML format is easy to understand and easy to modify. This format was designed to transport and store data in a specific format. There are three main things that have to keeps in your mind when you are using the XML – Simplicity, Generality, and Usability. XML contains a few rules that you have to follow like opening and closing tags. XML was invented in the year of 1998, after that, it was modified in the year of 2006 and 2008 which is the latest standard edition of XML.
There are few key terminologies in the XML:
Character: XML is a string of characters that can cover every Unicode characters.
Markup and content: If the string constitutes markup then it will be started with <, and ended with >. And if the string that constitutes content then it will start with & and end with ;
Tag: The markup tag start with <tag> and ends with </tag > and the empty element tag <line-break/>
Elements: The elements placed between the start tag and the end tag like <tag> elements </tag >
Attribute: The attribute placed inside the start tag like <tag attribute=”value”> elements </tag >. It is used to hold the behavior of the elements.
Characteristics of XML:
Structure: XML is a structured format where we can decide how to arrange the data within a file. We can struct as we want, put any data at any place.
Described: XML data format is a much more described format if you’re familiar with the HTML then you can easily understand the XML, it will look to you as a normal text.
Validated: Validation comes in mind when you have to follow some specific structure for your data, you can describe exactly how the XML data file should be structured in another XML file.
Discoverable: Any language can easily discover the data from an XML data and can create another XML data that will follow the validation also.
Strongly-formed: The application can check the schema definition to identify the data type to import it.
Advantage of XML:
XML is easy to read and write to normal human being can understand the XML.
Backward and forward compatibility is so easy to maintain.
It has one standard that the international standard means any language can collaborate with the XML easily.
It is platform-independent that means resistance changes in technologies.
XML can upgrade incrementally.
Disadvantage of XML:
The namespace support can be difficult to correctly implement in an XML parser.
XML become complex when you are trying to struct a lots of data manually.
It required so many tags to struct the data compared to JSON.
XML node relation required extra effort.
XML encourage non-relational database.
prachisoda1234
HTML and XML
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How do you run JavaScript script through the Terminal?
How to set input type date in dd-mm-yyyy format using HTML ?
Node.js | fs.writeFileSync() Method
Types of CSS (Cascading Style Sheet)
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set space between the flexbox ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 659,
"s": 28,
"text": "XML stands for Extensible Markup Language that is used to encode the document that can be understandable by humans and machines both. A data is stored in XML format is easy to understand and easy to modify. This format was designed to transport and store data in a specific format. There are three main things that have to keeps in your mind when you are using the XML – Simplicity, Generality, and Usability. XML contains a few rules that you have to follow like opening and closing tags. XML was invented in the year of 1998, after that, it was modified in the year of 2006 and 2008 which is the latest standard edition of XML. "
},
{
"code": null,
"e": 705,
"s": 659,
"text": "There are few key terminologies in the XML: "
},
{
"code": null,
"e": 787,
"s": 705,
"text": "Character: XML is a string of characters that can cover every Unicode characters."
},
{
"code": null,
"e": 974,
"s": 787,
"text": "Markup and content: If the string constitutes markup then it will be started with <, and ended with >. And if the string that constitutes content then it will start with & and end with ;"
},
{
"code": null,
"e": 1073,
"s": 974,
"text": "Tag: The markup tag start with <tag> and ends with </tag > and the empty element tag <line-break/>"
},
{
"code": null,
"e": 1169,
"s": 1073,
"text": "Elements: The elements placed between the start tag and the end tag like <tag> elements </tag >"
},
{
"code": null,
"e": 1318,
"s": 1169,
"text": "Attribute: The attribute placed inside the start tag like <tag attribute=”value”> elements </tag >. It is used to hold the behavior of the elements."
},
{
"code": null,
"e": 1344,
"s": 1318,
"text": "Characteristics of XML: "
},
{
"code": null,
"e": 1494,
"s": 1344,
"text": "Structure: XML is a structured format where we can decide how to arrange the data within a file. We can struct as we want, put any data at any place."
},
{
"code": null,
"e": 1664,
"s": 1494,
"text": "Described: XML data format is a much more described format if you’re familiar with the HTML then you can easily understand the XML, it will look to you as a normal text."
},
{
"code": null,
"e": 1852,
"s": 1664,
"text": "Validated: Validation comes in mind when you have to follow some specific structure for your data, you can describe exactly how the XML data file should be structured in another XML file."
},
{
"code": null,
"e": 1995,
"s": 1852,
"text": "Discoverable: Any language can easily discover the data from an XML data and can create another XML data that will follow the validation also."
},
{
"code": null,
"e": 2100,
"s": 1995,
"text": "Strongly-formed: The application can check the schema definition to identify the data type to import it."
},
{
"code": null,
"e": 2120,
"s": 2100,
"text": "Advantage of XML: "
},
{
"code": null,
"e": 2196,
"s": 2120,
"text": "XML is easy to read and write to normal human being can understand the XML."
},
{
"code": null,
"e": 2255,
"s": 2196,
"text": "Backward and forward compatibility is so easy to maintain."
},
{
"code": null,
"e": 2363,
"s": 2255,
"text": "It has one standard that the international standard means any language can collaborate with the XML easily."
},
{
"code": null,
"e": 2437,
"s": 2363,
"text": "It is platform-independent that means resistance changes in technologies."
},
{
"code": null,
"e": 2468,
"s": 2437,
"text": "XML can upgrade incrementally."
},
{
"code": null,
"e": 2491,
"s": 2468,
"text": "Disadvantage of XML: "
},
{
"code": null,
"e": 2571,
"s": 2491,
"text": "The namespace support can be difficult to correctly implement in an XML parser."
},
{
"code": null,
"e": 2645,
"s": 2571,
"text": "XML become complex when you are trying to struct a lots of data manually."
},
{
"code": null,
"e": 2707,
"s": 2645,
"text": "It required so many tags to struct the data compared to JSON."
},
{
"code": null,
"e": 2748,
"s": 2707,
"text": "XML node relation required extra effort."
},
{
"code": null,
"e": 2787,
"s": 2748,
"text": "XML encourage non-relational database."
},
{
"code": null,
"e": 2804,
"s": 2789,
"text": "prachisoda1234"
},
{
"code": null,
"e": 2817,
"s": 2804,
"text": "HTML and XML"
},
{
"code": null,
"e": 2834,
"s": 2817,
"text": "Web Technologies"
},
{
"code": null,
"e": 2861,
"s": 2834,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2959,
"s": 2861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2992,
"s": 2959,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 3052,
"s": 2992,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 3107,
"s": 3052,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 3168,
"s": 3107,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 3204,
"s": 3168,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 3241,
"s": 3204,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3301,
"s": 3241,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 3328,
"s": 3301,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 3367,
"s": 3328,
"text": "How to set space between the flexbox ?"
}
] |
Creating a PortScanner in C | 29 May, 2016
Picture a bay where lots of private boats are docked. The location is called a seaport, literally a port at or on the sea. Everyone wanting to dock there, requesting landing services uses the same port. Seaports work with berth numbers assigned to individual boats. The port name and the berth number combine into the “who, what, and where” of boat identification.
The concept of ip address and port is similar. Here the sea_port_name is similar to the IP address while the latter matches with the network_port_no.
Ports are numbered for consistency and programming. The most commonly used and best known ports are those numbered 0 to 1023 dedicated for Internet use, but they can extend far higher for specialized purposes. Each port set or range is assigned specialized jobs or functions, and that’s generally all they do. Usually, all identical system services or functions use the same port numbers on the receiving servers and they remain consistent what-so-ever may be the situation.
When a criminal targets a house for a burglary, typically the first thing he or she checks is if there is an open window or door through which access to the home can be gained. Security technicians often use devices/softwares, known as port-scanners, that enable them to scan all the ports to audit computers for vulnerabilities. Any time there are open ports on one’s personal computer, there is potential for the loss of data, the occurrence of a virus, and at times, even complete system compromise.
Developing a port-scanner is not so difficult as it may seem. The end result of the scanner will be as follows:
INPUT : IPv4 address, Port Range
FUNCTION : Enter an IP address and a port range
where the program will then attempt to
find open ports on the given computer
by connecting to each of them. On any
successful connection ports, mark the
port as open.
OUTPUT : Status of port (open/closed)
The Three step Process for creating a Port Scanner
Step 1: Creating the main()
We create a main() function that takes in the required arguments (server_ip, start_port, end_port). The server IP must be IPv4, though we can extend it to accept IPv6 as well. Try it yourself !!
int main(int argc, char *argv[])
{
if (argc < 4)
{
printf ("Please enter the server IP address"
" and range of ports to be scanned\n");
printf ("USAGE: %s IPv4 First_Port Last_Port\n",
argv[0]);
exit(1);
}
char tIP[16] = {0};
strcpy(tIP, argv[1]); // Copy the IPv4 address
char First_Port[6] = {0};
strcpy(First_Port, argv[2]); // Copy the start_port
char Last_Port[6] = {0};
strcpy(Last_Port, argv[3]); // Copy the end_port
// Start port-scanner
port_scanner(tIP, First_Port, Last_Port);
return 0;
}
Step 2: Creating the port_scanner()
Create a new function, port_scanner(). We traverse through all the ports in range provided and then check against each one of them.
Create a “struct addrinfo hints” and initialize it with proper values.
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
‘hints’ is an optional pointer to a struct addrinfo, as defined by . This structure can be used to provide hints concerning the type of socket that the caller supports or wishes to use. – from the FreeBSD man page.
Initialize a pointer for the server_address that we will obtain from the server.Now, call “getaddrinfo(tIP, tport, &hints, &serv_addr)” with proper parameters. The getaddrinfo() function allocates and initializes a linked list of addrinfo structures, one for each network address that matches node and service, subject to any restrictions imposed by hints, and returns a pointer to the start of the list in the 4th paraments, in this case “serv_addr”. The items in the linked list are linked by the ai_next field.
Additional Info:There are several reasons why the linked list may have more than one addrinfo structure, including: the network host is multihomed, accessible over multiple protocols (e.g., both AF_INET and AF_INET6); or the same service is available from multiple socket types (one SOCK_STREAM address and another SOCK_DGRAM address, for example).Normally, the application should try using the addresses in the order in which they are returned.
Step 3: Connecting against the sockets
Traverse through all the addrinfo received in the linked list, and create a socket. The values for the “socket()” are present in the addrinfo struct obtained above. (Each node of the linked_list is traversed using the pointer “temp”.)
sockfd = socket(temp->ai_family, temp->ai_socktype,
temp->ai_protocol);
if (sockfd < 0)
{
printf("Port %d is NOT open.\n", port);
continue;
}
If the socket creation fails, then try using the values in other nodes. Once socket creation succeeds, try connecting to it using the “connect()”. If the connection is a success, then congratulations, the socket is OPEN, else try with the other addrinfo nodes. If none of them works from the linked_list, then the socket is CLOSED. Here is the code for the same,
status = connect(sockfd, temp->ai_addr,
temp->ai_addrlen);
if (status<0)
{
printf("Port %d is NOT open.\n", port);
close(sockfd);
continue;
}
printf("Port %d is open.\n", port);
close(sockfd);
The “freeaddrinfo()” function frees the memory that was allocated for the dynamically allocated linked list “serv_addr”. It is a good practice to use this instead of “free()”.
The full source code for this tutorial can be downloaded from here.
Note: The code for this program is not long, but how the addresses are derived using getaddrinfo is very important. Almost all networking applications in c have similar first 2 steps. The 3rd step depends on the purpose of the application.
For more info regarding the struct returned by freeaddrinfo, read this documentation and details of the arguments of socket, go through this documentation.
About the Author:
Pinkesh Badjatiya hails from IIIT Hyderabad. He is a geek at heart with ample projects worth looking for. His project work can be seen here.
If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.
GBlog
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
How to Learn Data Science in 10 weeks?
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
SDE SHEET - A Complete Guide for SDE Preparation
Implementing Web Scraping in Python with BeautifulSoup
Working with zip files in Python
XML parsing in Python
Python | Simple GUI calculator using Tkinter | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 May, 2016"
},
{
"code": null,
"e": 419,
"s": 54,
"text": "Picture a bay where lots of private boats are docked. The location is called a seaport, literally a port at or on the sea. Everyone wanting to dock there, requesting landing services uses the same port. Seaports work with berth numbers assigned to individual boats. The port name and the berth number combine into the “who, what, and where” of boat identification."
},
{
"code": null,
"e": 569,
"s": 419,
"text": "The concept of ip address and port is similar. Here the sea_port_name is similar to the IP address while the latter matches with the network_port_no."
},
{
"code": null,
"e": 1044,
"s": 569,
"text": "Ports are numbered for consistency and programming. The most commonly used and best known ports are those numbered 0 to 1023 dedicated for Internet use, but they can extend far higher for specialized purposes. Each port set or range is assigned specialized jobs or functions, and that’s generally all they do. Usually, all identical system services or functions use the same port numbers on the receiving servers and they remain consistent what-so-ever may be the situation."
},
{
"code": null,
"e": 1547,
"s": 1044,
"text": "When a criminal targets a house for a burglary, typically the first thing he or she checks is if there is an open window or door through which access to the home can be gained. Security technicians often use devices/softwares, known as port-scanners, that enable them to scan all the ports to audit computers for vulnerabilities. Any time there are open ports on one’s personal computer, there is potential for the loss of data, the occurrence of a virus, and at times, even complete system compromise."
},
{
"code": null,
"e": 1659,
"s": 1547,
"text": "Developing a port-scanner is not so difficult as it may seem. The end result of the scanner will be as follows:"
},
{
"code": null,
"e": 2005,
"s": 1659,
"text": "INPUT : IPv4 address, Port Range\nFUNCTION : Enter an IP address and a port range \n where the program will then attempt to\n find open ports on the given computer \n by connecting to each of them. On any \n successful connection ports, mark the \n port as open.\nOUTPUT : Status of port (open/closed)\n"
},
{
"code": null,
"e": 2056,
"s": 2005,
"text": "The Three step Process for creating a Port Scanner"
},
{
"code": null,
"e": 2084,
"s": 2056,
"text": "Step 1: Creating the main()"
},
{
"code": null,
"e": 2279,
"s": 2084,
"text": "We create a main() function that takes in the required arguments (server_ip, start_port, end_port). The server IP must be IPv4, though we can extend it to accept IPv6 as well. Try it yourself !!"
},
{
"code": null,
"e": 2887,
"s": 2279,
"text": "int main(int argc, char *argv[])\n{\n if (argc < 4)\n {\n printf (\"Please enter the server IP address\"\n \" and range of ports to be scanned\\n\");\n printf (\"USAGE: %s IPv4 First_Port Last_Port\\n\", \n argv[0]);\n exit(1);\n }\n char tIP[16] = {0};\n strcpy(tIP, argv[1]); // Copy the IPv4 address\n char First_Port[6] = {0};\n strcpy(First_Port, argv[2]); // Copy the start_port\n char Last_Port[6] = {0};\n strcpy(Last_Port, argv[3]); // Copy the end_port\n\n // Start port-scanner\n port_scanner(tIP, First_Port, Last_Port);\n return 0;\n}\n"
},
{
"code": null,
"e": 2923,
"s": 2887,
"text": "Step 2: Creating the port_scanner()"
},
{
"code": null,
"e": 3055,
"s": 2923,
"text": "Create a new function, port_scanner(). We traverse through all the ports in range provided and then check against each one of them."
},
{
"code": null,
"e": 3126,
"s": 3055,
"text": "Create a “struct addrinfo hints” and initialize it with proper values."
},
{
"code": null,
"e": 3244,
"s": 3126,
"text": "struct addrinfo hints;\nmemset(&hints, 0, sizeof(hints));\nhints.ai_family = AF_INET;\nhints.ai_socktype = SOCK_STREAM;\n"
},
{
"code": null,
"e": 3459,
"s": 3244,
"text": "‘hints’ is an optional pointer to a struct addrinfo, as defined by . This structure can be used to provide hints concerning the type of socket that the caller supports or wishes to use. – from the FreeBSD man page."
},
{
"code": null,
"e": 3973,
"s": 3459,
"text": "Initialize a pointer for the server_address that we will obtain from the server.Now, call “getaddrinfo(tIP, tport, &hints, &serv_addr)” with proper parameters. The getaddrinfo() function allocates and initializes a linked list of addrinfo structures, one for each network address that matches node and service, subject to any restrictions imposed by hints, and returns a pointer to the start of the list in the 4th paraments, in this case “serv_addr”. The items in the linked list are linked by the ai_next field."
},
{
"code": null,
"e": 4420,
"s": 3973,
"text": "Additional Info:There are several reasons why the linked list may have more than one addrinfo structure, including: the network host is multihomed, accessible over multiple protocols (e.g., both AF_INET and AF_INET6); or the same service is available from multiple socket types (one SOCK_STREAM address and another SOCK_DGRAM address, for example).Normally, the application should try using the addresses in the order in which they are returned."
},
{
"code": null,
"e": 4459,
"s": 4420,
"text": "Step 3: Connecting against the sockets"
},
{
"code": null,
"e": 4694,
"s": 4459,
"text": "Traverse through all the addrinfo received in the linked list, and create a socket. The values for the “socket()” are present in the addrinfo struct obtained above. (Each node of the linked_list is traversed using the pointer “temp”.)"
},
{
"code": null,
"e": 4866,
"s": 4694,
"text": "sockfd = socket(temp->ai_family, temp->ai_socktype, \n temp->ai_protocol);\nif (sockfd < 0) \n{\n printf(\"Port %d is NOT open.\\n\", port);\n continue; \n}\n"
},
{
"code": null,
"e": 5229,
"s": 4866,
"text": "If the socket creation fails, then try using the values in other nodes. Once socket creation succeeds, try connecting to it using the “connect()”. If the connection is a success, then congratulations, the socket is OPEN, else try with the other addrinfo nodes. If none of them works from the linked_list, then the socket is CLOSED. Here is the code for the same,"
},
{
"code": null,
"e": 5455,
"s": 5229,
"text": "status = connect(sockfd, temp->ai_addr, \n temp->ai_addrlen);\nif (status<0) \n{\n printf(\"Port %d is NOT open.\\n\", port);\n close(sockfd);\n continue;\n}\n\nprintf(\"Port %d is open.\\n\", port);\nclose(sockfd);\n"
},
{
"code": null,
"e": 5631,
"s": 5455,
"text": "The “freeaddrinfo()” function frees the memory that was allocated for the dynamically allocated linked list “serv_addr”. It is a good practice to use this instead of “free()”."
},
{
"code": null,
"e": 5699,
"s": 5631,
"text": "The full source code for this tutorial can be downloaded from here."
},
{
"code": null,
"e": 5939,
"s": 5699,
"text": "Note: The code for this program is not long, but how the addresses are derived using getaddrinfo is very important. Almost all networking applications in c have similar first 2 steps. The 3rd step depends on the purpose of the application."
},
{
"code": null,
"e": 6095,
"s": 5939,
"text": "For more info regarding the struct returned by freeaddrinfo, read this documentation and details of the arguments of socket, go through this documentation."
},
{
"code": null,
"e": 6113,
"s": 6095,
"text": "About the Author:"
},
{
"code": null,
"e": 6255,
"s": 6113,
"text": "Pinkesh Badjatiya hails from IIIT Hyderabad. He is a geek at heart with ample projects worth looking for. His project work can be seen here. "
},
{
"code": null,
"e": 6358,
"s": 6255,
"text": "If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks."
},
{
"code": null,
"e": 6364,
"s": 6358,
"text": "GBlog"
},
{
"code": null,
"e": 6372,
"s": 6364,
"text": "Project"
},
{
"code": null,
"e": 6470,
"s": 6372,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6525,
"s": 6470,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 6562,
"s": 6525,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 6601,
"s": 6562,
"text": "How to Learn Data Science in 10 weeks?"
},
{
"code": null,
"e": 6639,
"s": 6601,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6705,
"s": 6639,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 6754,
"s": 6705,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 6809,
"s": 6754,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 6842,
"s": 6809,
"text": "Working with zip files in Python"
},
{
"code": null,
"e": 6864,
"s": 6842,
"text": "XML parsing in Python"
}
] |
Reverse a LinkedList in Java | 11 Dec, 2018
Assuming you have gone through LinkedList in java and know about linked list. This post contains different examples for reversing a linked list which are given below:
1. By writing our own function(Using additional space): reverseLinkedList() method contains logic for reversing string objects in a linked list. This method takes a linked list as a parameter, traverses all the elements in reverse order and adds it to the newly created linked list.
Algorithm:Step 1. Create a linked list with n elementsStep 2. Create an empty linked list which will be used to store reversed elementsStep 3. Start traversing the list from ‘n’ to ‘0’ and store the elements in the newly created list.Step 4. The elements will be stored in the following order: n, n-1, n-2, ......0Step 5. Return the list to the caller and print it
Example:
Step 1: LL: 1 -> 2 -> 3 -> 4 -> 5 where 'LL' is the linked list with n elements
Step 2: 'Rev' is an empty linked list
Step 3: Start traversing, the below passes are the intermediate steps while traversing
1st pass: Rev: 5
2nd pass: Rev: 5 -> 4
3rd pass: Rev: 5 -> 4 -> 3
4th pass: Rev: 5 -> 4 -> 3 -> 2
5th pass: Rev: 5 -> 4 -> 3 -> 2 -> 1
Step 4: nth element of 'LL' is stored in 0th position of 'Rev',
n-1 element of LL is stored in 1st position of Rev and so on......
Step 5: Return Rev: 5 -> 4 -> 3 -> 2 -> 1 to the calling function.
// Java program for reversing linked list using additional spaceimport java.util.*; public class LinkedListTest1 { public static void main(String[] args) { // Declaring linkedlist without any initial size LinkedList<String> linkedli = new LinkedList<String>(); // Appending elements at the end of the list linkedli.add("Cherry"); linkedli.add("Chennai"); linkedli.add("Bullet"); System.out.print("Elements before reversing: " + linkedli); linkedli = reverseLinkedList(linkedli); System.out.print("\nElements after reversing: " + linkedli); } // Takes a linkedlist as a parameter and returns a reversed linkedlist public static LinkedList<String> reverseLinkedList(LinkedList<String> llist) { LinkedList<String> revLinkedList = new LinkedList<String>(); for (int i = llist.size() - 1; i >= 0; i--) { // Append the elements in reverse order revLinkedList.add(llist.get(i)); } // Return the reversed arraylist return revLinkedList; }}
Time Complexity: O(n)Space Complexity: O(n)
NOTE: As we are using additional memory space for storing all the reversed ‘n’ elements, the space complexity is O(n).
Elements before reversing: [Cherry, Chennai, Bullet]
Elements after reversing: [Bullet, Chennai, Cherry]
2. By writing our own function(Without using additional space): In the previous example, a linked list is used additionally for storing all the reversed elements which takes more space. To avoid that, same linked list can be used for reversing.
Algorithm:1. Create a linked list with n elements1. Run the loop for n/2 times where ‘n’ is the number of elements in the linkedlist.2. In the first pass, Swap the first and nth element3. In the second pass, Swap the second and (n-1)th element and so on till you reach the mid of the linked list.4. Return the linked list after loop termination.
Example:
Input: 1 -> 2 -> 3 -> 4 -> 5
1st pass: (swap first and nth element)
5 -> 2 -> 3 -> 4 -> 1
2nd pass: (swap second and (n-1)th element)
5 -> 4 -> 3 -> 2 -> 1
3rd pass: (reached mid, Terminate loop)
5 -> 4 -> 3 -> 2 -> 1
Output: 5 -> 4 -> 3 -> 2 -> 1
// Java program for reversing an arraylist without// using any additional spaceimport java.util.*; public class LinkedListTest2 { public static void main(String[] args) { // Declaring linkedlist without any initial size LinkedList<Integer> linkedli = new LinkedList<Integer>(); // Appending elements at the end of the list linkedli.add(new Integer(1)); linkedli.add(new Integer(2)); linkedli.add(new Integer(3)); linkedli.add(new Integer(4)); linkedli.add(new Integer(5)); System.out.print("Elements before reversing: " + linkedli); // Calling user defined function for reversing linkedli = reverseLinkedList(linkedli); System.out.print("\nElements after reversing: " + linkedli); } // Takes a linkedlist as a parameter and returns a reversed linkedlist public static LinkedList<Integer> reverseLinkedList(LinkedList<Integer> llist) { for (int i = 0; i < llist.size() / 2; i++) { Integer temp = llist.get(i); llist.set(i, llist.get(llist.size() - i - 1)); llist.set(llist.size() - i - 1, temp); } // Return the reversed arraylist return llist; }}
Time Complexity: O(n/2)Space Complexity: O(1)
Elements before reversing: [1, 2, 3, 4, 5]
Elements after reversing: [5, 4, 3, 2, 1]
3. By using Collections class: Collections is a class in java.util package which contains various static methods for searching, sorting, reversing, finding max, min....etc. We can make use of the In-built Collections.reverse() method for reversing an linked list. It takes a list as an input parameter and returns the reversed list.
NOTE: Collections.reverse() method uses the same algorithm as “By writing our own function(Without using additional space)”
// Java program for reversing a linked list using// In-built collections classimport java.util.*; public class LinkedListTest3 { public static void main(String[] args) { // Declaring linkedlist without any initial size LinkedList<Integer> linkedli = new LinkedList<Integer>(); // Appending elements at the end of the list linkedli.add(new Integer(1)); linkedli.add(new Integer(2)); linkedli.add(new Integer(3)); linkedli.add(new Integer(4)); linkedli.add(new Integer(5)); System.out.print("Elements before reversing: " + linkedli); // Collections.reverse method takes a list as a // parameter and returns the reversed list Collections.reverse(linkedli); System.out.print("\nElements after reversing: " + linkedli); }}
Time Complexity: O(n/2)Space Complexity: O(1)
Elements before reversing: [1, 2, 3, 4, 5]
Elements after reversing: [5, 4, 3, 2, 1]
4.Reversing a linked list of user defined objects: An Employee class is created for creating user defined objects with employeeID, employeeName, departmentName as class variables which are initialized in the constructor. An linked list is created that takes only Employee(user defined) Objects. These objects are added to the linked list using add() method. The linked list is reversed using In-built reverse() method of Collections class.
printElements() method is used to iterate through all the user defined objects in the linked list and print the employee ID, name and department name for every object.
// Java program for reversing a inkedlist of user defined objectsimport java.util.*; class Employee { int empID; String empName; String deptName; // Constructor for initializing the class variables public Employee(int empID, String empName, String deptName) { this.empID = empID; this.empName = empName; this.deptName = deptName; }} public class LinkedListTest4 { public static void main(String[] args) { // Declaring linkedList without any initial size LinkedList<Employee> linkedli = new LinkedList<Employee>(); // Creating user defined objects Employee emp1 = new Employee(123, "Cherry", "Fashionist"); Employee emp2 = new Employee(124, "muppala", "Development"); Employee emp3 = new Employee(125, "Bullet", "Police"); // Appending all the objects to linkedList linkedli.add(emp1); linkedli.add(emp2); linkedli.add(emp3); System.out.print("Elements before reversing: "); printElements(linkedli); // Collections.reverse method takes a list as a parameter // and returns the reversed list Collections.reverse(linkedli); System.out.print("\nElements after reversing: "); printElements(linkedli); } // Iterate through all the elements and print public static void printElements(LinkedList<Employee> llist) { for (int i = 0; i < llist.size(); i++) { System.out.print("\n EmpID:" + llist.get(i).empID + ", EmpName:" + llist.get(i).empName + ", Department:" + llist.get(i).deptName); } }}
Time Complexity: O(n/2)Space Complexity: O(1)
Elements before reversing:
EmpID:123, EmpName:Cherry, Department:Fashionist
EmpID:124, EmpName:muppala, Department:Development
EmpID:125, EmpName:Bullet, Department:Police
Elements after reversing:
EmpID:125, EmpName:Bullet, Department:Police
EmpID:124, EmpName:muppala, Department:Development
EmpID:123, EmpName:Cherry, Department:Fashionist
See reverse a linked list for reversing a user defined linked list.
SujanM
Java - util package
Java-Collections
java-LinkedList
Java-List-Programs
Picked
Reverse
Java
Java
Reverse
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 219,
"s": 52,
"text": "Assuming you have gone through LinkedList in java and know about linked list. This post contains different examples for reversing a linked list which are given below:"
},
{
"code": null,
"e": 502,
"s": 219,
"text": "1. By writing our own function(Using additional space): reverseLinkedList() method contains logic for reversing string objects in a linked list. This method takes a linked list as a parameter, traverses all the elements in reverse order and adds it to the newly created linked list."
},
{
"code": null,
"e": 867,
"s": 502,
"text": "Algorithm:Step 1. Create a linked list with n elementsStep 2. Create an empty linked list which will be used to store reversed elementsStep 3. Start traversing the list from ‘n’ to ‘0’ and store the elements in the newly created list.Step 4. The elements will be stored in the following order: n, n-1, n-2, ......0Step 5. Return the list to the caller and print it"
},
{
"code": null,
"e": 1477,
"s": 867,
"text": "Example:\nStep 1: LL: 1 -> 2 -> 3 -> 4 -> 5 where 'LL' is the linked list with n elements\nStep 2: 'Rev' is an empty linked list\nStep 3: Start traversing, the below passes are the intermediate steps while traversing\n 1st pass: Rev: 5\n 2nd pass: Rev: 5 -> 4\n 3rd pass: Rev: 5 -> 4 -> 3\n 4th pass: Rev: 5 -> 4 -> 3 -> 2\n 5th pass: Rev: 5 -> 4 -> 3 -> 2 -> 1\nStep 4: nth element of 'LL' is stored in 0th position of 'Rev', \n n-1 element of LL is stored in 1st position of Rev and so on......\nStep 5: Return Rev: 5 -> 4 -> 3 -> 2 -> 1 to the calling function.\n"
},
{
"code": "// Java program for reversing linked list using additional spaceimport java.util.*; public class LinkedListTest1 { public static void main(String[] args) { // Declaring linkedlist without any initial size LinkedList<String> linkedli = new LinkedList<String>(); // Appending elements at the end of the list linkedli.add(\"Cherry\"); linkedli.add(\"Chennai\"); linkedli.add(\"Bullet\"); System.out.print(\"Elements before reversing: \" + linkedli); linkedli = reverseLinkedList(linkedli); System.out.print(\"\\nElements after reversing: \" + linkedli); } // Takes a linkedlist as a parameter and returns a reversed linkedlist public static LinkedList<String> reverseLinkedList(LinkedList<String> llist) { LinkedList<String> revLinkedList = new LinkedList<String>(); for (int i = llist.size() - 1; i >= 0; i--) { // Append the elements in reverse order revLinkedList.add(llist.get(i)); } // Return the reversed arraylist return revLinkedList; }}",
"e": 2555,
"s": 1477,
"text": null
},
{
"code": null,
"e": 2599,
"s": 2555,
"text": "Time Complexity: O(n)Space Complexity: O(n)"
},
{
"code": null,
"e": 2718,
"s": 2599,
"text": "NOTE: As we are using additional memory space for storing all the reversed ‘n’ elements, the space complexity is O(n)."
},
{
"code": null,
"e": 2824,
"s": 2718,
"text": "Elements before reversing: [Cherry, Chennai, Bullet]\nElements after reversing: [Bullet, Chennai, Cherry]\n"
},
{
"code": null,
"e": 3069,
"s": 2824,
"text": "2. By writing our own function(Without using additional space): In the previous example, a linked list is used additionally for storing all the reversed elements which takes more space. To avoid that, same linked list can be used for reversing."
},
{
"code": null,
"e": 3415,
"s": 3069,
"text": "Algorithm:1. Create a linked list with n elements1. Run the loop for n/2 times where ‘n’ is the number of elements in the linkedlist.2. In the first pass, Swap the first and nth element3. In the second pass, Swap the second and (n-1)th element and so on till you reach the mid of the linked list.4. Return the linked list after loop termination."
},
{
"code": null,
"e": 3706,
"s": 3415,
"text": "Example:\nInput: 1 -> 2 -> 3 -> 4 -> 5\n1st pass: (swap first and nth element)\n 5 -> 2 -> 3 -> 4 -> 1\n2nd pass: (swap second and (n-1)th element)\n 5 -> 4 -> 3 -> 2 -> 1\n3rd pass: (reached mid, Terminate loop)\n 5 -> 4 -> 3 -> 2 -> 1\nOutput: 5 -> 4 -> 3 -> 2 -> 1\n"
},
{
"code": "// Java program for reversing an arraylist without// using any additional spaceimport java.util.*; public class LinkedListTest2 { public static void main(String[] args) { // Declaring linkedlist without any initial size LinkedList<Integer> linkedli = new LinkedList<Integer>(); // Appending elements at the end of the list linkedli.add(new Integer(1)); linkedli.add(new Integer(2)); linkedli.add(new Integer(3)); linkedli.add(new Integer(4)); linkedli.add(new Integer(5)); System.out.print(\"Elements before reversing: \" + linkedli); // Calling user defined function for reversing linkedli = reverseLinkedList(linkedli); System.out.print(\"\\nElements after reversing: \" + linkedli); } // Takes a linkedlist as a parameter and returns a reversed linkedlist public static LinkedList<Integer> reverseLinkedList(LinkedList<Integer> llist) { for (int i = 0; i < llist.size() / 2; i++) { Integer temp = llist.get(i); llist.set(i, llist.get(llist.size() - i - 1)); llist.set(llist.size() - i - 1, temp); } // Return the reversed arraylist return llist; }}",
"e": 4928,
"s": 3706,
"text": null
},
{
"code": null,
"e": 4974,
"s": 4928,
"text": "Time Complexity: O(n/2)Space Complexity: O(1)"
},
{
"code": null,
"e": 5060,
"s": 4974,
"text": "Elements before reversing: [1, 2, 3, 4, 5]\nElements after reversing: [5, 4, 3, 2, 1]\n"
},
{
"code": null,
"e": 5393,
"s": 5060,
"text": "3. By using Collections class: Collections is a class in java.util package which contains various static methods for searching, sorting, reversing, finding max, min....etc. We can make use of the In-built Collections.reverse() method for reversing an linked list. It takes a list as an input parameter and returns the reversed list."
},
{
"code": null,
"e": 5517,
"s": 5393,
"text": "NOTE: Collections.reverse() method uses the same algorithm as “By writing our own function(Without using additional space)”"
},
{
"code": "// Java program for reversing a linked list using// In-built collections classimport java.util.*; public class LinkedListTest3 { public static void main(String[] args) { // Declaring linkedlist without any initial size LinkedList<Integer> linkedli = new LinkedList<Integer>(); // Appending elements at the end of the list linkedli.add(new Integer(1)); linkedli.add(new Integer(2)); linkedli.add(new Integer(3)); linkedli.add(new Integer(4)); linkedli.add(new Integer(5)); System.out.print(\"Elements before reversing: \" + linkedli); // Collections.reverse method takes a list as a // parameter and returns the reversed list Collections.reverse(linkedli); System.out.print(\"\\nElements after reversing: \" + linkedli); }}",
"e": 6342,
"s": 5517,
"text": null
},
{
"code": null,
"e": 6388,
"s": 6342,
"text": "Time Complexity: O(n/2)Space Complexity: O(1)"
},
{
"code": null,
"e": 6474,
"s": 6388,
"text": "Elements before reversing: [1, 2, 3, 4, 5]\nElements after reversing: [5, 4, 3, 2, 1]\n"
},
{
"code": null,
"e": 6914,
"s": 6474,
"text": "4.Reversing a linked list of user defined objects: An Employee class is created for creating user defined objects with employeeID, employeeName, departmentName as class variables which are initialized in the constructor. An linked list is created that takes only Employee(user defined) Objects. These objects are added to the linked list using add() method. The linked list is reversed using In-built reverse() method of Collections class."
},
{
"code": null,
"e": 7082,
"s": 6914,
"text": "printElements() method is used to iterate through all the user defined objects in the linked list and print the employee ID, name and department name for every object."
},
{
"code": "// Java program for reversing a inkedlist of user defined objectsimport java.util.*; class Employee { int empID; String empName; String deptName; // Constructor for initializing the class variables public Employee(int empID, String empName, String deptName) { this.empID = empID; this.empName = empName; this.deptName = deptName; }} public class LinkedListTest4 { public static void main(String[] args) { // Declaring linkedList without any initial size LinkedList<Employee> linkedli = new LinkedList<Employee>(); // Creating user defined objects Employee emp1 = new Employee(123, \"Cherry\", \"Fashionist\"); Employee emp2 = new Employee(124, \"muppala\", \"Development\"); Employee emp3 = new Employee(125, \"Bullet\", \"Police\"); // Appending all the objects to linkedList linkedli.add(emp1); linkedli.add(emp2); linkedli.add(emp3); System.out.print(\"Elements before reversing: \"); printElements(linkedli); // Collections.reverse method takes a list as a parameter // and returns the reversed list Collections.reverse(linkedli); System.out.print(\"\\nElements after reversing: \"); printElements(linkedli); } // Iterate through all the elements and print public static void printElements(LinkedList<Employee> llist) { for (int i = 0; i < llist.size(); i++) { System.out.print(\"\\n EmpID:\" + llist.get(i).empID + \", EmpName:\" + llist.get(i).empName + \", Department:\" + llist.get(i).deptName); } }}",
"e": 8716,
"s": 7082,
"text": null
},
{
"code": null,
"e": 8762,
"s": 8716,
"text": "Time Complexity: O(n/2)Space Complexity: O(1)"
},
{
"code": null,
"e": 9114,
"s": 8762,
"text": "Elements before reversing: \n EmpID:123, EmpName:Cherry, Department:Fashionist\n EmpID:124, EmpName:muppala, Department:Development\n EmpID:125, EmpName:Bullet, Department:Police\nElements after reversing: \n EmpID:125, EmpName:Bullet, Department:Police\n EmpID:124, EmpName:muppala, Department:Development\n EmpID:123, EmpName:Cherry, Department:Fashionist\n"
},
{
"code": null,
"e": 9182,
"s": 9114,
"text": "See reverse a linked list for reversing a user defined linked list."
},
{
"code": null,
"e": 9189,
"s": 9182,
"text": "SujanM"
},
{
"code": null,
"e": 9209,
"s": 9189,
"text": "Java - util package"
},
{
"code": null,
"e": 9226,
"s": 9209,
"text": "Java-Collections"
},
{
"code": null,
"e": 9242,
"s": 9226,
"text": "java-LinkedList"
},
{
"code": null,
"e": 9261,
"s": 9242,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 9268,
"s": 9261,
"text": "Picked"
},
{
"code": null,
"e": 9276,
"s": 9268,
"text": "Reverse"
},
{
"code": null,
"e": 9281,
"s": 9276,
"text": "Java"
},
{
"code": null,
"e": 9286,
"s": 9281,
"text": "Java"
},
{
"code": null,
"e": 9294,
"s": 9286,
"text": "Reverse"
},
{
"code": null,
"e": 9311,
"s": 9294,
"text": "Java-Collections"
},
{
"code": null,
"e": 9409,
"s": 9311,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9424,
"s": 9409,
"text": "Stream In Java"
},
{
"code": null,
"e": 9445,
"s": 9424,
"text": "Introduction to Java"
},
{
"code": null,
"e": 9466,
"s": 9445,
"text": "Constructors in Java"
},
{
"code": null,
"e": 9485,
"s": 9466,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 9502,
"s": 9485,
"text": "Generics in Java"
},
{
"code": null,
"e": 9532,
"s": 9502,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 9548,
"s": 9532,
"text": "Strings in Java"
},
{
"code": null,
"e": 9574,
"s": 9548,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 9594,
"s": 9574,
"text": "Abstraction in Java"
}
] |
Bokeh – Multiple Plots | 08 Feb, 2022
Prerequisites: Introduction to Bokeh in Python
In this article, we will discuss how to plot multiple plots using Bokeh in Python. We are going to use the row() method of the bokeh.layouts module, it is used in show() method of bokeh.io library as an argument to depict multiple plots in using bokeh.
Syntax:
show(row(fig1,fig2,fig3.....fign))
In which fig1, fig2, etc are objects of the class figure in bokeh.plotting module.
Import required modules
Assign coordinates and depict plots using figure class.
Use the figure objects as arguments in the row() method.
Use the show() method to depict the visualization returned from the row()method.
Example 1:
Different plots in the same page
Python3
# import modulesfrom bokeh.io import output_file, showfrom bokeh.layouts import rowfrom bokeh.plotting import figure # create a new plotfig1 = figure(plot_width=500, plot_height=500)fig1.line([1, 2, 3, 4, 5], [3, 1, 2, 6, 5], line_width=5) # create another plotx = y = list(range(10))fig2 = figure(plot_width=500, plot_height=500)fig2.circle(x, y, size=5) # depict visualizationshow(row(fig1, fig2))
Output:
Example 2:
Different plots on the same frame
Python3
# import modulesfrom bokeh.io import output_file, showfrom bokeh.layouts import rowfrom bokeh.plotting import figureimport numpy as npimport random # create a new plot# instantiating the figure objectfig1 = figure(title="Plot 1") # coordinatesx = [[[[0, 0, 1, 1]]], [[[2, 2, 4, 4], [2.5, 2.5, 3.5, 3.5]]], [[[2, 0, 4]]]]y = [[[[2.5, 0.5, 0.5, 2.5]]], [[[1, 0, 0, 1], [0.75, 0.25, 0.25, 0.75]]], [[[2, 0, 0]]]] # color values of the polygonscolor = ["red", "purple", "yellow"] # fill alpha values of the polygonsfill_alpha = 0.5 # plotting the graphfig1.multi_polygons(x, y, color=color, fill_alpha=fill_alpha) # create another plot# coordinatesx = np.arange(5)y = x**2z = x*3p = np.linspace(1, 20, 7)q = np.linspace(1, 10, 7)r = np.linspace(1, 30, 5)a = np.arange(31) # creating an empty figure with specific plot# width and heightfig2 = figure(title="Plot 2") # plotting the points in the form of# circular glyphsfig2.circle(x, y, color="red", size=20) # plotting the points in the form of# square glyphsfig2.square(x, z, color="blue", size=15, alpha=0.5) # plotting the points in the form of# hex glyphsfig2.hex(y, z, color="green", size=10, alpha=0.7) # drawing a line between the plotted pointsfig2.line(x, y, color="green", line_width=4) # plotting the points in the form of# inverted triangle glyphfig2.inverted_triangle(p, q, color="yellow", size=20, alpha=0.4) # plotting the points in the form of# diamond glyphsfig2.diamond(x, r, color="purple", size=16, alpha=0.8) # plotting the points in the form of# cross glyphsfig2.cross(a, a, size=14) # create a third plot# generating the points to be plottedx = []y = []for i in range(100): x.append(i)for i in range(100): y.append(1 + random.random()) # parameters of line 1line_color = "red"line_dash = "solid"legend_label = "Line 1" fig3 = figure(title="Plot 3") # plotting the linefig3.line(x, y, line_color=line_color, line_dash=line_dash, legend_label=legend_label) # plotting line 2# generating the points to be plottedx = []y = []for i in range(100): x.append(i)for i in range(100): y.append(random.random()) # parameters of line 2line_color = "green"line_dash = "dotdash"line_dash_offset = 1legend_label = "Line 2" # plotting the linefig3.line(x, y, line_color=line_color, line_dash=line_dash, line_dash_offset=line_dash_offset, legend_label=legend_label) # depict visualizationshow(row(fig1, fig2, fig3))
Output:
Example 3:
Multiple plots in a row
Python3
# import modulesfrom bokeh.io import output_file, showfrom bokeh.layouts import rowfrom bokeh.plotting import figure # assign coordinatesx = y = list(range(10))xs = [[[[0, 0, 1, 1]]]]ys = [[[[3, 2, 2, 3]]]] # create a new plotfig1 = figure(title="Plot 1", plot_width=250, plot_height=250)fig1.line(x, y, line_width=25, color="lime") # create another plotfig2 = figure(title="Plot 2", plot_width=250, plot_height=250)fig2.circle(x, y, size=25, color="lime") # create another plotfig3 = figure(title="Plot 3", plot_width=250, plot_height=250)fig3.square(x, y, size=25, color="lime") # create another plotfig4 = figure(title="Plot 4", plot_width=250, plot_height=250)fig4.triangle(x, y, size=25, color="lime") # create another plotfig5 = figure(title="Plot 5", plot_width=250, plot_height=250)fig5.multi_polygons(xs, ys, color="lime") # create another plotfig6 = figure(title="Plot 6", plot_width=250, plot_height=250)fig6.line(x, y, line_dash="dotted", color="lime") # depict visualizationshow(row(fig1, fig2, fig3, fig4, fig5, fig6))
Output:
simranarora5sos
sumitgumber28
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 76,
"s": 28,
"text": "Prerequisites: Introduction to Bokeh in Python "
},
{
"code": null,
"e": 330,
"s": 76,
"text": "In this article, we will discuss how to plot multiple plots using Bokeh in Python. We are going to use the row() method of the bokeh.layouts module, it is used in show() method of bokeh.io library as an argument to depict multiple plots in using bokeh. "
},
{
"code": null,
"e": 338,
"s": 330,
"text": "Syntax:"
},
{
"code": null,
"e": 374,
"s": 338,
"text": "show(row(fig1,fig2,fig3.....fign)) "
},
{
"code": null,
"e": 457,
"s": 374,
"text": "In which fig1, fig2, etc are objects of the class figure in bokeh.plotting module."
},
{
"code": null,
"e": 481,
"s": 457,
"text": "Import required modules"
},
{
"code": null,
"e": 537,
"s": 481,
"text": "Assign coordinates and depict plots using figure class."
},
{
"code": null,
"e": 594,
"s": 537,
"text": "Use the figure objects as arguments in the row() method."
},
{
"code": null,
"e": 675,
"s": 594,
"text": "Use the show() method to depict the visualization returned from the row()method."
},
{
"code": null,
"e": 686,
"s": 675,
"text": "Example 1:"
},
{
"code": null,
"e": 719,
"s": 686,
"text": "Different plots in the same page"
},
{
"code": null,
"e": 727,
"s": 719,
"text": "Python3"
},
{
"code": "# import modulesfrom bokeh.io import output_file, showfrom bokeh.layouts import rowfrom bokeh.plotting import figure # create a new plotfig1 = figure(plot_width=500, plot_height=500)fig1.line([1, 2, 3, 4, 5], [3, 1, 2, 6, 5], line_width=5) # create another plotx = y = list(range(10))fig2 = figure(plot_width=500, plot_height=500)fig2.circle(x, y, size=5) # depict visualizationshow(row(fig1, fig2))",
"e": 1171,
"s": 727,
"text": null
},
{
"code": null,
"e": 1179,
"s": 1171,
"text": "Output:"
},
{
"code": null,
"e": 1190,
"s": 1179,
"text": "Example 2:"
},
{
"code": null,
"e": 1224,
"s": 1190,
"text": "Different plots on the same frame"
},
{
"code": null,
"e": 1232,
"s": 1224,
"text": "Python3"
},
{
"code": "# import modulesfrom bokeh.io import output_file, showfrom bokeh.layouts import rowfrom bokeh.plotting import figureimport numpy as npimport random # create a new plot# instantiating the figure objectfig1 = figure(title=\"Plot 1\") # coordinatesx = [[[[0, 0, 1, 1]]], [[[2, 2, 4, 4], [2.5, 2.5, 3.5, 3.5]]], [[[2, 0, 4]]]]y = [[[[2.5, 0.5, 0.5, 2.5]]], [[[1, 0, 0, 1], [0.75, 0.25, 0.25, 0.75]]], [[[2, 0, 0]]]] # color values of the polygonscolor = [\"red\", \"purple\", \"yellow\"] # fill alpha values of the polygonsfill_alpha = 0.5 # plotting the graphfig1.multi_polygons(x, y, color=color, fill_alpha=fill_alpha) # create another plot# coordinatesx = np.arange(5)y = x**2z = x*3p = np.linspace(1, 20, 7)q = np.linspace(1, 10, 7)r = np.linspace(1, 30, 5)a = np.arange(31) # creating an empty figure with specific plot# width and heightfig2 = figure(title=\"Plot 2\") # plotting the points in the form of# circular glyphsfig2.circle(x, y, color=\"red\", size=20) # plotting the points in the form of# square glyphsfig2.square(x, z, color=\"blue\", size=15, alpha=0.5) # plotting the points in the form of# hex glyphsfig2.hex(y, z, color=\"green\", size=10, alpha=0.7) # drawing a line between the plotted pointsfig2.line(x, y, color=\"green\", line_width=4) # plotting the points in the form of# inverted triangle glyphfig2.inverted_triangle(p, q, color=\"yellow\", size=20, alpha=0.4) # plotting the points in the form of# diamond glyphsfig2.diamond(x, r, color=\"purple\", size=16, alpha=0.8) # plotting the points in the form of# cross glyphsfig2.cross(a, a, size=14) # create a third plot# generating the points to be plottedx = []y = []for i in range(100): x.append(i)for i in range(100): y.append(1 + random.random()) # parameters of line 1line_color = \"red\"line_dash = \"solid\"legend_label = \"Line 1\" fig3 = figure(title=\"Plot 3\") # plotting the linefig3.line(x, y, line_color=line_color, line_dash=line_dash, legend_label=legend_label) # plotting line 2# generating the points to be plottedx = []y = []for i in range(100): x.append(i)for i in range(100): y.append(random.random()) # parameters of line 2line_color = \"green\"line_dash = \"dotdash\"line_dash_offset = 1legend_label = \"Line 2\" # plotting the linefig3.line(x, y, line_color=line_color, line_dash=line_dash, line_dash_offset=line_dash_offset, legend_label=legend_label) # depict visualizationshow(row(fig1, fig2, fig3))",
"e": 3731,
"s": 1232,
"text": null
},
{
"code": null,
"e": 3739,
"s": 3731,
"text": "Output:"
},
{
"code": null,
"e": 3751,
"s": 3739,
"text": "Example 3: "
},
{
"code": null,
"e": 3775,
"s": 3751,
"text": "Multiple plots in a row"
},
{
"code": null,
"e": 3783,
"s": 3775,
"text": "Python3"
},
{
"code": "# import modulesfrom bokeh.io import output_file, showfrom bokeh.layouts import rowfrom bokeh.plotting import figure # assign coordinatesx = y = list(range(10))xs = [[[[0, 0, 1, 1]]]]ys = [[[[3, 2, 2, 3]]]] # create a new plotfig1 = figure(title=\"Plot 1\", plot_width=250, plot_height=250)fig1.line(x, y, line_width=25, color=\"lime\") # create another plotfig2 = figure(title=\"Plot 2\", plot_width=250, plot_height=250)fig2.circle(x, y, size=25, color=\"lime\") # create another plotfig3 = figure(title=\"Plot 3\", plot_width=250, plot_height=250)fig3.square(x, y, size=25, color=\"lime\") # create another plotfig4 = figure(title=\"Plot 4\", plot_width=250, plot_height=250)fig4.triangle(x, y, size=25, color=\"lime\") # create another plotfig5 = figure(title=\"Plot 5\", plot_width=250, plot_height=250)fig5.multi_polygons(xs, ys, color=\"lime\") # create another plotfig6 = figure(title=\"Plot 6\", plot_width=250, plot_height=250)fig6.line(x, y, line_dash=\"dotted\", color=\"lime\") # depict visualizationshow(row(fig1, fig2, fig3, fig4, fig5, fig6))",
"e": 4910,
"s": 3783,
"text": null
},
{
"code": null,
"e": 4918,
"s": 4910,
"text": "Output:"
},
{
"code": null,
"e": 4934,
"s": 4918,
"text": "simranarora5sos"
},
{
"code": null,
"e": 4948,
"s": 4934,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4961,
"s": 4948,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 4968,
"s": 4961,
"text": "Python"
},
{
"code": null,
"e": 5066,
"s": 4968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5094,
"s": 5066,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5116,
"s": 5094,
"text": "Python map() function"
},
{
"code": null,
"e": 5166,
"s": 5116,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5184,
"s": 5166,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5228,
"s": 5184,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 5270,
"s": 5228,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5293,
"s": 5270,
"text": "Taking input in Python"
},
{
"code": null,
"e": 5315,
"s": 5293,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5350,
"s": 5315,
"text": "Read a file line by line in Python"
}
] |
Count possible binary strings of length N without P consecutive 0s and Q consecutive 1s | 21 Jun, 2021
Given three integers N, P, and Q, the task is to count all possible distinct binary strings of length N such that each binary string does not contain P times consecutive 0’s and Q times consecutive 1’s.
Examples:
Input: N = 5, P = 2, Q = 3Output: 7Explanation: Binary strings that satisfy the given conditions are { “01010”, “01011”, “01101”, “10101”, “10110”, “11010”, “11011”}. Therefore, the required output is 7.
Input: N = 5, P = 3, Q = 4Output: 21
Naive Approach: The problem can be solved using Recursion. Following are the recurrence relations and their base cases :
At each possible index of a Binary String, either place the value ‘0‘ or place the value ‘1‘
Therefore, cntBinStr(str, N, P, Q) = cntBinStr(str + ‘0’, N, P, Q) + cntBinStr(str + ‘1’, N, P, Q)where cntBinStr(str, N, P, Q) stores the count of distinct binary strings which does not contain P consecutive 1s and Q consecutive 0s.
Base Case: If length(str) == N, check if str satisfy the given condition or not. If found to be true, return 1. Otherwise, return 0.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if a// string satisfy the given// condition or notbool checkStr(string str, int P, int Q){ // Stores the length // of string int N = str.size(); // Stores the previous // character of the string char prev = str[0]; // Stores the count of // consecutive equal characters int cnt = 0; // Traverse the string for (int i = 0; i < N; i++) { // If current character // is equal to the // previous character if (str[i] == prev) { cnt++; } else { // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } // Reset value of cnt cnt = 1; } prev = str[i]; } // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } return true;} // Function to count all distinct// binary strings that satisfy// the given conditionint cntBinStr(string str, int N, int P, int Q){ // Stores the length of str int len = str.size(); // If length of str is N if (len == N) { // If str satisfy // the given condition if (checkStr(str, P, Q)) return 1; // If str does not satisfy // the given condition return 0; } // Append a character '0' at // end of str int X = cntBinStr(str + '0', N, P, Q); // Append a character '1' at // end of str int Y = cntBinStr(str + '1', N, P, Q); // Return total count // of binary strings return X + Y;} // Driver Codeint main(){ int N = 5, P = 2, Q = 3; cout << cntBinStr("", N, P, Q); return 0;}
// Java program to implement// the above approach class GFG{ // Function to check if a// string satisfy the given// condition or notstatic boolean checkStr(String str, int P, int Q){ // Stores the length // of string int N = str.length(); // Stores the previous // character of the string char prev = str.charAt(0); // Stores the count of // consecutive equal characters int cnt = 0; // Traverse the string for(int i = 0; i < N; i++) { // If current character // is equal to the // previous character if (str.charAt(i) == prev) { cnt++; } else { // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } // Reset value of cnt cnt = 1; } prev = str.charAt(i); } // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } return true;} // Function to count all distinct// binary strings that satisfy// the given conditionstatic int cntBinStr(String str, int N, int P, int Q){ // Stores the length of str int len = str.length(); // If length of str is N if (len == N) { // If str satisfy // the given condition if (checkStr(str, P, Q)) return 1; // If str does not satisfy // the given condition return 0; } // Append a character '0' at // end of str int X = cntBinStr(str + '0', N, P, Q); // Append a character '1' at // end of str int Y = cntBinStr(str + '1', N, P, Q); // Return total count // of binary strings return X + Y;} // Driver Codepublic static void main (String[] args){ int N = 5, P = 2, Q = 3; System.out.println(cntBinStr("", N, P, Q));}} // This code is contributed by code_hunt
# Python3 program to implement# the above approach # Function to check if a# satisfy the given# condition or notdef checkStr(str, P, Q): # Stores the length # of string N = len(str) # Stores the previous # character of the string prev = str[0] # Stores the count of # consecutive equal # characters cnt = 0 # Traverse the string for i in range(N): # If current character # is equal to the # previous character if (str[i] == prev): cnt += 1 else: # If count of consecutive # 1s is more than Q if (prev == '1' and cnt >= Q): return False # If count of consecutive # 0s is more than P if (prev == '0' and cnt >= P): return False # Reset value of cnt cnt = 1 prev = str[i] # If count of consecutive # 1s is more than Q if (prev == '1'and cnt >= Q): return False # If count of consecutive # 0s is more than P if (prev == '0' and cnt >= P): return False return True # Function to count all# distinct binary strings# that satisfy the given# conditiondef cntBinStr(str, N, P, Q): # Stores the length # of str lenn = len(str) # If length of str # is N if (lenn == N): # If str satisfy # the given condition if (checkStr(str, P, Q)): return 1 # If str does not satisfy # the given condition return 0 # Append a character '0' # at end of str X = cntBinStr(str + '0', N, P, Q) # Append a character # '1' at end of str Y = cntBinStr(str + '1', N, P, Q) # Return total count # of binary strings return X + Y # Driver Codeif __name__ == '__main__': N = 5 P = 2 Q = 3 print(cntBinStr("", N, P, Q)) # This code is contributed by mohit kumar 29
// C# program to implement// the above approach using System; class GFG{ // Function to check if a// string satisfy the given// condition or notstatic bool checkStr(string str, int P, int Q){ // Stores the length // of string int N = str.Length; // Stores the previous // character of the string char prev = str[0]; // Stores the count of // consecutive equal characters int cnt = 0; // Traverse the string for(int i = 0; i < N; i++) { // If current character // is equal to the // previous character if (str[i] == prev) { cnt++; } else { // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } // Reset value of cnt cnt = 1; } prev = str[i]; } // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } return true;} // Function to count all distinct// binary strings that satisfy// the given conditionstatic int cntBinStr(string str, int N, int P, int Q){ // Stores the length of str int len = str.Length; // If length of str is N if (len == N) { // If str satisfy // the given condition if (checkStr(str, P, Q)) return 1; // If str does not satisfy // the given condition return 0; } // Append a character '0' at // end of str int X = cntBinStr(str + '0', N, P, Q); // Append a character '1' at // end of str int Y = cntBinStr(str + '1', N, P, Q); // Return total count // of binary strings return X + Y;} // Driver Codepublic static void Main (){ int N = 5, P = 2, Q = 3; Console.WriteLine(cntBinStr("", N, P, Q));}} // This code is contributed by sanjoy_62
<script> // Javascript program to implement// the above approach // Function to check if a// string satisfy the given// condition or notfunction checkStr(str, P, Q){ // Stores the length // of string let N = str.length; // Stores the previous // character of the string let prev = str[0]; // Stores the count of // consecutive equal characters let cnt = 0; // Traverse the string for(let i = 0; i < N; i++) { // If current character // is equal to the // previous character if (str[i] == prev) { cnt++; } else { // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } // Reset value of cnt cnt = 1; } prev = str[i]; } // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } return true;} // Function to count all distinct// binary strings that satisfy// the given conditionfunction cntBinStr(str, N, P, Q){ // Stores the length of str let len = str.length; // If length of str is N if (len == N) { // If str satisfy // the given condition if (checkStr(str, P, Q)) return 1; // If str does not satisfy // the given condition return 0; } // Append a character '0' at // end of str let X = cntBinStr(str + '0', N, P, Q); // Append a character '1' at // end of str let Y = cntBinStr(str + '1', N, P, Q); // Return total count // of binary strings return X + Y;} // Driver Code let N = 5, P = 2, Q = 3; document.write(cntBinStr("", N, P, Q)); </script>
7
Time Complexity: O(2N)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach the idea is to use Dynamic Programming. Follow the steps below to solve the problem:
Initialize two 2D arrays, say zero[N][P] and one[N][Q].
zero[i][j] stores the count of binary strings of length i having j consecutive 0’s. Fill all the value of zero[i][j] in bottom-up manner.
Insert 0 at the ith index. Case 1: If (i – 1)th index of string contains 1.
Case 2: If (i – 1)th index of string contains 0.
for all r in the range [2, P – 1].
one[i][j] stores the count of binary strings of length i having j consecutive 1’s. Fill all the value of zero[i][j] in bottom-up manner.
Insert 1 at the ith index. Case 1: If (i-1)th index of string contains 0.
Case 2: If (i-1)th index of string contains 1.
for all j in the range [2, Q – 1].
Finally, print count of subarrays that satisfy the given condition.
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to count binary strings// that satisfy the given conditionint cntBinStr(int N, int P, int Q){ // zero[i][j] stores count // of binary strings of length i // having j consecutive 0s int zero[N + 1][P]; // one[i][j] stores count // of binary strings of length i // having j consecutive 1s int one[N + 1][Q]; // Set all values of // zero[][] array to 0 memset(zero, 0, sizeof(zero)); // Set all values of // one[i][j] array to 0 memset(one, 0, sizeof(one)); // Base case zero[1][1] = one[1][1] = 1; // Fill all the values of zero[i][j] // and one[i][j] in bottom up manner for (int i = 2; i <= N; i++) { for (int j = 2; j < P; j++) { zero[i][j] = zero[i - 1][j - 1]; } for (int j = 1; j < Q; j++) { zero[i][1] = zero[i][1] + one[i - 1][j]; } for (int j = 2; j < Q; j++) { one[i][j] = one[i - 1][j - 1]; } for (int j = 1; j < P; j++) { one[i][1] = one[i][1] + zero[i - 1][j]; } } // Stores count of binary strings // that satisfy the given condition int res = 0; // Count binary strings of // length N having less than // P consecutive 0s for (int i = 1; i < P; i++) { res = res + zero[N][i]; } // Count binary strings of // length N having less than // Q consecutive 1s for (int i = 1; i < Q; i++) { res = res + one[N][i]; } return res;} // Driver Codeint main(){ int N = 5, P = 2, Q = 3; cout << cntBinStr(N, P, Q); return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to count binary Strings// that satisfy the given conditionstatic int cntBinStr(int N, int P, int Q){ // zero[i][j] stores count // of binary Strings of length i // having j consecutive 0s int [][]zero = new int[N + 1][P]; // one[i][j] stores count // of binary Strings of length i // having j consecutive 1s int [][]one = new int[N + 1][Q]; // Base case zero[1][1] = one[1][1] = 1; // Fill all the values of zero[i][j] // and one[i][j] in bottom up manner for(int i = 2; i <= N; i++) { for(int j = 2; j < P; j++) { zero[i][j] = zero[i - 1][j - 1]; } for(int j = 1; j < Q; j++) { zero[i][1] = zero[i][1] + one[i - 1][j]; } for(int j = 2; j < Q; j++) { one[i][j] = one[i - 1][j - 1]; } for(int j = 1; j < P; j++) { one[i][1] = one[i][1] + zero[i - 1][j]; } } // Stores count of binary Strings // that satisfy the given condition int res = 0; // Count binary Strings of // length N having less than // P consecutive 0s for(int i = 1; i < P; i++) { res = res + zero[N][i]; } // Count binary Strings of // length N having less than // Q consecutive 1s for(int i = 1; i < Q; i++) { res = res + one[N][i]; } return res;} // Driver Codepublic static void main(String[] args){ int N = 5, P = 2, Q = 3; System.out.print(cntBinStr(N, P, Q));}} // This code is contributed by Amit Katiyar
# Python3 program to implement# the above approach # Function to count binary# Strings that satisfy the# given conditiondef cntBinStr(N, P, Q): # zero[i][j] stores count # of binary Strings of length i # having j consecutive 0s zero = [[0 for i in range(P)] for j in range(N + 1)]; # one[i][j] stores count # of binary Strings of length i # having j consecutive 1s one = [[0 for i in range(Q)] for j in range(N + 1)]; # Base case zero[1][1] = one[1][1] = 1; # Fill all the values of # zero[i][j] and one[i][j] # in bottom up manner for i in range(2, N + 1): for j in range(2, P): zero[i][j] = zero[i - 1][j - 1]; for j in range(1, Q): zero[i][1] = (zero[i][1] + one[i - 1][j]); for j in range(2, Q): one[i][j] = one[i - 1][j - 1]; for j in range(1, P): one[i][1] = one[i][1] + zero[i - 1][j]; # Stores count of binary # Strings that satisfy # the given condition res = 0; # Count binary Strings of # length N having less than # P consecutive 0s for i in range(1, P): res = res + zero[N][i]; # Count binary Strings of # length N having less than # Q consecutive 1s for i in range(1, Q): res = res + one[N][i]; return res; # Driver Codeif __name__ == '__main__': N = 5; P = 2; Q = 3; print(cntBinStr(N, P, Q)); # This code is contributed by gauravrajput1
// C# program to implement// the above approachusing System; class GFG{ // Function to count binary Strings// that satisfy the given conditionstatic int cntBinStr(int N, int P, int Q){ // zero[i,j] stores count // of binary Strings of length i // having j consecutive 0s int [,]zero = new int[N + 1, P]; // one[i,j] stores count // of binary Strings of length i // having j consecutive 1s int [,]one = new int[N + 1, Q]; // Base case zero[1, 1] = one[1, 1] = 1; // Fill all the values of zero[i,j] // and one[i,j] in bottom up manner for(int i = 2; i <= N; i++) { for(int j = 2; j < P; j++) { zero[i, j] = zero[i - 1, j - 1]; } for(int j = 1; j < Q; j++) { zero[i, 1] = zero[i, 1] + one[i - 1, j]; } for(int j = 2; j < Q; j++) { one[i, j] = one[i - 1, j - 1]; } for(int j = 1; j < P; j++) { one[i, 1] = one[i, 1] + zero[i - 1, j]; } } // Stores count of binary Strings // that satisfy the given condition int res = 0; // Count binary Strings of // length N having less than // P consecutive 0s for(int i = 1; i < P; i++) { res = res + zero[N, i]; } // Count binary Strings of // length N having less than // Q consecutive 1s for(int i = 1; i < Q; i++) { res = res + one[N, i]; } return res;} // Driver Codepublic static void Main(String[] args){ int N = 5, P = 2, Q = 3; Console.Write(cntBinStr(N, P, Q));}} // This code is contributed by gauravrajput1
<script> // JavaScript program to implement// the above approach // Function to count binary strings// that satisfy the given conditionfunction cntBinStr(N, P, Q){ // zero[i][j] stores count // of binary strings of length i // having j consecutive 0s //and // Set all values of // zero[][] array to 0 var zero = new Array(N+1).fill(0). map(item=>(new Array(P).fill(0))); // one[i][j] stores count // of binary strings of length i // having j consecutive 1s //and // Set all values of // one[i][j] array to 0 var one = new Array(N+1).fill(0). map(item=>(new Array(Q).fill(0)));; // Base case zero[1][1] = one[1][1] = 1; // Fill all the values of zero[i][j] // and one[i][j] in bottom up manner for (var i = 2; i <= N; i++) { for (var j = 2; j < P; j++) { zero[i][j] = zero[i - 1][j - 1]; } for (var j = 1; j < Q; j++) { zero[i][1] = zero[i][1] + one[i - 1][j]; } for (var j = 2; j < Q; j++) { one[i][j] = one[i - 1][j - 1]; } for (var j = 1; j < P; j++) { one[i][1] = one[i][1] + zero[i - 1][j]; } } // Stores count of binary strings // that satisfy the given condition var res = 0; // Count binary strings of // length N having less than // P consecutive 0s for (var i = 1; i < P; i++) { res = res + zero[N][i]; } // Count binary strings of // length N having less than // Q consecutive 1s for (var i = 1; i < Q; i++) { res = res + one[N][i]; } return res;} var N = 5, P = 2, Q = 3; document.write( cntBinStr(N, P, Q)); // This code in contributed by SoumikMondal </script>
7
Time complexity: O(N * (P + Q))Auxiliary Space: O(N * (P + Q))
mohit kumar 29
sanjoy_62
code_hunt
amit143katiyar
GauravRajput1
avijitmondal1998
simmytarika5
SoumikMondal
binary-string
permutation
Combinatorial
Dynamic Programming
Mathematical
Recursion
Strings
Strings
Dynamic Programming
Mathematical
Recursion
permutation
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 255,
"s": 52,
"text": "Given three integers N, P, and Q, the task is to count all possible distinct binary strings of length N such that each binary string does not contain P times consecutive 0’s and Q times consecutive 1’s."
},
{
"code": null,
"e": 265,
"s": 255,
"text": "Examples:"
},
{
"code": null,
"e": 469,
"s": 265,
"text": "Input: N = 5, P = 2, Q = 3Output: 7Explanation: Binary strings that satisfy the given conditions are { “01010”, “01011”, “01101”, “10101”, “10110”, “11010”, “11011”}. Therefore, the required output is 7."
},
{
"code": null,
"e": 506,
"s": 469,
"text": "Input: N = 5, P = 3, Q = 4Output: 21"
},
{
"code": null,
"e": 627,
"s": 506,
"text": "Naive Approach: The problem can be solved using Recursion. Following are the recurrence relations and their base cases :"
},
{
"code": null,
"e": 720,
"s": 627,
"text": "At each possible index of a Binary String, either place the value ‘0‘ or place the value ‘1‘"
},
{
"code": null,
"e": 954,
"s": 720,
"text": "Therefore, cntBinStr(str, N, P, Q) = cntBinStr(str + ‘0’, N, P, Q) + cntBinStr(str + ‘1’, N, P, Q)where cntBinStr(str, N, P, Q) stores the count of distinct binary strings which does not contain P consecutive 1s and Q consecutive 0s."
},
{
"code": null,
"e": 1087,
"s": 954,
"text": "Base Case: If length(str) == N, check if str satisfy the given condition or not. If found to be true, return 1. Otherwise, return 0."
},
{
"code": null,
"e": 1138,
"s": 1087,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1142,
"s": 1138,
"text": "C++"
},
{
"code": null,
"e": 1147,
"s": 1142,
"text": "Java"
},
{
"code": null,
"e": 1155,
"s": 1147,
"text": "Python3"
},
{
"code": null,
"e": 1158,
"s": 1155,
"text": "C#"
},
{
"code": null,
"e": 1169,
"s": 1158,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if a// string satisfy the given// condition or notbool checkStr(string str, int P, int Q){ // Stores the length // of string int N = str.size(); // Stores the previous // character of the string char prev = str[0]; // Stores the count of // consecutive equal characters int cnt = 0; // Traverse the string for (int i = 0; i < N; i++) { // If current character // is equal to the // previous character if (str[i] == prev) { cnt++; } else { // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } // Reset value of cnt cnt = 1; } prev = str[i]; } // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } return true;} // Function to count all distinct// binary strings that satisfy// the given conditionint cntBinStr(string str, int N, int P, int Q){ // Stores the length of str int len = str.size(); // If length of str is N if (len == N) { // If str satisfy // the given condition if (checkStr(str, P, Q)) return 1; // If str does not satisfy // the given condition return 0; } // Append a character '0' at // end of str int X = cntBinStr(str + '0', N, P, Q); // Append a character '1' at // end of str int Y = cntBinStr(str + '1', N, P, Q); // Return total count // of binary strings return X + Y;} // Driver Codeint main(){ int N = 5, P = 2, Q = 3; cout << cntBinStr(\"\", N, P, Q); return 0;}",
"e": 3330,
"s": 1169,
"text": null
},
{
"code": "// Java program to implement// the above approach class GFG{ // Function to check if a// string satisfy the given// condition or notstatic boolean checkStr(String str, int P, int Q){ // Stores the length // of string int N = str.length(); // Stores the previous // character of the string char prev = str.charAt(0); // Stores the count of // consecutive equal characters int cnt = 0; // Traverse the string for(int i = 0; i < N; i++) { // If current character // is equal to the // previous character if (str.charAt(i) == prev) { cnt++; } else { // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } // Reset value of cnt cnt = 1; } prev = str.charAt(i); } // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } return true;} // Function to count all distinct// binary strings that satisfy// the given conditionstatic int cntBinStr(String str, int N, int P, int Q){ // Stores the length of str int len = str.length(); // If length of str is N if (len == N) { // If str satisfy // the given condition if (checkStr(str, P, Q)) return 1; // If str does not satisfy // the given condition return 0; } // Append a character '0' at // end of str int X = cntBinStr(str + '0', N, P, Q); // Append a character '1' at // end of str int Y = cntBinStr(str + '1', N, P, Q); // Return total count // of binary strings return X + Y;} // Driver Codepublic static void main (String[] args){ int N = 5, P = 2, Q = 3; System.out.println(cntBinStr(\"\", N, P, Q));}} // This code is contributed by code_hunt",
"e": 5702,
"s": 3330,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to check if a# satisfy the given# condition or notdef checkStr(str, P, Q): # Stores the length # of string N = len(str) # Stores the previous # character of the string prev = str[0] # Stores the count of # consecutive equal # characters cnt = 0 # Traverse the string for i in range(N): # If current character # is equal to the # previous character if (str[i] == prev): cnt += 1 else: # If count of consecutive # 1s is more than Q if (prev == '1' and cnt >= Q): return False # If count of consecutive # 0s is more than P if (prev == '0' and cnt >= P): return False # Reset value of cnt cnt = 1 prev = str[i] # If count of consecutive # 1s is more than Q if (prev == '1'and cnt >= Q): return False # If count of consecutive # 0s is more than P if (prev == '0' and cnt >= P): return False return True # Function to count all# distinct binary strings# that satisfy the given# conditiondef cntBinStr(str, N, P, Q): # Stores the length # of str lenn = len(str) # If length of str # is N if (lenn == N): # If str satisfy # the given condition if (checkStr(str, P, Q)): return 1 # If str does not satisfy # the given condition return 0 # Append a character '0' # at end of str X = cntBinStr(str + '0', N, P, Q) # Append a character # '1' at end of str Y = cntBinStr(str + '1', N, P, Q) # Return total count # of binary strings return X + Y # Driver Codeif __name__ == '__main__': N = 5 P = 2 Q = 3 print(cntBinStr(\"\", N, P, Q)) # This code is contributed by mohit kumar 29",
"e": 7747,
"s": 5702,
"text": null
},
{
"code": "// C# program to implement// the above approach using System; class GFG{ // Function to check if a// string satisfy the given// condition or notstatic bool checkStr(string str, int P, int Q){ // Stores the length // of string int N = str.Length; // Stores the previous // character of the string char prev = str[0]; // Stores the count of // consecutive equal characters int cnt = 0; // Traverse the string for(int i = 0; i < N; i++) { // If current character // is equal to the // previous character if (str[i] == prev) { cnt++; } else { // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } // Reset value of cnt cnt = 1; } prev = str[i]; } // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } return true;} // Function to count all distinct// binary strings that satisfy// the given conditionstatic int cntBinStr(string str, int N, int P, int Q){ // Stores the length of str int len = str.Length; // If length of str is N if (len == N) { // If str satisfy // the given condition if (checkStr(str, P, Q)) return 1; // If str does not satisfy // the given condition return 0; } // Append a character '0' at // end of str int X = cntBinStr(str + '0', N, P, Q); // Append a character '1' at // end of str int Y = cntBinStr(str + '1', N, P, Q); // Return total count // of binary strings return X + Y;} // Driver Codepublic static void Main (){ int N = 5, P = 2, Q = 3; Console.WriteLine(cntBinStr(\"\", N, P, Q));}} // This code is contributed by sanjoy_62",
"e": 10074,
"s": 7747,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to check if a// string satisfy the given// condition or notfunction checkStr(str, P, Q){ // Stores the length // of string let N = str.length; // Stores the previous // character of the string let prev = str[0]; // Stores the count of // consecutive equal characters let cnt = 0; // Traverse the string for(let i = 0; i < N; i++) { // If current character // is equal to the // previous character if (str[i] == prev) { cnt++; } else { // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } // Reset value of cnt cnt = 1; } prev = str[i]; } // If count of consecutive // 1s is more than Q if (prev == '1' && cnt >= Q) { return false; } // If count of consecutive // 0s is more than P if (prev == '0' && cnt >= P) { return false; } return true;} // Function to count all distinct// binary strings that satisfy// the given conditionfunction cntBinStr(str, N, P, Q){ // Stores the length of str let len = str.length; // If length of str is N if (len == N) { // If str satisfy // the given condition if (checkStr(str, P, Q)) return 1; // If str does not satisfy // the given condition return 0; } // Append a character '0' at // end of str let X = cntBinStr(str + '0', N, P, Q); // Append a character '1' at // end of str let Y = cntBinStr(str + '1', N, P, Q); // Return total count // of binary strings return X + Y;} // Driver Code let N = 5, P = 2, Q = 3; document.write(cntBinStr(\"\", N, P, Q)); </script>",
"e": 12258,
"s": 10074,
"text": null
},
{
"code": null,
"e": 12260,
"s": 12258,
"text": "7"
},
{
"code": null,
"e": 12304,
"s": 12260,
"text": "Time Complexity: O(2N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12440,
"s": 12304,
"text": "Efficient Approach: To optimize the above approach the idea is to use Dynamic Programming. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 12496,
"s": 12440,
"text": "Initialize two 2D arrays, say zero[N][P] and one[N][Q]."
},
{
"code": null,
"e": 12634,
"s": 12496,
"text": "zero[i][j] stores the count of binary strings of length i having j consecutive 0’s. Fill all the value of zero[i][j] in bottom-up manner."
},
{
"code": null,
"e": 12712,
"s": 12634,
"text": "Insert 0 at the ith index. Case 1: If (i – 1)th index of string contains 1. "
},
{
"code": null,
"e": 12763,
"s": 12714,
"text": "Case 2: If (i – 1)th index of string contains 0."
},
{
"code": null,
"e": 12801,
"s": 12765,
"text": "for all r in the range [2, P – 1]. "
},
{
"code": null,
"e": 12940,
"s": 12803,
"text": "one[i][j] stores the count of binary strings of length i having j consecutive 1’s. Fill all the value of zero[i][j] in bottom-up manner."
},
{
"code": null,
"e": 13016,
"s": 12940,
"text": "Insert 1 at the ith index. Case 1: If (i-1)th index of string contains 0. "
},
{
"code": null,
"e": 13065,
"s": 13018,
"text": "Case 2: If (i-1)th index of string contains 1."
},
{
"code": null,
"e": 13103,
"s": 13067,
"text": "for all j in the range [2, Q – 1]. "
},
{
"code": null,
"e": 13173,
"s": 13105,
"text": "Finally, print count of subarrays that satisfy the given condition."
},
{
"code": null,
"e": 13177,
"s": 13173,
"text": "C++"
},
{
"code": null,
"e": 13182,
"s": 13177,
"text": "Java"
},
{
"code": null,
"e": 13190,
"s": 13182,
"text": "Python3"
},
{
"code": null,
"e": 13193,
"s": 13190,
"text": "C#"
},
{
"code": null,
"e": 13204,
"s": 13193,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to count binary strings// that satisfy the given conditionint cntBinStr(int N, int P, int Q){ // zero[i][j] stores count // of binary strings of length i // having j consecutive 0s int zero[N + 1][P]; // one[i][j] stores count // of binary strings of length i // having j consecutive 1s int one[N + 1][Q]; // Set all values of // zero[][] array to 0 memset(zero, 0, sizeof(zero)); // Set all values of // one[i][j] array to 0 memset(one, 0, sizeof(one)); // Base case zero[1][1] = one[1][1] = 1; // Fill all the values of zero[i][j] // and one[i][j] in bottom up manner for (int i = 2; i <= N; i++) { for (int j = 2; j < P; j++) { zero[i][j] = zero[i - 1][j - 1]; } for (int j = 1; j < Q; j++) { zero[i][1] = zero[i][1] + one[i - 1][j]; } for (int j = 2; j < Q; j++) { one[i][j] = one[i - 1][j - 1]; } for (int j = 1; j < P; j++) { one[i][1] = one[i][1] + zero[i - 1][j]; } } // Stores count of binary strings // that satisfy the given condition int res = 0; // Count binary strings of // length N having less than // P consecutive 0s for (int i = 1; i < P; i++) { res = res + zero[N][i]; } // Count binary strings of // length N having less than // Q consecutive 1s for (int i = 1; i < Q; i++) { res = res + one[N][i]; } return res;} // Driver Codeint main(){ int N = 5, P = 2, Q = 3; cout << cntBinStr(N, P, Q); return 0;}",
"e": 14920,
"s": 13204,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to count binary Strings// that satisfy the given conditionstatic int cntBinStr(int N, int P, int Q){ // zero[i][j] stores count // of binary Strings of length i // having j consecutive 0s int [][]zero = new int[N + 1][P]; // one[i][j] stores count // of binary Strings of length i // having j consecutive 1s int [][]one = new int[N + 1][Q]; // Base case zero[1][1] = one[1][1] = 1; // Fill all the values of zero[i][j] // and one[i][j] in bottom up manner for(int i = 2; i <= N; i++) { for(int j = 2; j < P; j++) { zero[i][j] = zero[i - 1][j - 1]; } for(int j = 1; j < Q; j++) { zero[i][1] = zero[i][1] + one[i - 1][j]; } for(int j = 2; j < Q; j++) { one[i][j] = one[i - 1][j - 1]; } for(int j = 1; j < P; j++) { one[i][1] = one[i][1] + zero[i - 1][j]; } } // Stores count of binary Strings // that satisfy the given condition int res = 0; // Count binary Strings of // length N having less than // P consecutive 0s for(int i = 1; i < P; i++) { res = res + zero[N][i]; } // Count binary Strings of // length N having less than // Q consecutive 1s for(int i = 1; i < Q; i++) { res = res + one[N][i]; } return res;} // Driver Codepublic static void main(String[] args){ int N = 5, P = 2, Q = 3; System.out.print(cntBinStr(N, P, Q));}} // This code is contributed by Amit Katiyar",
"e": 16596,
"s": 14920,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to count binary# Strings that satisfy the# given conditiondef cntBinStr(N, P, Q): # zero[i][j] stores count # of binary Strings of length i # having j consecutive 0s zero = [[0 for i in range(P)] for j in range(N + 1)]; # one[i][j] stores count # of binary Strings of length i # having j consecutive 1s one = [[0 for i in range(Q)] for j in range(N + 1)]; # Base case zero[1][1] = one[1][1] = 1; # Fill all the values of # zero[i][j] and one[i][j] # in bottom up manner for i in range(2, N + 1): for j in range(2, P): zero[i][j] = zero[i - 1][j - 1]; for j in range(1, Q): zero[i][1] = (zero[i][1] + one[i - 1][j]); for j in range(2, Q): one[i][j] = one[i - 1][j - 1]; for j in range(1, P): one[i][1] = one[i][1] + zero[i - 1][j]; # Stores count of binary # Strings that satisfy # the given condition res = 0; # Count binary Strings of # length N having less than # P consecutive 0s for i in range(1, P): res = res + zero[N][i]; # Count binary Strings of # length N having less than # Q consecutive 1s for i in range(1, Q): res = res + one[N][i]; return res; # Driver Codeif __name__ == '__main__': N = 5; P = 2; Q = 3; print(cntBinStr(N, P, Q)); # This code is contributed by gauravrajput1",
"e": 18096,
"s": 16596,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to count binary Strings// that satisfy the given conditionstatic int cntBinStr(int N, int P, int Q){ // zero[i,j] stores count // of binary Strings of length i // having j consecutive 0s int [,]zero = new int[N + 1, P]; // one[i,j] stores count // of binary Strings of length i // having j consecutive 1s int [,]one = new int[N + 1, Q]; // Base case zero[1, 1] = one[1, 1] = 1; // Fill all the values of zero[i,j] // and one[i,j] in bottom up manner for(int i = 2; i <= N; i++) { for(int j = 2; j < P; j++) { zero[i, j] = zero[i - 1, j - 1]; } for(int j = 1; j < Q; j++) { zero[i, 1] = zero[i, 1] + one[i - 1, j]; } for(int j = 2; j < Q; j++) { one[i, j] = one[i - 1, j - 1]; } for(int j = 1; j < P; j++) { one[i, 1] = one[i, 1] + zero[i - 1, j]; } } // Stores count of binary Strings // that satisfy the given condition int res = 0; // Count binary Strings of // length N having less than // P consecutive 0s for(int i = 1; i < P; i++) { res = res + zero[N, i]; } // Count binary Strings of // length N having less than // Q consecutive 1s for(int i = 1; i < Q; i++) { res = res + one[N, i]; } return res;} // Driver Codepublic static void Main(String[] args){ int N = 5, P = 2, Q = 3; Console.Write(cntBinStr(N, P, Q));}} // This code is contributed by gauravrajput1",
"e": 19756,
"s": 18096,
"text": null
},
{
"code": "<script> // JavaScript program to implement// the above approach // Function to count binary strings// that satisfy the given conditionfunction cntBinStr(N, P, Q){ // zero[i][j] stores count // of binary strings of length i // having j consecutive 0s //and // Set all values of // zero[][] array to 0 var zero = new Array(N+1).fill(0). map(item=>(new Array(P).fill(0))); // one[i][j] stores count // of binary strings of length i // having j consecutive 1s //and // Set all values of // one[i][j] array to 0 var one = new Array(N+1).fill(0). map(item=>(new Array(Q).fill(0)));; // Base case zero[1][1] = one[1][1] = 1; // Fill all the values of zero[i][j] // and one[i][j] in bottom up manner for (var i = 2; i <= N; i++) { for (var j = 2; j < P; j++) { zero[i][j] = zero[i - 1][j - 1]; } for (var j = 1; j < Q; j++) { zero[i][1] = zero[i][1] + one[i - 1][j]; } for (var j = 2; j < Q; j++) { one[i][j] = one[i - 1][j - 1]; } for (var j = 1; j < P; j++) { one[i][1] = one[i][1] + zero[i - 1][j]; } } // Stores count of binary strings // that satisfy the given condition var res = 0; // Count binary strings of // length N having less than // P consecutive 0s for (var i = 1; i < P; i++) { res = res + zero[N][i]; } // Count binary strings of // length N having less than // Q consecutive 1s for (var i = 1; i < Q; i++) { res = res + one[N][i]; } return res;} var N = 5, P = 2, Q = 3; document.write( cntBinStr(N, P, Q)); // This code in contributed by SoumikMondal </script>",
"e": 21519,
"s": 19756,
"text": null
},
{
"code": null,
"e": 21521,
"s": 21519,
"text": "7"
},
{
"code": null,
"e": 21584,
"s": 21521,
"text": "Time complexity: O(N * (P + Q))Auxiliary Space: O(N * (P + Q))"
},
{
"code": null,
"e": 21599,
"s": 21584,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 21609,
"s": 21599,
"text": "sanjoy_62"
},
{
"code": null,
"e": 21619,
"s": 21609,
"text": "code_hunt"
},
{
"code": null,
"e": 21634,
"s": 21619,
"text": "amit143katiyar"
},
{
"code": null,
"e": 21648,
"s": 21634,
"text": "GauravRajput1"
},
{
"code": null,
"e": 21665,
"s": 21648,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 21678,
"s": 21665,
"text": "simmytarika5"
},
{
"code": null,
"e": 21691,
"s": 21678,
"text": "SoumikMondal"
},
{
"code": null,
"e": 21705,
"s": 21691,
"text": "binary-string"
},
{
"code": null,
"e": 21717,
"s": 21705,
"text": "permutation"
},
{
"code": null,
"e": 21731,
"s": 21717,
"text": "Combinatorial"
},
{
"code": null,
"e": 21751,
"s": 21731,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 21764,
"s": 21751,
"text": "Mathematical"
},
{
"code": null,
"e": 21774,
"s": 21764,
"text": "Recursion"
},
{
"code": null,
"e": 21782,
"s": 21774,
"text": "Strings"
},
{
"code": null,
"e": 21790,
"s": 21782,
"text": "Strings"
},
{
"code": null,
"e": 21810,
"s": 21790,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 21823,
"s": 21810,
"text": "Mathematical"
},
{
"code": null,
"e": 21833,
"s": 21823,
"text": "Recursion"
},
{
"code": null,
"e": 21845,
"s": 21833,
"text": "permutation"
},
{
"code": null,
"e": 21859,
"s": 21845,
"text": "Combinatorial"
}
] |
Find Kth largest number in a given Binary Tree | 24 Aug, 2021
Given a Binary Tree consisting of N nodes and a positive integer K, the task is to find the Kth largest number in the given tree.Examples:
Input: K = 3 1 / \ 2 3 / \ / \ 4 5 6 7Output: 5Explanation: The third largest element in the given binary tree is 5.
Input: K = 1 1 / \ 2 3Output: 1Explanation: The first largest element in the given binary tree is 1.
Naive Approach: Flatten the given binary tree and then sort the array. Print the Kth largest number from this sorted array now.
Efficient Approach: The above approach can be made efficient by storing all the elements of the Tree in a priority queue, as the elements are stored based on the priority order, which is ascending by default. Though the complexity will remain the same as the above approach, here we can avoid the additional sorting step. Just print the Kth largest element in the priority queue.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Struct binary tree nodestruct Node { int data; Node *left, *right;}; // Function to create a new node of// the treeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Utility function to find the Kth// largest element in the given treeint findKthLargest(priority_queue<int, vector<int> >& pq, int k){ // Loop until priority queue is not // empty and K greater than 0 while (--k && !pq.empty()) { pq.pop(); } // If PQ is not empty then return // the top element if (!pq.empty()) { return pq.top(); } // Otherwise, return -1 return -1;} // Function to traverse the given// binary treevoid traverse( Node* root, priority_queue<int, vector<int> >& pq){ if (!root) { return; } // Pushing values in binary tree pq.push(root->data); // Left and Right Recursive Call traverse(root->left, pq); traverse(root->right, pq);} // Function to find the Kth largest// element in the given treevoid findKthLargestTree(Node* root, int K){ // Stores all elements tree in PQ priority_queue<int, vector<int> > pq; // Function Call traverse(root, pq); // Function Call cout << findKthLargest(pq, K);} // Driver Codeint main(){ // Given Input Node* root = newNode(1); root->left = newNode(2); root->left->left = newNode(4); root->left->right = newNode(5); root->right = newNode(3); root->right->right = newNode(7); root->right->left = newNode(6); int K = 3; findKthLargestTree(root, K); return 0;}
// Java program for the above approachimport java.util.*;public class Main{ // Struct binary tree node static class Node { int data; Node left; Node right; } // Function to create new node of the tree static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Stores all elements tree in PQ static Vector<Integer> pq = new Vector<Integer>(); // Utility function to find the Kth // largest element in the given tree static int findKthLargest(int k) { // Loop until priority queue is not // empty and K greater than 0 --k; while (k > 0 && pq.size() > 0) { pq.remove(0); --k; } // If PQ is not empty then return // the top element if (pq.size() > 0) { return pq.get(0); } // Otherwise, return -1 return -1; } // Function to traverse the given // binary tree static void traverse(Node root) { if (root == null) { return; } // Pushing values in binary tree pq.add(root.data); Collections.sort(pq); Collections.reverse(pq); // Left and Right Recursive Call traverse(root.left); traverse(root.right); } // Function to find the Kth largest // element in the given tree static void findKthLargestTree(Node root, int K) { // Function Call traverse(root); // Function Call System.out.print(findKthLargest(K)); } // Driver code public static void main(String[] args) { // Given Input Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.right = newNode(5); root.right = newNode(3); root.right.right = newNode(7); root.right.left = newNode(6); int K = 3; findKthLargestTree(root, K); }} // This code is contributed by divyesh07.
# Python3 program for the above approachclass Node: # Struct binary tree node def __init__(self, data): self.data = data self.left = None self.right = None # Stores all elements tree in PQpq = [] # Utility function to find the Kth# largest element in the given treedef findKthLargest(k): # Loop until priority queue is not # empty and K greater than 0 k-=1 while (k > 0 and len(pq) > 0): pq.pop(0) k-=1 # If PQ is not empty then return # the top element if len(pq) > 0: return pq[0] # Otherwise, return -1 return -1 # Function to traverse the given# binary treedef traverse(root): if (root == None): return # Pushing values in binary tree pq.append(root.data) pq.sort() pq.reverse() # Left and Right Recursive Call traverse(root.left) traverse(root.right) # Function to find the Kth largest# element in the given treedef findKthLargestTree(root, K): # Function Call traverse(root); # Function Call print(findKthLargest(K)) # Given Inputroot = Node(1)root.left = Node(2)root.left.left = Node(4)root.left.right = Node(5)root.right = Node(3)root.right.right = Node(7)root.right.left = Node(6)K = 3 findKthLargestTree(root, K) # This code is contributed by mukesh07.
// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Struct binary tree node class Node { public int data; public Node left, right; }; // Function to create a new node of the tree static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Stores all elements tree in PQ static List<int> pq = new List<int>(); // Utility function to find the Kth // largest element in the given tree static int findKthLargest(int k) { // Loop until priority queue is not // empty and K greater than 0 --k; while (k > 0 && pq.Count > 0) { pq.RemoveAt(0); --k; } // If PQ is not empty then return // the top element if (pq.Count > 0) { return pq[0]; } // Otherwise, return -1 return -1; } // Function to traverse the given // binary tree static void traverse(Node root) { if (root == null) { return; } // Pushing values in binary tree pq.Add(root.data); pq.Sort(); pq.Reverse(); // Left and Right Recursive Call traverse(root.left); traverse(root.right); } // Function to find the Kth largest // element in the given tree static void findKthLargestTree(Node root, int K) { // Function Call traverse(root); // Function Call Console.Write(findKthLargest(K)); } static void Main() { // Given Input Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.right = newNode(5); root.right = newNode(3); root.right.right = newNode(7); root.right.left = newNode(6); int K = 3; findKthLargestTree(root, K); }} // This code is contributed by divyeshrabadiya07.
<script> // Javascript program for the above approach // Struct binary tree node class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function to create a new node of the tree function newNode(data) { let temp = new Node(data); return temp; } // Stores all elements tree in PQ let pq = []; // Utility function to find the Kth // largest element in the given tree function findKthLargest(k) { // Loop until priority queue is not // empty and K greater than 0 --k; while (k > 0 && pq.length > 0) { pq.shift(); --k; } // If PQ is not empty then return // the top element if (pq.length > 0) { return pq[0]; } // Otherwise, return -1 return -1; } // Function to traverse the given // binary tree function traverse(root) { if (root == null) { return; } // Pushing values in binary tree pq.push(root.data); pq.sort(function(a, b){return a - b}); pq.reverse(); // Left and Right Recursive Call traverse(root.left); traverse(root.right); } // Function to find the Kth largest // element in the given tree function findKthLargestTree(root, K) { // Function Call traverse(root); // Function Call document.write(findKthLargest(K)); } // Given Input let root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.right = newNode(5); root.right = newNode(3); root.right.right = newNode(7); root.right.left = newNode(6); let K = 3; findKthLargestTree(root, K); // This code is contributed by decode2207.</script>
5
Time Complexity: O((N + K)log N)Auxiliary Space: O(N)
divyeshrabadiya07
decode2207
divyesh072019
mukesh07
priority-queue
Heap
Mathematical
Sorting
Tree
Mathematical
Sorting
Tree
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Find k numbers with most occurrences in the given array
Difference between Min Heap and Max Heap
Priority queue of pairs in C++ (Ordered by first)
K-th Largest Sum Contiguous Subarray
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Given a Binary Tree consisting of N nodes and a positive integer K, the task is to find the Kth largest number in the given tree.Examples:"
},
{
"code": null,
"e": 349,
"s": 167,
"text": "Input: K = 3 1 / \\ 2 3 / \\ / \\ 4 5 6 7Output: 5Explanation: The third largest element in the given binary tree is 5."
},
{
"code": null,
"e": 490,
"s": 349,
"text": "Input: K = 1 1 / \\ 2 3Output: 1Explanation: The first largest element in the given binary tree is 1."
},
{
"code": null,
"e": 619,
"s": 490,
"text": "Naive Approach: Flatten the given binary tree and then sort the array. Print the Kth largest number from this sorted array now. "
},
{
"code": null,
"e": 1000,
"s": 619,
"text": "Efficient Approach: The above approach can be made efficient by storing all the elements of the Tree in a priority queue, as the elements are stored based on the priority order, which is ascending by default. Though the complexity will remain the same as the above approach, here we can avoid the additional sorting step. Just print the Kth largest element in the priority queue. "
},
{
"code": null,
"e": 1053,
"s": 1002,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1059,
"s": 1055,
"text": "C++"
},
{
"code": null,
"e": 1064,
"s": 1059,
"text": "Java"
},
{
"code": null,
"e": 1072,
"s": 1064,
"text": "Python3"
},
{
"code": null,
"e": 1075,
"s": 1072,
"text": "C#"
},
{
"code": null,
"e": 1086,
"s": 1075,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Struct binary tree nodestruct Node { int data; Node *left, *right;}; // Function to create a new node of// the treeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Utility function to find the Kth// largest element in the given treeint findKthLargest(priority_queue<int, vector<int> >& pq, int k){ // Loop until priority queue is not // empty and K greater than 0 while (--k && !pq.empty()) { pq.pop(); } // If PQ is not empty then return // the top element if (!pq.empty()) { return pq.top(); } // Otherwise, return -1 return -1;} // Function to traverse the given// binary treevoid traverse( Node* root, priority_queue<int, vector<int> >& pq){ if (!root) { return; } // Pushing values in binary tree pq.push(root->data); // Left and Right Recursive Call traverse(root->left, pq); traverse(root->right, pq);} // Function to find the Kth largest// element in the given treevoid findKthLargestTree(Node* root, int K){ // Stores all elements tree in PQ priority_queue<int, vector<int> > pq; // Function Call traverse(root, pq); // Function Call cout << findKthLargest(pq, K);} // Driver Codeint main(){ // Given Input Node* root = newNode(1); root->left = newNode(2); root->left->left = newNode(4); root->left->right = newNode(5); root->right = newNode(3); root->right->right = newNode(7); root->right->left = newNode(6); int K = 3; findKthLargestTree(root, K); return 0;}",
"e": 2847,
"s": 1086,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;public class Main{ // Struct binary tree node static class Node { int data; Node left; Node right; } // Function to create new node of the tree static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Stores all elements tree in PQ static Vector<Integer> pq = new Vector<Integer>(); // Utility function to find the Kth // largest element in the given tree static int findKthLargest(int k) { // Loop until priority queue is not // empty and K greater than 0 --k; while (k > 0 && pq.size() > 0) { pq.remove(0); --k; } // If PQ is not empty then return // the top element if (pq.size() > 0) { return pq.get(0); } // Otherwise, return -1 return -1; } // Function to traverse the given // binary tree static void traverse(Node root) { if (root == null) { return; } // Pushing values in binary tree pq.add(root.data); Collections.sort(pq); Collections.reverse(pq); // Left and Right Recursive Call traverse(root.left); traverse(root.right); } // Function to find the Kth largest // element in the given tree static void findKthLargestTree(Node root, int K) { // Function Call traverse(root); // Function Call System.out.print(findKthLargest(K)); } // Driver code public static void main(String[] args) { // Given Input Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.right = newNode(5); root.right = newNode(3); root.right.right = newNode(7); root.right.left = newNode(6); int K = 3; findKthLargestTree(root, K); }} // This code is contributed by divyesh07.",
"e": 4989,
"s": 2847,
"text": null
},
{
"code": "# Python3 program for the above approachclass Node: # Struct binary tree node def __init__(self, data): self.data = data self.left = None self.right = None # Stores all elements tree in PQpq = [] # Utility function to find the Kth# largest element in the given treedef findKthLargest(k): # Loop until priority queue is not # empty and K greater than 0 k-=1 while (k > 0 and len(pq) > 0): pq.pop(0) k-=1 # If PQ is not empty then return # the top element if len(pq) > 0: return pq[0] # Otherwise, return -1 return -1 # Function to traverse the given# binary treedef traverse(root): if (root == None): return # Pushing values in binary tree pq.append(root.data) pq.sort() pq.reverse() # Left and Right Recursive Call traverse(root.left) traverse(root.right) # Function to find the Kth largest# element in the given treedef findKthLargestTree(root, K): # Function Call traverse(root); # Function Call print(findKthLargest(K)) # Given Inputroot = Node(1)root.left = Node(2)root.left.left = Node(4)root.left.right = Node(5)root.right = Node(3)root.right.right = Node(7)root.right.left = Node(6)K = 3 findKthLargestTree(root, K) # This code is contributed by mukesh07.",
"e": 6305,
"s": 4989,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Struct binary tree node class Node { public int data; public Node left, right; }; // Function to create a new node of the tree static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Stores all elements tree in PQ static List<int> pq = new List<int>(); // Utility function to find the Kth // largest element in the given tree static int findKthLargest(int k) { // Loop until priority queue is not // empty and K greater than 0 --k; while (k > 0 && pq.Count > 0) { pq.RemoveAt(0); --k; } // If PQ is not empty then return // the top element if (pq.Count > 0) { return pq[0]; } // Otherwise, return -1 return -1; } // Function to traverse the given // binary tree static void traverse(Node root) { if (root == null) { return; } // Pushing values in binary tree pq.Add(root.data); pq.Sort(); pq.Reverse(); // Left and Right Recursive Call traverse(root.left); traverse(root.right); } // Function to find the Kth largest // element in the given tree static void findKthLargestTree(Node root, int K) { // Function Call traverse(root); // Function Call Console.Write(findKthLargest(K)); } static void Main() { // Given Input Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.right = newNode(5); root.right = newNode(3); root.right.right = newNode(7); root.right.left = newNode(6); int K = 3; findKthLargestTree(root, K); }} // This code is contributed by divyeshrabadiya07.",
"e": 8318,
"s": 6305,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Struct binary tree node class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function to create a new node of the tree function newNode(data) { let temp = new Node(data); return temp; } // Stores all elements tree in PQ let pq = []; // Utility function to find the Kth // largest element in the given tree function findKthLargest(k) { // Loop until priority queue is not // empty and K greater than 0 --k; while (k > 0 && pq.length > 0) { pq.shift(); --k; } // If PQ is not empty then return // the top element if (pq.length > 0) { return pq[0]; } // Otherwise, return -1 return -1; } // Function to traverse the given // binary tree function traverse(root) { if (root == null) { return; } // Pushing values in binary tree pq.push(root.data); pq.sort(function(a, b){return a - b}); pq.reverse(); // Left and Right Recursive Call traverse(root.left); traverse(root.right); } // Function to find the Kth largest // element in the given tree function findKthLargestTree(root, K) { // Function Call traverse(root); // Function Call document.write(findKthLargest(K)); } // Given Input let root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.right = newNode(5); root.right = newNode(3); root.right.right = newNode(7); root.right.left = newNode(6); let K = 3; findKthLargestTree(root, K); // This code is contributed by decode2207.</script>",
"e": 10264,
"s": 8318,
"text": null
},
{
"code": null,
"e": 10269,
"s": 10267,
"text": "5"
},
{
"code": null,
"e": 10327,
"s": 10273,
"text": "Time Complexity: O((N + K)log N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 10347,
"s": 10329,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 10358,
"s": 10347,
"text": "decode2207"
},
{
"code": null,
"e": 10372,
"s": 10358,
"text": "divyesh072019"
},
{
"code": null,
"e": 10381,
"s": 10372,
"text": "mukesh07"
},
{
"code": null,
"e": 10396,
"s": 10381,
"text": "priority-queue"
},
{
"code": null,
"e": 10401,
"s": 10396,
"text": "Heap"
},
{
"code": null,
"e": 10414,
"s": 10401,
"text": "Mathematical"
},
{
"code": null,
"e": 10422,
"s": 10414,
"text": "Sorting"
},
{
"code": null,
"e": 10427,
"s": 10422,
"text": "Tree"
},
{
"code": null,
"e": 10440,
"s": 10427,
"text": "Mathematical"
},
{
"code": null,
"e": 10448,
"s": 10440,
"text": "Sorting"
},
{
"code": null,
"e": 10453,
"s": 10448,
"text": "Tree"
},
{
"code": null,
"e": 10458,
"s": 10453,
"text": "Heap"
},
{
"code": null,
"e": 10473,
"s": 10458,
"text": "priority-queue"
},
{
"code": null,
"e": 10571,
"s": 10473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10603,
"s": 10571,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 10659,
"s": 10603,
"text": "Find k numbers with most occurrences in the given array"
},
{
"code": null,
"e": 10700,
"s": 10659,
"text": "Difference between Min Heap and Max Heap"
},
{
"code": null,
"e": 10750,
"s": 10700,
"text": "Priority queue of pairs in C++ (Ordered by first)"
},
{
"code": null,
"e": 10787,
"s": 10750,
"text": "K-th Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 10817,
"s": 10787,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 10860,
"s": 10817,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10920,
"s": 10860,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10935,
"s": 10920,
"text": "C++ Data Types"
}
] |
Replace every character of string by character whose ASCII value is K times more than it | 27 May, 2022
Given string str consisting of lowercase letters only and an integer k, the task is to replace every character of the given string with a character whose ASCII value is k times more than it. If the ASCII value exceeds ‘z’, then start checking from ‘a’ in a cyclic manner.
Examples:
Input: str = “abc”, k = 2 Output: cde a is moved by 2 times which results in character c b is moved by 2 times which results in character d c is moved by 2 times which results in character eInput: str = “abc”, k = 28 Output: cde a is moved 25 times, z is reached. Then 26th character will be a, 27-th b and 28-th c. b is moved 24 times, z is reached. 28-th is d. b is moved 23 times, z is reached. 28-th is e.
Approach: Iterate for every character in the string and perform the below steps for each character:
Add k to the ASCII value of character str[i].
If it exceeds 122, then perform a modulus operation of k with 26 to reduce the number of steps, as 26 is the maximum number of shifts that can be performed in a rotation.
To find the character, add k to 96. Hence, the character with ASCII value k+96 will be a new character.
Repeat the above steps for every character of the given string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to move every character// K times ahead in a given string#include <bits/stdc++.h>using namespace std; // Function to move string charactervoid encode(string s,int k){ // changed string string newS; // iterate for every characters for(int i=0; i<s.length(); ++i) { // ASCII value int val = int(s[i]); // store the duplicate int dup = k; // if k-th ahead character exceed 'z' if(val + k > 122){ k -= (122-val); k = k % 26; newS += char(96 + k); } else newS += char(val + k); k = dup; } // print the new string cout<<newS;} // driver codeint main(){ string str = "abc"; int k = 28; // function call encode(str, k); return 0;} // This code is contributed by Sanjit_Prasad
// Java program to move every character// K times ahead in a given string class GFG { // Function to move string character static void encode(String s, int k) { // changed string String newS = ""; // iterate for every characters for (int i = 0; i < s.length(); ++i) { // ASCII value int val = s.charAt(i); // store the duplicate int dup = k; // if k-th ahead character exceed 'z' if (val + k > 122) { k -= (122 - val); k = k % 26; newS += (char)(96 + k); } else { newS += (char)(val + k); } k = dup; } // print the new string System.out.println(newS); } // Driver Code public static void main(String[] args) { String str = "abc"; int k = 28; // function call encode(str, k); }} // This code is contributed by Rajput-JI
# Python program to move every character# K times ahead in a given string # Function to move string characterdef encode(s, k): # changed string newS = "" # iterate for every characters for i in range(len(s)): # ASCII value val = ord(s[i]) # store the duplicate dup = k # if k-th ahead character exceed 'z' if val + k>122: k -= (122-val) k = k % 26 newS += chr(96 + k) else: newS += chr(val + k) k = dup # print the new string print (newS) # driver code str = "abc"k = 28 encode(str, k)
// C# program to move every character// K times ahead in a given stringusing System;public class GFG { // Function to move string character static void encode(String s, int k) { // changed string String newS = ""; // iterate for every characters for (int i = 0; i < s.Length; ++i) { // ASCII value int val = s[i]; // store the duplicate int dup = k; // if k-th ahead character exceed 'z' if (val + k > 122) { k -= (122 - val); k = k % 26; newS += (char)(96 + k); } else { newS += (char)(96 + k); } k = dup; } // print the new string Console.Write(newS); } // Driver Code public static void Main() { String str = "abc"; int k = 28; // function call encode(str, k); }} // This code is contributed by Rajput-JI
<?php// PHP program to move every character// K times ahead in a given string // Function to move string characterfunction encode($s, $k){ // changed string $newS = ""; // iterate for every characters for($i = 0; $i < strlen($s); ++$i) { // ASCII value $val = ord($s[$i]); // store the duplicate $dup = $k; // if k-th ahead character exceed 'z' if($val + $k > 122) { $k -= (122 - $val); $k = $k % 26; $newS = $newS.chr(96 + $k); } else $newS = $newS.chr($val + $k); $k = $dup; } // print the new string echo $newS;} // Driver code $str = "abc";$k = 28; // function callencode($str, $k); // This code is contributed by ita_c?>
<script>// Javascript program to move every character// K times ahead in a given string // Function to move string character function encode(s,k) { // changed string let newS = ""; // iterate for every characters for (let i = 0; i < s.length; ++i) { // ASCII value let val = s[i].charCodeAt(0); // store the duplicate let dup = k; // if k-th ahead character exceed 'z' if (val + k > 122) { k -= (122 - val); k = k % 26; newS += String.fromCharCode(96 + k); } else { newS += String.fromCharCode(val + k); } k = dup; } // print the new string document.write(newS); } // Driver Code let str = "abc"; let k = 28; // function call encode(str, k); // This code is contributed by rag2127</script>
Output:
cde
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time, where N is the length of the string.Auxiliary Space: O(N)
Sanjit_Prasad
Rajput-Ji
ukasp
rag2127
rohitsingh07052
C-String-Question
Constructive Algorithms
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Convert string to char array in C++
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Reverse words in a given string
Print all the duplicates in the input string
What is Data Structure: Types, Classifications and Applications
Reverse string in Python (6 different ways) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 324,
"s": 52,
"text": "Given string str consisting of lowercase letters only and an integer k, the task is to replace every character of the given string with a character whose ASCII value is k times more than it. If the ASCII value exceeds ‘z’, then start checking from ‘a’ in a cyclic manner."
},
{
"code": null,
"e": 336,
"s": 324,
"text": "Examples: "
},
{
"code": null,
"e": 747,
"s": 336,
"text": "Input: str = “abc”, k = 2 Output: cde a is moved by 2 times which results in character c b is moved by 2 times which results in character d c is moved by 2 times which results in character eInput: str = “abc”, k = 28 Output: cde a is moved 25 times, z is reached. Then 26th character will be a, 27-th b and 28-th c. b is moved 24 times, z is reached. 28-th is d. b is moved 23 times, z is reached. 28-th is e. "
},
{
"code": null,
"e": 849,
"s": 747,
"text": "Approach: Iterate for every character in the string and perform the below steps for each character: "
},
{
"code": null,
"e": 895,
"s": 849,
"text": "Add k to the ASCII value of character str[i]."
},
{
"code": null,
"e": 1066,
"s": 895,
"text": "If it exceeds 122, then perform a modulus operation of k with 26 to reduce the number of steps, as 26 is the maximum number of shifts that can be performed in a rotation."
},
{
"code": null,
"e": 1170,
"s": 1066,
"text": "To find the character, add k to 96. Hence, the character with ASCII value k+96 will be a new character."
},
{
"code": null,
"e": 1234,
"s": 1170,
"text": "Repeat the above steps for every character of the given string."
},
{
"code": null,
"e": 1286,
"s": 1234,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1290,
"s": 1286,
"text": "C++"
},
{
"code": null,
"e": 1295,
"s": 1290,
"text": "Java"
},
{
"code": null,
"e": 1303,
"s": 1295,
"text": "Python3"
},
{
"code": null,
"e": 1306,
"s": 1303,
"text": "C#"
},
{
"code": null,
"e": 1310,
"s": 1306,
"text": "PHP"
},
{
"code": null,
"e": 1321,
"s": 1310,
"text": "Javascript"
},
{
"code": "// CPP program to move every character// K times ahead in a given string#include <bits/stdc++.h>using namespace std; // Function to move string charactervoid encode(string s,int k){ // changed string string newS; // iterate for every characters for(int i=0; i<s.length(); ++i) { // ASCII value int val = int(s[i]); // store the duplicate int dup = k; // if k-th ahead character exceed 'z' if(val + k > 122){ k -= (122-val); k = k % 26; newS += char(96 + k); } else newS += char(val + k); k = dup; } // print the new string cout<<newS;} // driver codeint main(){ string str = \"abc\"; int k = 28; // function call encode(str, k); return 0;} // This code is contributed by Sanjit_Prasad",
"e": 2158,
"s": 1321,
"text": null
},
{
"code": "// Java program to move every character// K times ahead in a given string class GFG { // Function to move string character static void encode(String s, int k) { // changed string String newS = \"\"; // iterate for every characters for (int i = 0; i < s.length(); ++i) { // ASCII value int val = s.charAt(i); // store the duplicate int dup = k; // if k-th ahead character exceed 'z' if (val + k > 122) { k -= (122 - val); k = k % 26; newS += (char)(96 + k); } else { newS += (char)(val + k); } k = dup; } // print the new string System.out.println(newS); } // Driver Code public static void main(String[] args) { String str = \"abc\"; int k = 28; // function call encode(str, k); }} // This code is contributed by Rajput-JI",
"e": 3148,
"s": 2158,
"text": null
},
{
"code": "# Python program to move every character# K times ahead in a given string # Function to move string characterdef encode(s, k): # changed string newS = \"\" # iterate for every characters for i in range(len(s)): # ASCII value val = ord(s[i]) # store the duplicate dup = k # if k-th ahead character exceed 'z' if val + k>122: k -= (122-val) k = k % 26 newS += chr(96 + k) else: newS += chr(val + k) k = dup # print the new string print (newS) # driver code str = \"abc\"k = 28 encode(str, k)",
"e": 3831,
"s": 3148,
"text": null
},
{
"code": "// C# program to move every character// K times ahead in a given stringusing System;public class GFG { // Function to move string character static void encode(String s, int k) { // changed string String newS = \"\"; // iterate for every characters for (int i = 0; i < s.Length; ++i) { // ASCII value int val = s[i]; // store the duplicate int dup = k; // if k-th ahead character exceed 'z' if (val + k > 122) { k -= (122 - val); k = k % 26; newS += (char)(96 + k); } else { newS += (char)(96 + k); } k = dup; } // print the new string Console.Write(newS); } // Driver Code public static void Main() { String str = \"abc\"; int k = 28; // function call encode(str, k); }} // This code is contributed by Rajput-JI",
"e": 4810,
"s": 3831,
"text": null
},
{
"code": "<?php// PHP program to move every character// K times ahead in a given string // Function to move string characterfunction encode($s, $k){ // changed string $newS = \"\"; // iterate for every characters for($i = 0; $i < strlen($s); ++$i) { // ASCII value $val = ord($s[$i]); // store the duplicate $dup = $k; // if k-th ahead character exceed 'z' if($val + $k > 122) { $k -= (122 - $val); $k = $k % 26; $newS = $newS.chr(96 + $k); } else $newS = $newS.chr($val + $k); $k = $dup; } // print the new string echo $newS;} // Driver code $str = \"abc\";$k = 28; // function callencode($str, $k); // This code is contributed by ita_c?>",
"e": 5580,
"s": 4810,
"text": null
},
{
"code": "<script>// Javascript program to move every character// K times ahead in a given string // Function to move string character function encode(s,k) { // changed string let newS = \"\"; // iterate for every characters for (let i = 0; i < s.length; ++i) { // ASCII value let val = s[i].charCodeAt(0); // store the duplicate let dup = k; // if k-th ahead character exceed 'z' if (val + k > 122) { k -= (122 - val); k = k % 26; newS += String.fromCharCode(96 + k); } else { newS += String.fromCharCode(val + k); } k = dup; } // print the new string document.write(newS); } // Driver Code let str = \"abc\"; let k = 28; // function call encode(str, k); // This code is contributed by rag2127</script>",
"e": 6555,
"s": 5580,
"text": null
},
{
"code": null,
"e": 6565,
"s": 6555,
"text": "Output: "
},
{
"code": null,
"e": 6569,
"s": 6565,
"text": "cde"
},
{
"code": null,
"e": 6723,
"s": 6569,
"text": "Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time, where N is the length of the string.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 6737,
"s": 6723,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 6747,
"s": 6737,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6753,
"s": 6747,
"text": "ukasp"
},
{
"code": null,
"e": 6761,
"s": 6753,
"text": "rag2127"
},
{
"code": null,
"e": 6777,
"s": 6761,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 6795,
"s": 6777,
"text": "C-String-Question"
},
{
"code": null,
"e": 6819,
"s": 6795,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 6827,
"s": 6819,
"text": "Strings"
},
{
"code": null,
"e": 6846,
"s": 6827,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6854,
"s": 6846,
"text": "Strings"
},
{
"code": null,
"e": 6952,
"s": 6854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7009,
"s": 6952,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 7047,
"s": 7009,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 7108,
"s": 7047,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 7144,
"s": 7108,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 7196,
"s": 7144,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 7241,
"s": 7196,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 7273,
"s": 7241,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 7318,
"s": 7273,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 7382,
"s": 7318,
"text": "What is Data Structure: Types, Classifications and Applications"
}
] |
Reverse a linked list | Difficulty Level :
Medium
Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing the links between nodes.
Examples:
Input: Head of following linked list 1->2->3->4->NULL Output: Linked list should be changed to, 4->3->2->1->NULL
Input: Head of following linked list 1->2->3->4->5->NULL Output: Linked list should be changed to, 5->4->3->2->1->NULL
Input: NULL Output: NULL
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Input: 1->NULL Output: 1->NULL
Iterative Method
Initialize three pointers prev as NULL, curr as head and next as NULL.Iterate through the linked list. In loop, do following. // Before changing next of current, // store next node next = curr->next// Now change next of current // This is where actual reversing happens curr->next = prev // Move prev and curr one step forward prev = curr curr = next
Initialize three pointers prev as NULL, curr as head and next as NULL.
Iterate through the linked list. In loop, do following. // Before changing next of current, // store next node next = curr->next// Now change next of current // This is where actual reversing happens curr->next = prev // Move prev and curr one step forward prev = curr curr = next
Below is the implementation of the above approach:
C++
C
Java
Python
C#
Javascript
// Iterative C++ program to reverse a linked list#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; }}; struct LinkedList { Node* head; LinkedList() { head = NULL; } /* Function to reverse the linked list */ void reverse() { // Initialize current, previous and next pointers Node* current = head; Node *prev = NULL, *next = NULL; while (current != NULL) { // Store next next = current->next; // Reverse current node's pointer current->next = prev; // Move pointers one position ahead. prev = current; current = next; } head = prev; } /* Function to print linked list */ void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; }}; /* Driver code*/int main(){ /* Start with the empty list */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); cout << "Given linked list\n"; ll.print(); ll.reverse(); cout << "\nReversed Linked list \n"; ll.print(); return 0;}
// Iterative C program to reverse a linked list#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* Function to reverse the linked list */static void reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next = NULL; while (current != NULL) { // Store next next = current->next; // Reverse current node's pointer current->next = prev; // Move pointers one position ahead. prev = current; current = next; } *head_ref = prev;} /* Function to push a node */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node* head){ struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; }} /* Driver code*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 85); printf("Given linked list\n"); printList(head); reverse(&head); printf("\nReversed Linked list \n"); printList(head); getchar();}
// Java program for reversing the linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to reverse the linked list */ Node reverse(Node node) { Node prev = null; Node current = node; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } node = prev; return node; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } // Driver Code public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(85); list.head.next = new Node(15); list.head.next.next = new Node(4); list.head.next.next.next = new Node(20); System.out.println("Given Linked list"); list.printList(head); head = list.reverse(head); System.out.println(""); System.out.println("Reversed linked list "); list.printList(head); }} // This code has been contributed by Mayank Jaiswal
# Python program to reverse a linked list# Time Complexity : O(n)# Space Complexity : O(1) # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to reverse the linked list def reverse(self): prev = None current = self.head while(current is not None): next = current.next current.next = prev prev = current current = next self.head = prev # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # Driver codellist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(85) print "Given Linked List"llist.printList()llist.reverse()print "\nReversed Linked List"llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# program for reversing the linked listusing System; class GFG { // Driver Code static void Main(string[] args) { LinkedList list = new LinkedList(); list.AddNode(new LinkedList.Node(85)); list.AddNode(new LinkedList.Node(15)); list.AddNode(new LinkedList.Node(4)); list.AddNode(new LinkedList.Node(20)); // List before reversal Console.WriteLine("Given linked list:"); list.PrintList(); // Reverse the list list.ReverseList(); // List after reversal Console.WriteLine("Reversed linked list:"); list.PrintList(); }} class LinkedList { Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // function to add a new node at // the end of the list public void AddNode(Node node) { if (head == null) head = node; else { Node temp = head; while (temp.next != null) { temp = temp.next; } temp.next = node; } } // function to reverse the list public void ReverseList() { Node prev = null, current = head, next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; } // function to print the list data public void PrintList() { Node current = head; while (current != null) { Console.Write(current.data + " "); current = current.next; } Console.WriteLine(); }} // This code is contributed by Mayank Sharma
<script> // JavaScript program for reversing the linked list var head; class Node { constructor(val) { this.data = val; this.next = null; } } /* Function to reverse the linked list */ function reverse(node) { var prev = null; var current = node; var next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } node = prev; return node; } // prints content of double linked list function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } // Driver Code head = new Node(85); head.next = new Node(15); head.next.next = new Node(4); head.next.next.next = new Node(20); document.write("Given Linked list<br/>"); printList(head); head = reverse(head); document.write("<br/>"); document.write("Reversed linked list<br/> "); printList(head); // This code is contributed by todaysgaurav </script>
Output:
Given linked list
85 15 4 20
Reversed Linked list
20 4 15 85
Time Complexity: O(n) Auxiliary Space: O(1)
Recursive Method:
1) Divide the list in two parts - first node and
rest of the linked list.
2) Call reverse for the rest of the linked list.
3) Link rest to first.
4) Fix head pointer
C++
Java
Python3
C#
Javascript
// Recursive C++ program to reverse// a linked list#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; }}; struct LinkedList { Node* head; LinkedList() { head = NULL; } Node* reverse(Node* head) { if (head == NULL || head->next == NULL) return head; /* reverse the rest list and put the first element at the end */ Node* rest = reverse(head->next); head->next->next = head; /* tricky step -- see the diagram */ head->next = NULL; /* fix the head pointer */ return rest; } /* Function to print linked list */ void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; }}; /* Driver program to test above function*/int main(){ /* Start with the empty list */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); cout << "Given linked list\n"; ll.print(); ll.head = ll.reverse(ll.head); cout << "\nReversed Linked list \n"; ll.print(); return 0;}
// Recursive Java program to reverse// a linked listclass recursion { static Node head; // head of list static class Node { int data; Node next; Node(int d) { data = d; next = null; } } static Node reverse(Node head) { if (head == null || head.next == null) return head; /* reverse the rest list and put the first element at the end */ Node rest = reverse(head.next); head.next.next = head; /* tricky step -- see the diagram */ head.next = null; /* fix the head pointer */ return rest; } /* Function to print linked list */ static void print() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } static void push(int data) { Node temp = new Node(data); temp.next = head; head = temp; } /* Driver program to test above function*/public static void main(String args[]){ /* Start with the empty list */ push(20); push(4); push(15); push(85); System.out.println("Given linked list"); print(); head = reverse(head); System.out.println("Reversed Linked list"); print();}} // This code is contributed by Prakhar Agarwal
"""Python3 program to reverse linked listusing recursive method""" # Linked List Nodeclass Node: def __init__(self, data): self.data = data self.next = None # Create and Handle list operationsclass LinkedList: def __init__(self): self.head = None # Head of list # Method to reverse the list def reverse(self, head): # If head is empty or has reached the list end if head is None or head.next is None: return head # Reverse the rest list rest = self.reverse(head.next) # Put first element at the end head.next.next = head head.next = None # Fix the header pointer return rest # Returns the linked list in display format def __str__(self): linkedListStr = "" temp = self.head while temp: linkedListStr = (linkedListStr + str(temp.data) + " ") temp = temp.next return linkedListStr # Pushes new data to the head of the list def push(self, data): temp = Node(data) temp.next = self.head self.head = temp # Driver codelinkedList = LinkedList()linkedList.push(20)linkedList.push(4)linkedList.push(15)linkedList.push(85) print("Given linked list")print(linkedList) linkedList.head = linkedList.reverse(linkedList.head) print("Reversed linked list")print(linkedList) # This code is contributed by Debidutta Rath
// Recursive C# program to// reverse a linked listusing System;class recursion{ // Head of liststatic Node head; public class Node{ public int data; public Node next; public Node(int d) { data = d; next = null; }} static Node reverse(Node head){ if (head == null || head.next == null) return head; // Reverse the rest list and put // the first element at the end Node rest = reverse(head.next); head.next.next = head; // Tricky step -- // see the diagram head.next = null; // Fix the head pointer return rest;} // Function to print// linked liststatic void print(){ Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine();} static void push(int data){ Node temp = new Node(data); temp.next = head; head = temp;} // Driver codepublic static void Main(String []args){ // Start with the // empty list push(20); push(4); push(15); push(85); Console.WriteLine("Given linked list"); print(); head = reverse(head); Console.WriteLine("Reversed Linked list"); print();}} // This code is contributed by gauravrajput1
<script>// Recursive javascript program to reverse// a linked list var head; // head of list class Node { constructor(val) { this.data = val; this.next = null; } } function reverse(head) { if (head == null || head.next == null) return head; /* * reverse the rest list and put the first element at the end */ var rest = reverse(head.next); head.next.next = head; /* tricky step -- see the diagram */ head.next = null; /* fix the head pointer */ return rest; } /* Function to print linked list */ function print() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write(); } function push(data) { var temp = new Node(data); temp.next = head; head = temp; } /* Driver program to test above function */ /* Start with the empty list */ push(20); push(4); push(15); push(85); document.write("Given linked list<br/>"); print(); head = reverse(head); document.write("<br/>Reversed Linked list<br/>"); print(); // This code is contributed by Rajput-Ji</script>
Output:
Given linked list
85 15 4 20
Reversed Linked list
20 4 15 85
Time Complexity: O(n) Auxiliary Space: O(n)
A Simpler and Tail Recursive Method
Below is the implementation of this method.
C++
C
Java
Python
C#
Javascript
// A simple and tail recursive C++ program to reverse// a linked list#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; void reverseUtil(Node* curr, Node* prev, Node** head); // This function mainly calls reverseUtil()// with prev as NULLvoid reverse(Node** head){ if (!head) return; reverseUtil(*head, NULL, head);} // A simple and tail-recursive function to reverse// a linked list. prev is passed as NULL initially.void reverseUtil(Node* curr, Node* prev, Node** head){ /* If last node mark it head*/ if (!curr->next) { *head = curr; /* Update next to prev node */ curr->next = prev; return; } /* Save curr->next node for recursive call */ Node* next = curr->next; /* and update next ..*/ curr->next = prev; reverseUtil(next, curr, head);} // A utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printlist(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; } cout << endl;} // Driver codeint main(){ Node* head1 = newNode(1); head1->next = newNode(2); head1->next->next = newNode(3); head1->next->next->next = newNode(4); head1->next->next->next->next = newNode(5); head1->next->next->next->next->next = newNode(6); head1->next->next->next->next->next->next = newNode(7); head1->next->next->next->next->next->next->next = newNode(8); cout << "Given linked list\n"; printlist(head1); reverse(&head1); cout << "\nReversed linked list\n"; printlist(head1); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// A simple and tail recursive C program to reverse a linked list#include <stdio.h>#include <stdlib.h> typedef struct Node { int data; struct Node* next;}Node; void reverseUtil(Node* curr, Node* prev, Node** head); // This function mainly calls reverseUtil()// with prev as NULLvoid reverse(Node** head){ if (!head) return; reverseUtil(*head, NULL, head);} // A simple and tail-recursive function to reverse// a linked list. prev is passed as NULL initially.void reverseUtil(Node* curr, Node* prev, Node** head){ /* If last node mark it head*/ if (!curr->next) { *head = curr; /* Update next to prev node */ curr->next = prev; return; } /* Save curr->next node for recursive call */ Node* next = curr->next; /* and update next ..*/ curr->next = prev; reverseUtil(next, curr, head);} // A utility function to create a new nodeNode* newNode(int key){ Node* temp = (Node *)malloc(sizeof(Node)); temp->data = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printlist(Node* head){ while (head != NULL) { printf("%d ",head->data); head = head->next; } printf("\n");} // Driver codeint main(){ Node* head1 = newNode(1); head1->next = newNode(2); head1->next->next = newNode(3); head1->next->next->next = newNode(4); head1->next->next->next->next = newNode(5); head1->next->next->next->next->next = newNode(6); head1->next->next->next->next->next->next = newNode(7); head1->next->next->next->next->next->next->next = newNode(8); printf("Given linked list\n"); printlist(head1); reverse(&head1); printf("\nReversed linked list\n"); printlist(head1); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program for reversing the Linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } // A simple and tail recursive function to reverse // a linked list. prev is passed as NULL initially. Node reverseUtil(Node curr, Node prev) { /*If head is initially null OR list is empty*/ if (head == null) return head; /* If last node mark it head*/ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return head; } /* Save curr->next node for recursive call */ Node next1 = curr.next; /* and update next ..*/ curr.next = prev; reverseUtil(next1, curr); return head; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } // Driver Code public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); list.head.next.next.next.next.next.next.next = new Node(8); System.out.println("Original Linked list "); list.printList(head); Node res = list.reverseUtil(head, null); System.out.println(""); System.out.println(""); System.out.println("Reversed linked list "); list.printList(res); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Simple and tail recursive Python program to# reverse a linked list # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None def reverseUtil(self, curr, prev): # If last node mark it head if curr.next is None: self.head = curr # Update next to prev node curr.next = prev return # Save curr.next node for recursive call next = curr.next # And update next curr.next = prev self.reverseUtil(next, curr) # This function mainly calls reverseUtil() # with previous as None def reverse(self): if self.head is None: return self.reverseUtil(self.head, None) # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # Driver codellist = LinkedList()llist.push(8)llist.push(7)llist.push(6)llist.push(5)llist.push(4)llist.push(3)llist.push(2)llist.push(1) print "Given linked list"llist.printList() llist.reverse() print "\nReverse linked list"llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# program for reversing the Linked listusing System; public class LinkedList { Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // A simple and tail-recursive function to reverse // a linked list. prev is passed as NULL initially. Node reverseUtil(Node curr, Node prev) { /* If last node mark it head*/ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return head; } /* Save curr->next node for recursive call */ Node next1 = curr.next; /* and update next ..*/ curr.next = prev; reverseUtil(next1, curr); return head; } // prints content of double linked list void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Driver code public static void Main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); list.head.next.next.next.next.next.next.next = new Node(8); Console.WriteLine("Original Linked list "); list.printList(list.head); Node res = list.reverseUtil(list.head, null); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Reversed linked list "); list.printList(res); }} // This code contributed by Rajput-Ji
<script>// javascript program for reversing the Linked list var head; class Node { constructor(d) { this.data = d; this.next = null; } } // A simple and tail recursive function to reverse // a linked list. prev is passed as NULL initially. function reverseUtil(curr, prev) { /* If head is initially null OR list is empty */ if (head == null) return head; /* If last node mark it head */ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return head; } /* Save curr->next node for recursive call */ var next1 = curr.next; /* and update next .. */ curr.next = prev; reverseUtil(next1, curr); return head; } // prints content of var linked list function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } // Driver Code var head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(6); head.next.next.next.next.next.next = new Node(7); head.next.next.next.next.next.next.next = new Node(8); document.write("Original Linked list<br/> "); printList(head); var res = reverseUtil(head, null); document.write("<br/>"); document.write("<br/>"); document.write("Reversed linked list <br/>"); printList(res); // This code is contributed by Rajput-Ji</script>
Given linked list
1 2 3 4 5 6 7 8
Reversed linked list
8 7 6 5 4 3 2 1
Time Complexity: O(N)
As we do certain operation for every node of the linked list.
Auxiliary Space: O(1)
As constant extra space is used.
Head Recursive Method:
C++
// Head recursive C++ program to reverse a linked list#include <iostream>using namespace std; // Linked list nodeclass Node {public: int data; Node* next; // constructor: automatically assigns the value to the // data and next pointer to NULL Node(){}; Node(int val) : data(val) , next(NULL){};}; void reverseUtil(Node* curr, Node* prev, Node** headref){ // Base Case - If curr is last node if (curr->next == NULL) { // Update head of the linked list *headref = curr; // Update next to prev node curr->next = prev; return; } // Recursive Call for next node reverseUtil(curr->next, curr, headref); // Update next to prev node curr->next = prev;} void reverse(Node** headref){ // If linked list is empty or contains single node if (*headref == NULL || (*headref)->next == NULL) return; // Call reverseUtil() with prev as NULL reverseUtil(*headref, NULL, headref);} // Function to insert a node at the end of linked listvoid push(Node** headref, int x){ Node* newptr = new Node(x); if (*headref == NULL) { *headref = newptr; } else { Node* temp = *headref; while (temp->next != NULL) { temp = temp->next; } temp->next = newptr; }} // Functio to print the linked listvoid print(Node* headref){ while (headref != NULL) { cout << headref->data << " "; headref = headref->next; } cout << "\n";} int main(){ Node* head = NULL; // head->1->2->3->4->5->6->NULL push(&head, 1); push(&head, 2); push(&head, 3); push(&head, 4); push(&head, 5); push(&head, 6); cout << "Given Linked List\n"; print(head); reverse(&head); cout << "Reversed Linked List\n"; print(head); return 0;} //This code is contributed by Anisha Wagh
Output:
Given Linked List
1 2 3 4 5 6
Reversed Linked List
6 5 4 3 2 1
Time Complexity : O(N)
Using Stack:
Algorithm –
Store the nodes(values and address) in the stack until all the values are entered.
Once all entries are done, Update the Head pointer to the last location(i.e the last value).
Start popping the nodes(value and address) and store them in the same order until the stack is empty.
Update the next pointer of last Node in the stack by NULL.
Below is the implementation of the above approach:
C++
Java
C#
Python3
Javascript
// C++ program for above approach#include <bits/stdc++.h>#include <iostream>using namespace std; // Create a class Node to enter values and address in the listclass Node {public: int data; Node* next;}; // Function to reverse the linked listvoid reverseLL(Node** head){ // Create a stack "s" of Node type stack<Node*> s; Node* temp = *head; while (temp->next != NULL) { // Push all the nodes in to stack s.push(temp); temp = temp->next; } *head = temp; while (!s.empty()) { // Store the top value of stack in list temp->next = s.top(); // Pop the value from stack s.pop(); // update the next pointer in the list temp = temp->next; } temp->next = NULL;} // Function to Display the elements in Listvoid printlist(Node* temp){ while (temp != NULL) { cout << temp->data << " "; temp = temp->next; }} // Program to insert back of the linked listvoid insert_back(Node** head, int value){ // we have used insertion at back method to enter values // in the list.(eg: head->1->2->3->4->Null) Node* temp = new Node(); temp->data = value; temp->next = NULL; // If *head equals to NULL if (*head == NULL) { *head = temp; return; } else { Node* last_node = *head; while (last_node->next != NULL) last_node = last_node->next; last_node->next = temp; return; }} // Driver Codeint main(){ Node* head = NULL; insert_back(&head, 1); insert_back(&head, 2); insert_back(&head, 3); insert_back(&head, 4); cout << "Given linked list\n"; printlist(head); reverseLL(&head); cout << "\nReversed linked list\n"; printlist(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program for above approachimport java.util.*; class GFG { // Create a class Node to enter values and address in the list static class Node { int data; Node next; }; static Node head = null; // Function to reverse the linked list static void reverseLL() { // Create a stack "s" of Node type Stack<Node> s = new Stack<>(); Node temp = head; while (temp.next != null) { // Push all the nodes in to stack s.add(temp); temp = temp.next; } head = temp; while (!s.isEmpty()) { // Store the top value of stack in list temp.next = s.peek(); // Pop the value from stack s.pop(); // update the next pointer in the list temp = temp.next; } temp.next = null; } // Function to Display the elements in List static void printlist(Node temp) { while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } } // Program to insert back of the linked list static void insert_back(int value) { // we have used insertion at back method to enter // values in the list.(eg: head.1.2.3.4.Null) Node temp = new Node(); temp.data = value; temp.next = null; // If *head equals to null if (head == null) { head = temp; return; } else { Node last_node = head; while (last_node.next != null) last_node = last_node.next; last_node.next = temp; return; } } // Driver Code public static void main(String[] args) { insert_back(1); insert_back(2); insert_back(3); insert_back(4); System.out.print("Given linked list\n"); printlist(head); reverseLL(); System.out.print("\nReversed linked list\n"); printlist(head); }} // This code is contributed by Aditya Kumar (adityakumar129)
// C# program for above approachusing System;using System.Collections.Generic; class GFG{ // Create a class Node to enter// values and address in the listpublic class Node{ public int data; public Node next;};static Node head = null; // Function to reverse the// linked liststatic void reverseLL(){ // Create a stack "s" // of Node type Stack<Node> s = new Stack<Node>(); Node temp = head; while (temp.next != null) { // Push all the nodes // in to stack s.Push(temp); temp = temp.next; } head = temp; while (s.Count != 0) { // Store the top value of // stack in list temp.next = s.Peek(); // Pop the value from stack s.Pop(); // Update the next pointer in the // in the list temp = temp.next; } temp.next = null;} // Function to Display// the elements in Liststatic void printlist(Node temp){ while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; }} // Function to insert back of the// linked liststatic void insert_back( int value){ // We have used insertion at back method // to enter values in the list.(eg: // head.1.2.3.4.Null) Node temp = new Node(); temp.data = value; temp.next = null; // If *head equals to null if (head == null) { head = temp; return; } else { Node last_node = head; while (last_node.next != null) { last_node = last_node.next; } last_node.next = temp; return; }} // Driver Codepublic static void Main(String[] args){ insert_back(1); insert_back(2); insert_back(3); insert_back(4); Console.Write("Given linked list\n"); printlist(head); reverseLL(); Console.Write("\nReversed linked list\n"); printlist(head);}} // This code is contributed by gauravrajput1
# Python code for the above approach # Definition for singly-linked list.class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: # Program to reverse the linked list # using stack def reverseLLUsingStack(self, head): # Initialise the variables stack, temp = [], head while temp: stack.append(temp) temp = temp.next head = temp = stack.pop() # Until stack is not # empty while len(stack) > 0: temp.next = stack.pop() temp = temp.next temp.next = None return head # Driver Codeif __name__ == "__main__": head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) obj = Solution() head = obj.reverseLLUsingStack(head) while head: print(head.val, end=' ') head = head.next
<script>// javascript program for above approach // Create a class Node to enter// values and address in the list class Node{ constructor(){ this.data = 0; this.next = null;}}var head = null;// Function to reverse the// linked listfunction reverseLL(){ // Create a stack "s" // of Node type var s = []; var temp = head; while (temp.next != null) { // Push all the nodes // in to stack s.push(temp); temp = temp.next; } head = temp; while (s.length!=0) { // Store the top value of // stack in list temp.next = s.pop(); // update the next pointer in the // in the list temp = temp.next; } temp.next = null;} // Function to Display// the elements in Listfunction printlist(temp){ while (temp != null) { document.write(temp.data+ " "); temp = temp.next; }} // Program to insert back of the// linked listfunction insert_back( value){ // we have used insertion at back method // to enter values in the list.(eg: // head.1.2.3.4.Null) var temp = new Node(); temp.data = value; temp.next = null; // If *head equals to null if (head == null) { head = temp; return; } else { var last_node = head; while (last_node.next != null) { last_node = last_node.next; } last_node.next = temp; return; }} // Driver Code insert_back(1); insert_back(2); insert_back(3); insert_back(4); document.write("Given linked list\n"); printlist(head); reverseLL(); document.write("<br/>Reversed linked list\n"); printlist(head); // This code is contributed by umadevi9616</script>
Given linked list
1 2 3 4
Reversed linked list
4 3 2 1
Thanks to Gaurav Ahirwar for suggesting this solution.
Time Complexity: O(N)
As we do certain operation for every node of the linked list.
Auxiliary Space: O(N)
Space is used to store the nodes in the stack.
Using array:
Algorithm :-
1. Create a linked list.
2. Count the number of nodes present in the Linked List
3. Initialize an array with the size of the count.
4. Store the elements of the Linked list in array
5. Print the array from the last index to the first.
C++
C
Java
C#
Javascript
#include <bits/stdc++.h>using namespace std; typedef struct node { int val; struct node* next;} node; node* head = NULL; // Function to return the No of nodes present in the linked listint count(node* head){ node* p = head; int k = 1; while (p != NULL) { p = p->next; k++; } return k;} node* ll_reverse(node* head) // to reverse the linked list{ node* p = head; long int i = count(head), j = 1; long int arr[i]; while (i && p != NULL) { arr[j++] = p->val; p = p->next; i--; } j--; while (j) // loop will break as soon as j=0 cout << arr[j--] << " "; return head;} // Function to insert node at the end of linked listnode* insert_end(node* head, int data){ node *q = head, *p = (node*)malloc(sizeof(node)); p->val = data; while (q->next != NULL) q = q->next; q->next = p; p->next = NULL; return head;} node* create_ll(node* head, int data) // create ll{ node* p = (node*)malloc(sizeof(node)); p->val = data; if (head == NULL) { head = p; p->next = NULL; return head; } else { head = insert_end(head, data); return head; }} // Driver code int main(){ int i = 5, j = 1; while (i--) head = create_ll(head, j++); head = ll_reverse(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
#include<stdio.h>#include<stdlib.h> typedef struct node { int val; struct node* next;} node; node* head = NULL; // Function to return the No of nodes present in the linked listint count(node* head){ node* p = head; int k = 1; while (p != NULL) { p = p->next; k++; } return k;} node* ll_reverse(node* head) // to reverse the linked list{ node* p = head; long int i = count(head), j = 1; int arr[i]; while (i && p != NULL) { arr[j++] = p->val; p = p->next; i--; } j--; while (j) // loop will break as soon as j=0 printf("%d ",arr[j--]); return head;} // Function to insert node at the end of linked listnode* insert_end(node* head, int data){ node *q = head, *p = (node*)malloc(sizeof(node)); p->val = data; while (q->next != NULL) q = q->next; q->next = p; p->next = NULL; return head;} node* create_ll(node* head, int data) // create ll{ node* p = (node*)malloc(sizeof(node)); p->val = data; if (head == NULL) { head = p; p->next = NULL; return head; } else { head = insert_end(head, data); return head; }} // Driver code int main(){ int i = 5, j = 1; while (i--) head = create_ll(head, j++); head = ll_reverse(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program of the above approachclass GFG { // Create a class Node to enter values and address in the list static class node { int val; node next; }; static node head = null; // code to count the no. of nodes static int count(node head) { node p = head; int k = 1; while (p != null) { p = p.next; k++; } return k; } // to reverse the linked list static node ll_reverse(node head) { node p = head; int i = count(head), j = 1; int[] arr = new int[i]; while (i != 0 && p != null) { arr[j++] = p.val; p = p.next; i--; } j--; while (j != 0) // loop will break as soon as j=0 System.out.print(arr[j--] + " "); return head; } // code to insert at end of ll static node insert_end(node head, int data) { node q = head; node p = new node(); p.val = data; p.next = null; while (q.next != null) q = q.next; q.next = p; p.next = null; return head; } // create ll static node create_ll(node head, int data) { node p = new node(); p.next = null; p.val = data; if (head == null) { head = p; p.next = null; return head; } else { head = insert_end(head, data); return head; } } public static void main(String[] args) { int i = 5, j = 1; while (i != 0) { head = create_ll(head, j++); i--; } head = ll_reverse(head); }} // This code is contributed by Aditya Kumar (adityakumar129)
// C# program of the above approachusing System; public class GFG { // Create a class Node to enter // values and address in the list public class node { public int val; public node next; }; static node head = null; // code to count the no. of nodes static int count(node head) { node p = head; int k = 1; while (p != null) { p = p.next; k++; } return k; } // to reverse the linked list static node ll_reverse(node head) { node p = head; int i = count(head), j = 1; int[] arr = new int[i]; while (i != 0 && p != null) { arr[j++] = p.val; p = p.next; i--; } j--; while (j != 0) // loop will break as soon as j=0 { Console.Write(arr[j--] + " "); } return head; } // code to insert at end of ll static node insert_end(node head, int data) { node q = head; node p = new node(); p.val = data; p.next = null; while (q.next != null) { q = q.next; } q.next = p; p.next = null; return head; } // create ll static node create_ll(node head, int data) { node p = new node(); p.next = null; p.val = data; if (head == null) { head = p; p.next = null; return head; } else { head = insert_end(head, data); return head; } } public static void Main(String[] args) { int i = 5, j = 1; while (i != 0) { head = create_ll(head, j++); i--; } head = ll_reverse(head); }} // This code is contributed by umadevi9616
<script>// Javascript program of the above approach // Create a class Node to enter values and address in the listclass node { constructor() { this.val = null; this.next = null; }}; let head = null;// code to count the no. of nodesfunction count(head) { let p = head; let k = 1; while (p != null) { p = p.next; k++; } return k;} // to reverse the linked listfunction ll_reverse(head) { let p = head; let i = count(head), j = 1; let arr = new Array(i); while (i != 0 && p != null) { arr[j++] = p.val; p = p.next; i--; } j--; while (j != 0) // loop will break as soon as j=0 document.write(arr[j--] + " "); return head;}// code to insert at end of llfunction insert_end(head, data) { let q = head; let p = new node(); p.val = data; p.next = null; while (q.next != null) q = q.next; q.next = p; p.next = null; return head;} // create llfunction create_ll(head, data) { let p = new node(); p.next = null; p.val = data; if (head == null) { head = p; p.next = null; return head; } else { head = insert_end(head, data); return head; }} let i = 5, j = 1;while (i != 0) { head = create_ll(head, j++); i--;}head = ll_reverse(head); // This code is contributed by gfgking</script>
Input : 1->2->3->4->5
Output: 5->4->3->2->1
Time complexity: O(N) as we visit every node once.
Auxiliary Space: O(N) as extra space is used to store all the nodes in the array.
Recursively Reversing a linked list (A simple implementation) Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
Reversing a linked list | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersReversing a linked list | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=D7y_hoT_YZI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
References: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf
AshishKumar22
andrew1234
Mayank Sharma 25
Rajput-Ji
prakhar7
AmiyaRanjanRout
manavgoswami001
GauravRajput1
SumitSingh41
avishekarora
madhav_mohan
mdusmanansari
todaysgaurav
rajsanghavi9
umadevi9616
arorakashish0911
nnr223442
lokeshmajeti
nishantchandhok
adityakumar129
gfgking
abhijeet19403
anishawagh2
mitalibhola94
Accolite
Adobe
Amazon
MakeMyTrip
Microsoft
Qualcomm
Reverse
Samsung
SAP Labs
Snapdeal
Zoho
Linked List
Zoho
Accolite
Amazon
Microsoft
Samsung
Snapdeal
MakeMyTrip
Adobe
SAP Labs
Qualcomm
Linked List
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
LinkedList in Java
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Implementing a Linked List in Java using Class
Add two numbers represented by linked lists | Set 1
Detect and Remove Loop in a Linked List
Function to check if a singly linked list is palindrome
Queue - Linked List Implementation
Implement a stack using singly linked list | [
{
"code": null,
"e": 26,
"s": 0,
"text": "Difficulty Level :\nMedium"
},
{
"code": null,
"e": 180,
"s": 26,
"text": "Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing the links between nodes."
},
{
"code": null,
"e": 191,
"s": 180,
"text": "Examples: "
},
{
"code": null,
"e": 304,
"s": 191,
"text": "Input: Head of following linked list 1->2->3->4->NULL Output: Linked list should be changed to, 4->3->2->1->NULL"
},
{
"code": null,
"e": 423,
"s": 304,
"text": "Input: Head of following linked list 1->2->3->4->5->NULL Output: Linked list should be changed to, 5->4->3->2->1->NULL"
},
{
"code": null,
"e": 448,
"s": 423,
"text": "Input: NULL Output: NULL"
},
{
"code": null,
"e": 457,
"s": 448,
"text": "Chapters"
},
{
"code": null,
"e": 484,
"s": 457,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 534,
"s": 484,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 557,
"s": 534,
"text": "captions off, selected"
},
{
"code": null,
"e": 565,
"s": 557,
"text": "English"
},
{
"code": null,
"e": 589,
"s": 565,
"text": "This is a modal window."
},
{
"code": null,
"e": 658,
"s": 589,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 680,
"s": 658,
"text": "End of dialog window."
},
{
"code": null,
"e": 713,
"s": 680,
"text": "Input: 1->NULL Output: 1->NULL "
},
{
"code": null,
"e": 731,
"s": 713,
"text": "Iterative Method "
},
{
"code": null,
"e": 1082,
"s": 731,
"text": "Initialize three pointers prev as NULL, curr as head and next as NULL.Iterate through the linked list. In loop, do following. // Before changing next of current, // store next node next = curr->next// Now change next of current // This is where actual reversing happens curr->next = prev // Move prev and curr one step forward prev = curr curr = next"
},
{
"code": null,
"e": 1153,
"s": 1082,
"text": "Initialize three pointers prev as NULL, curr as head and next as NULL."
},
{
"code": null,
"e": 1434,
"s": 1153,
"text": "Iterate through the linked list. In loop, do following. // Before changing next of current, // store next node next = curr->next// Now change next of current // This is where actual reversing happens curr->next = prev // Move prev and curr one step forward prev = curr curr = next"
},
{
"code": null,
"e": 1486,
"s": 1434,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1490,
"s": 1486,
"text": "C++"
},
{
"code": null,
"e": 1492,
"s": 1490,
"text": "C"
},
{
"code": null,
"e": 1497,
"s": 1492,
"text": "Java"
},
{
"code": null,
"e": 1504,
"s": 1497,
"text": "Python"
},
{
"code": null,
"e": 1507,
"s": 1504,
"text": "C#"
},
{
"code": null,
"e": 1518,
"s": 1507,
"text": "Javascript"
},
{
"code": "// Iterative C++ program to reverse a linked list#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; }}; struct LinkedList { Node* head; LinkedList() { head = NULL; } /* Function to reverse the linked list */ void reverse() { // Initialize current, previous and next pointers Node* current = head; Node *prev = NULL, *next = NULL; while (current != NULL) { // Store next next = current->next; // Reverse current node's pointer current->next = prev; // Move pointers one position ahead. prev = current; current = next; } head = prev; } /* Function to print linked list */ void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << \" \"; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; }}; /* Driver code*/int main(){ /* Start with the empty list */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); cout << \"Given linked list\\n\"; ll.print(); ll.reverse(); cout << \"\\nReversed Linked list \\n\"; ll.print(); return 0;}",
"e": 2927,
"s": 1518,
"text": null
},
{
"code": "// Iterative C program to reverse a linked list#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* Function to reverse the linked list */static void reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next = NULL; while (current != NULL) { // Store next next = current->next; // Reverse current node's pointer current->next = prev; // Move pointers one position ahead. prev = current; current = next; } *head_ref = prev;} /* Function to push a node */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node* head){ struct Node* temp = head; while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; }} /* Driver code*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 85); printf(\"Given linked list\\n\"); printList(head); reverse(&head); printf(\"\\nReversed Linked list \\n\"); printList(head); getchar();}",
"e": 4291,
"s": 2927,
"text": null
},
{
"code": "// Java program for reversing the linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to reverse the linked list */ Node reverse(Node node) { Node prev = null; Node current = node; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } node = prev; return node; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } // Driver Code public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(85); list.head.next = new Node(15); list.head.next.next = new Node(4); list.head.next.next.next = new Node(20); System.out.println(\"Given Linked list\"); list.printList(head); head = list.reverse(head); System.out.println(\"\"); System.out.println(\"Reversed linked list \"); list.printList(head); }} // This code has been contributed by Mayank Jaiswal",
"e": 5636,
"s": 4291,
"text": null
},
{
"code": "# Python program to reverse a linked list# Time Complexity : O(n)# Space Complexity : O(1) # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to reverse the linked list def reverse(self): prev = None current = self.head while(current is not None): next = current.next current.next = prev prev = current current = next self.head = prev # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # Driver codellist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(85) print \"Given Linked List\"llist.printList()llist.reverse()print \"\\nReversed Linked List\"llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 6873,
"s": 5636,
"text": null
},
{
"code": "// C# program for reversing the linked listusing System; class GFG { // Driver Code static void Main(string[] args) { LinkedList list = new LinkedList(); list.AddNode(new LinkedList.Node(85)); list.AddNode(new LinkedList.Node(15)); list.AddNode(new LinkedList.Node(4)); list.AddNode(new LinkedList.Node(20)); // List before reversal Console.WriteLine(\"Given linked list:\"); list.PrintList(); // Reverse the list list.ReverseList(); // List after reversal Console.WriteLine(\"Reversed linked list:\"); list.PrintList(); }} class LinkedList { Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // function to add a new node at // the end of the list public void AddNode(Node node) { if (head == null) head = node; else { Node temp = head; while (temp.next != null) { temp = temp.next; } temp.next = node; } } // function to reverse the list public void ReverseList() { Node prev = null, current = head, next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; } // function to print the list data public void PrintList() { Node current = head; while (current != null) { Console.Write(current.data + \" \"); current = current.next; } Console.WriteLine(); }} // This code is contributed by Mayank Sharma",
"e": 8635,
"s": 6873,
"text": null
},
{
"code": "<script> // JavaScript program for reversing the linked list var head; class Node { constructor(val) { this.data = val; this.next = null; } } /* Function to reverse the linked list */ function reverse(node) { var prev = null; var current = node; var next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } node = prev; return node; } // prints content of double linked list function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } // Driver Code head = new Node(85); head.next = new Node(15); head.next.next = new Node(4); head.next.next.next = new Node(20); document.write(\"Given Linked list<br/>\"); printList(head); head = reverse(head); document.write(\"<br/>\"); document.write(\"Reversed linked list<br/> \"); printList(head); // This code is contributed by todaysgaurav </script>",
"e": 9785,
"s": 8635,
"text": null
},
{
"code": null,
"e": 9794,
"s": 9785,
"text": "Output: "
},
{
"code": null,
"e": 9857,
"s": 9794,
"text": "Given linked list\n85 15 4 20 \nReversed Linked list \n20 4 15 85"
},
{
"code": null,
"e": 9901,
"s": 9857,
"text": "Time Complexity: O(n) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9920,
"s": 9901,
"text": "Recursive Method: "
},
{
"code": null,
"e": 10105,
"s": 9920,
"text": " 1) Divide the list in two parts - first node and \n rest of the linked list.\n 2) Call reverse for the rest of the linked list.\n 3) Link rest to first.\n 4) Fix head pointer"
},
{
"code": null,
"e": 10109,
"s": 10105,
"text": "C++"
},
{
"code": null,
"e": 10114,
"s": 10109,
"text": "Java"
},
{
"code": null,
"e": 10122,
"s": 10114,
"text": "Python3"
},
{
"code": null,
"e": 10125,
"s": 10122,
"text": "C#"
},
{
"code": null,
"e": 10136,
"s": 10125,
"text": "Javascript"
},
{
"code": "// Recursive C++ program to reverse// a linked list#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; }}; struct LinkedList { Node* head; LinkedList() { head = NULL; } Node* reverse(Node* head) { if (head == NULL || head->next == NULL) return head; /* reverse the rest list and put the first element at the end */ Node* rest = reverse(head->next); head->next->next = head; /* tricky step -- see the diagram */ head->next = NULL; /* fix the head pointer */ return rest; } /* Function to print linked list */ void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << \" \"; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; }}; /* Driver program to test above function*/int main(){ /* Start with the empty list */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); cout << \"Given linked list\\n\"; ll.print(); ll.head = ll.reverse(ll.head); cout << \"\\nReversed Linked list \\n\"; ll.print(); return 0;}",
"e": 11494,
"s": 10136,
"text": null
},
{
"code": "// Recursive Java program to reverse// a linked listclass recursion { static Node head; // head of list static class Node { int data; Node next; Node(int d) { data = d; next = null; } } static Node reverse(Node head) { if (head == null || head.next == null) return head; /* reverse the rest list and put the first element at the end */ Node rest = reverse(head.next); head.next.next = head; /* tricky step -- see the diagram */ head.next = null; /* fix the head pointer */ return rest; } /* Function to print linked list */ static void print() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println(); } static void push(int data) { Node temp = new Node(data); temp.next = head; head = temp; } /* Driver program to test above function*/public static void main(String args[]){ /* Start with the empty list */ push(20); push(4); push(15); push(85); System.out.println(\"Given linked list\"); print(); head = reverse(head); System.out.println(\"Reversed Linked list\"); print();}} // This code is contributed by Prakhar Agarwal",
"e": 12870,
"s": 11494,
"text": null
},
{
"code": "\"\"\"Python3 program to reverse linked listusing recursive method\"\"\" # Linked List Nodeclass Node: def __init__(self, data): self.data = data self.next = None # Create and Handle list operationsclass LinkedList: def __init__(self): self.head = None # Head of list # Method to reverse the list def reverse(self, head): # If head is empty or has reached the list end if head is None or head.next is None: return head # Reverse the rest list rest = self.reverse(head.next) # Put first element at the end head.next.next = head head.next = None # Fix the header pointer return rest # Returns the linked list in display format def __str__(self): linkedListStr = \"\" temp = self.head while temp: linkedListStr = (linkedListStr + str(temp.data) + \" \") temp = temp.next return linkedListStr # Pushes new data to the head of the list def push(self, data): temp = Node(data) temp.next = self.head self.head = temp # Driver codelinkedList = LinkedList()linkedList.push(20)linkedList.push(4)linkedList.push(15)linkedList.push(85) print(\"Given linked list\")print(linkedList) linkedList.head = linkedList.reverse(linkedList.head) print(\"Reversed linked list\")print(linkedList) # This code is contributed by Debidutta Rath",
"e": 14298,
"s": 12870,
"text": null
},
{
"code": "// Recursive C# program to// reverse a linked listusing System;class recursion{ // Head of liststatic Node head; public class Node{ public int data; public Node next; public Node(int d) { data = d; next = null; }} static Node reverse(Node head){ if (head == null || head.next == null) return head; // Reverse the rest list and put // the first element at the end Node rest = reverse(head.next); head.next.next = head; // Tricky step -- // see the diagram head.next = null; // Fix the head pointer return rest;} // Function to print// linked liststatic void print(){ Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine();} static void push(int data){ Node temp = new Node(data); temp.next = head; head = temp;} // Driver codepublic static void Main(String []args){ // Start with the // empty list push(20); push(4); push(15); push(85); Console.WriteLine(\"Given linked list\"); print(); head = reverse(head); Console.WriteLine(\"Reversed Linked list\"); print();}} // This code is contributed by gauravrajput1",
"e": 15425,
"s": 14298,
"text": null
},
{
"code": "<script>// Recursive javascript program to reverse// a linked list var head; // head of list class Node { constructor(val) { this.data = val; this.next = null; } } function reverse(head) { if (head == null || head.next == null) return head; /* * reverse the rest list and put the first element at the end */ var rest = reverse(head.next); head.next.next = head; /* tricky step -- see the diagram */ head.next = null; /* fix the head pointer */ return rest; } /* Function to print linked list */ function print() { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(); } function push(data) { var temp = new Node(data); temp.next = head; head = temp; } /* Driver program to test above function */ /* Start with the empty list */ push(20); push(4); push(15); push(85); document.write(\"Given linked list<br/>\"); print(); head = reverse(head); document.write(\"<br/>Reversed Linked list<br/>\"); print(); // This code is contributed by Rajput-Ji</script>",
"e": 16734,
"s": 15425,
"text": null
},
{
"code": null,
"e": 16743,
"s": 16734,
"text": "Output: "
},
{
"code": null,
"e": 16805,
"s": 16743,
"text": "Given linked list\n85 15 4 20 \nReversed Linked list\n20 4 15 85"
},
{
"code": null,
"e": 16849,
"s": 16805,
"text": "Time Complexity: O(n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 16886,
"s": 16849,
"text": "A Simpler and Tail Recursive Method "
},
{
"code": null,
"e": 16932,
"s": 16886,
"text": "Below is the implementation of this method. "
},
{
"code": null,
"e": 16936,
"s": 16932,
"text": "C++"
},
{
"code": null,
"e": 16938,
"s": 16936,
"text": "C"
},
{
"code": null,
"e": 16943,
"s": 16938,
"text": "Java"
},
{
"code": null,
"e": 16950,
"s": 16943,
"text": "Python"
},
{
"code": null,
"e": 16953,
"s": 16950,
"text": "C#"
},
{
"code": null,
"e": 16964,
"s": 16953,
"text": "Javascript"
},
{
"code": "// A simple and tail recursive C++ program to reverse// a linked list#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; void reverseUtil(Node* curr, Node* prev, Node** head); // This function mainly calls reverseUtil()// with prev as NULLvoid reverse(Node** head){ if (!head) return; reverseUtil(*head, NULL, head);} // A simple and tail-recursive function to reverse// a linked list. prev is passed as NULL initially.void reverseUtil(Node* curr, Node* prev, Node** head){ /* If last node mark it head*/ if (!curr->next) { *head = curr; /* Update next to prev node */ curr->next = prev; return; } /* Save curr->next node for recursive call */ Node* next = curr->next; /* and update next ..*/ curr->next = prev; reverseUtil(next, curr, head);} // A utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printlist(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; } cout << endl;} // Driver codeint main(){ Node* head1 = newNode(1); head1->next = newNode(2); head1->next->next = newNode(3); head1->next->next->next = newNode(4); head1->next->next->next->next = newNode(5); head1->next->next->next->next->next = newNode(6); head1->next->next->next->next->next->next = newNode(7); head1->next->next->next->next->next->next->next = newNode(8); cout << \"Given linked list\\n\"; printlist(head1); reverse(&head1); cout << \"\\nReversed linked list\\n\"; printlist(head1); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 18745,
"s": 16964,
"text": null
},
{
"code": "// A simple and tail recursive C program to reverse a linked list#include <stdio.h>#include <stdlib.h> typedef struct Node { int data; struct Node* next;}Node; void reverseUtil(Node* curr, Node* prev, Node** head); // This function mainly calls reverseUtil()// with prev as NULLvoid reverse(Node** head){ if (!head) return; reverseUtil(*head, NULL, head);} // A simple and tail-recursive function to reverse// a linked list. prev is passed as NULL initially.void reverseUtil(Node* curr, Node* prev, Node** head){ /* If last node mark it head*/ if (!curr->next) { *head = curr; /* Update next to prev node */ curr->next = prev; return; } /* Save curr->next node for recursive call */ Node* next = curr->next; /* and update next ..*/ curr->next = prev; reverseUtil(next, curr, head);} // A utility function to create a new nodeNode* newNode(int key){ Node* temp = (Node *)malloc(sizeof(Node)); temp->data = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printlist(Node* head){ while (head != NULL) { printf(\"%d \",head->data); head = head->next; } printf(\"\\n\");} // Driver codeint main(){ Node* head1 = newNode(1); head1->next = newNode(2); head1->next->next = newNode(3); head1->next->next->next = newNode(4); head1->next->next->next->next = newNode(5); head1->next->next->next->next->next = newNode(6); head1->next->next->next->next->next->next = newNode(7); head1->next->next->next->next->next->next->next = newNode(8); printf(\"Given linked list\\n\"); printlist(head1); reverse(&head1); printf(\"\\nReversed linked list\\n\"); printlist(head1); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 20547,
"s": 18745,
"text": null
},
{
"code": "// Java program for reversing the Linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } // A simple and tail recursive function to reverse // a linked list. prev is passed as NULL initially. Node reverseUtil(Node curr, Node prev) { /*If head is initially null OR list is empty*/ if (head == null) return head; /* If last node mark it head*/ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return head; } /* Save curr->next node for recursive call */ Node next1 = curr.next; /* and update next ..*/ curr.next = prev; reverseUtil(next1, curr); return head; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } // Driver Code public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); list.head.next.next.next.next.next.next.next = new Node(8); System.out.println(\"Original Linked list \"); list.printList(head); Node res = list.reverseUtil(head, null); System.out.println(\"\"); System.out.println(\"\"); System.out.println(\"Reversed linked list \"); list.printList(res); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 22476,
"s": 20547,
"text": null
},
{
"code": "# Simple and tail recursive Python program to# reverse a linked list # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None def reverseUtil(self, curr, prev): # If last node mark it head if curr.next is None: self.head = curr # Update next to prev node curr.next = prev return # Save curr.next node for recursive call next = curr.next # And update next curr.next = prev self.reverseUtil(next, curr) # This function mainly calls reverseUtil() # with previous as None def reverse(self): if self.head is None: return self.reverseUtil(self.head, None) # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # Driver codellist = LinkedList()llist.push(8)llist.push(7)llist.push(6)llist.push(5)llist.push(4)llist.push(3)llist.push(2)llist.push(1) print \"Given linked list\"llist.printList() llist.reverse() print \"\\nReverse linked list\"llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 24021,
"s": 22476,
"text": null
},
{
"code": "// C# program for reversing the Linked listusing System; public class LinkedList { Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // A simple and tail-recursive function to reverse // a linked list. prev is passed as NULL initially. Node reverseUtil(Node curr, Node prev) { /* If last node mark it head*/ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return head; } /* Save curr->next node for recursive call */ Node next1 = curr.next; /* and update next ..*/ curr.next = prev; reverseUtil(next1, curr); return head; } // prints content of double linked list void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } // Driver code public static void Main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); list.head.next.next.next.next.next.next.next = new Node(8); Console.WriteLine(\"Original Linked list \"); list.printList(list.head); Node res = list.reverseUtil(list.head, null); Console.WriteLine(\"\"); Console.WriteLine(\"\"); Console.WriteLine(\"Reversed linked list \"); list.printList(res); }} // This code contributed by Rajput-Ji",
"e": 25888,
"s": 24021,
"text": null
},
{
"code": "<script>// javascript program for reversing the Linked list var head; class Node { constructor(d) { this.data = d; this.next = null; } } // A simple and tail recursive function to reverse // a linked list. prev is passed as NULL initially. function reverseUtil(curr, prev) { /* If head is initially null OR list is empty */ if (head == null) return head; /* If last node mark it head */ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return head; } /* Save curr->next node for recursive call */ var next1 = curr.next; /* and update next .. */ curr.next = prev; reverseUtil(next1, curr); return head; } // prints content of var linked list function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } // Driver Code var head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(6); head.next.next.next.next.next.next = new Node(7); head.next.next.next.next.next.next.next = new Node(8); document.write(\"Original Linked list<br/> \"); printList(head); var res = reverseUtil(head, null); document.write(\"<br/>\"); document.write(\"<br/>\"); document.write(\"Reversed linked list <br/>\"); printList(res); // This code is contributed by Rajput-Ji</script>",
"e": 27621,
"s": 25888,
"text": null
},
{
"code": null,
"e": 27697,
"s": 27624,
"text": "Given linked list\n1 2 3 4 5 6 7 8 \n\nReversed linked list\n8 7 6 5 4 3 2 1"
},
{
"code": null,
"e": 27719,
"s": 27697,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 27781,
"s": 27719,
"text": "As we do certain operation for every node of the linked list."
},
{
"code": null,
"e": 27803,
"s": 27781,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27836,
"s": 27803,
"text": "As constant extra space is used."
},
{
"code": null,
"e": 27859,
"s": 27836,
"text": "Head Recursive Method:"
},
{
"code": null,
"e": 27863,
"s": 27859,
"text": "C++"
},
{
"code": "// Head recursive C++ program to reverse a linked list#include <iostream>using namespace std; // Linked list nodeclass Node {public: int data; Node* next; // constructor: automatically assigns the value to the // data and next pointer to NULL Node(){}; Node(int val) : data(val) , next(NULL){};}; void reverseUtil(Node* curr, Node* prev, Node** headref){ // Base Case - If curr is last node if (curr->next == NULL) { // Update head of the linked list *headref = curr; // Update next to prev node curr->next = prev; return; } // Recursive Call for next node reverseUtil(curr->next, curr, headref); // Update next to prev node curr->next = prev;} void reverse(Node** headref){ // If linked list is empty or contains single node if (*headref == NULL || (*headref)->next == NULL) return; // Call reverseUtil() with prev as NULL reverseUtil(*headref, NULL, headref);} // Function to insert a node at the end of linked listvoid push(Node** headref, int x){ Node* newptr = new Node(x); if (*headref == NULL) { *headref = newptr; } else { Node* temp = *headref; while (temp->next != NULL) { temp = temp->next; } temp->next = newptr; }} // Functio to print the linked listvoid print(Node* headref){ while (headref != NULL) { cout << headref->data << \" \"; headref = headref->next; } cout << \"\\n\";} int main(){ Node* head = NULL; // head->1->2->3->4->5->6->NULL push(&head, 1); push(&head, 2); push(&head, 3); push(&head, 4); push(&head, 5); push(&head, 6); cout << \"Given Linked List\\n\"; print(head); reverse(&head); cout << \"Reversed Linked List\\n\"; print(head); return 0;} //This code is contributed by Anisha Wagh",
"e": 29707,
"s": 27863,
"text": null
},
{
"code": null,
"e": 29715,
"s": 29707,
"text": "Output:"
},
{
"code": null,
"e": 29779,
"s": 29715,
"text": "Given Linked List\n1 2 3 4 5 6\n\nReversed Linked List\n6 5 4 3 2 1"
},
{
"code": null,
"e": 29802,
"s": 29779,
"text": "Time Complexity : O(N)"
},
{
"code": null,
"e": 29815,
"s": 29802,
"text": "Using Stack:"
},
{
"code": null,
"e": 29828,
"s": 29815,
"text": "Algorithm – "
},
{
"code": null,
"e": 29911,
"s": 29828,
"text": "Store the nodes(values and address) in the stack until all the values are entered."
},
{
"code": null,
"e": 30004,
"s": 29911,
"text": "Once all entries are done, Update the Head pointer to the last location(i.e the last value)."
},
{
"code": null,
"e": 30106,
"s": 30004,
"text": "Start popping the nodes(value and address) and store them in the same order until the stack is empty."
},
{
"code": null,
"e": 30165,
"s": 30106,
"text": "Update the next pointer of last Node in the stack by NULL."
},
{
"code": null,
"e": 30216,
"s": 30165,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 30220,
"s": 30216,
"text": "C++"
},
{
"code": null,
"e": 30225,
"s": 30220,
"text": "Java"
},
{
"code": null,
"e": 30228,
"s": 30225,
"text": "C#"
},
{
"code": null,
"e": 30236,
"s": 30228,
"text": "Python3"
},
{
"code": null,
"e": 30247,
"s": 30236,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>#include <iostream>using namespace std; // Create a class Node to enter values and address in the listclass Node {public: int data; Node* next;}; // Function to reverse the linked listvoid reverseLL(Node** head){ // Create a stack \"s\" of Node type stack<Node*> s; Node* temp = *head; while (temp->next != NULL) { // Push all the nodes in to stack s.push(temp); temp = temp->next; } *head = temp; while (!s.empty()) { // Store the top value of stack in list temp->next = s.top(); // Pop the value from stack s.pop(); // update the next pointer in the list temp = temp->next; } temp->next = NULL;} // Function to Display the elements in Listvoid printlist(Node* temp){ while (temp != NULL) { cout << temp->data << \" \"; temp = temp->next; }} // Program to insert back of the linked listvoid insert_back(Node** head, int value){ // we have used insertion at back method to enter values // in the list.(eg: head->1->2->3->4->Null) Node* temp = new Node(); temp->data = value; temp->next = NULL; // If *head equals to NULL if (*head == NULL) { *head = temp; return; } else { Node* last_node = *head; while (last_node->next != NULL) last_node = last_node->next; last_node->next = temp; return; }} // Driver Codeint main(){ Node* head = NULL; insert_back(&head, 1); insert_back(&head, 2); insert_back(&head, 3); insert_back(&head, 4); cout << \"Given linked list\\n\"; printlist(head); reverseLL(&head); cout << \"\\nReversed linked list\\n\"; printlist(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 32056,
"s": 30247,
"text": null
},
{
"code": "// Java program for above approachimport java.util.*; class GFG { // Create a class Node to enter values and address in the list static class Node { int data; Node next; }; static Node head = null; // Function to reverse the linked list static void reverseLL() { // Create a stack \"s\" of Node type Stack<Node> s = new Stack<>(); Node temp = head; while (temp.next != null) { // Push all the nodes in to stack s.add(temp); temp = temp.next; } head = temp; while (!s.isEmpty()) { // Store the top value of stack in list temp.next = s.peek(); // Pop the value from stack s.pop(); // update the next pointer in the list temp = temp.next; } temp.next = null; } // Function to Display the elements in List static void printlist(Node temp) { while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } } // Program to insert back of the linked list static void insert_back(int value) { // we have used insertion at back method to enter // values in the list.(eg: head.1.2.3.4.Null) Node temp = new Node(); temp.data = value; temp.next = null; // If *head equals to null if (head == null) { head = temp; return; } else { Node last_node = head; while (last_node.next != null) last_node = last_node.next; last_node.next = temp; return; } } // Driver Code public static void main(String[] args) { insert_back(1); insert_back(2); insert_back(3); insert_back(4); System.out.print(\"Given linked list\\n\"); printlist(head); reverseLL(); System.out.print(\"\\nReversed linked list\\n\"); printlist(head); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 34112,
"s": 32056,
"text": null
},
{
"code": "// C# program for above approachusing System;using System.Collections.Generic; class GFG{ // Create a class Node to enter// values and address in the listpublic class Node{ public int data; public Node next;};static Node head = null; // Function to reverse the// linked liststatic void reverseLL(){ // Create a stack \"s\" // of Node type Stack<Node> s = new Stack<Node>(); Node temp = head; while (temp.next != null) { // Push all the nodes // in to stack s.Push(temp); temp = temp.next; } head = temp; while (s.Count != 0) { // Store the top value of // stack in list temp.next = s.Peek(); // Pop the value from stack s.Pop(); // Update the next pointer in the // in the list temp = temp.next; } temp.next = null;} // Function to Display// the elements in Liststatic void printlist(Node temp){ while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; }} // Function to insert back of the// linked liststatic void insert_back( int value){ // We have used insertion at back method // to enter values in the list.(eg: // head.1.2.3.4.Null) Node temp = new Node(); temp.data = value; temp.next = null; // If *head equals to null if (head == null) { head = temp; return; } else { Node last_node = head; while (last_node.next != null) { last_node = last_node.next; } last_node.next = temp; return; }} // Driver Codepublic static void Main(String[] args){ insert_back(1); insert_back(2); insert_back(3); insert_back(4); Console.Write(\"Given linked list\\n\"); printlist(head); reverseLL(); Console.Write(\"\\nReversed linked list\\n\"); printlist(head);}} // This code is contributed by gauravrajput1",
"e": 36072,
"s": 34112,
"text": null
},
{
"code": "# Python code for the above approach # Definition for singly-linked list.class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: # Program to reverse the linked list # using stack def reverseLLUsingStack(self, head): # Initialise the variables stack, temp = [], head while temp: stack.append(temp) temp = temp.next head = temp = stack.pop() # Until stack is not # empty while len(stack) > 0: temp.next = stack.pop() temp = temp.next temp.next = None return head # Driver Codeif __name__ == \"__main__\": head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) obj = Solution() head = obj.reverseLLUsingStack(head) while head: print(head.val, end=' ') head = head.next",
"e": 37013,
"s": 36072,
"text": null
},
{
"code": "<script>// javascript program for above approach // Create a class Node to enter// values and address in the list class Node{ constructor(){ this.data = 0; this.next = null;}}var head = null;// Function to reverse the// linked listfunction reverseLL(){ // Create a stack \"s\" // of Node type var s = []; var temp = head; while (temp.next != null) { // Push all the nodes // in to stack s.push(temp); temp = temp.next; } head = temp; while (s.length!=0) { // Store the top value of // stack in list temp.next = s.pop(); // update the next pointer in the // in the list temp = temp.next; } temp.next = null;} // Function to Display// the elements in Listfunction printlist(temp){ while (temp != null) { document.write(temp.data+ \" \"); temp = temp.next; }} // Program to insert back of the// linked listfunction insert_back( value){ // we have used insertion at back method // to enter values in the list.(eg: // head.1.2.3.4.Null) var temp = new Node(); temp.data = value; temp.next = null; // If *head equals to null if (head == null) { head = temp; return; } else { var last_node = head; while (last_node.next != null) { last_node = last_node.next; } last_node.next = temp; return; }} // Driver Code insert_back(1); insert_back(2); insert_back(3); insert_back(4); document.write(\"Given linked list\\n\"); printlist(head); reverseLL(); document.write(\"<br/>Reversed linked list\\n\"); printlist(head); // This code is contributed by umadevi9616</script>",
"e": 38807,
"s": 37013,
"text": null
},
{
"code": null,
"e": 38864,
"s": 38807,
"text": "Given linked list\n1 2 3 4 \nReversed linked list\n4 3 2 1 "
},
{
"code": null,
"e": 38920,
"s": 38864,
"text": "Thanks to Gaurav Ahirwar for suggesting this solution. "
},
{
"code": null,
"e": 38942,
"s": 38920,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 39004,
"s": 38942,
"text": "As we do certain operation for every node of the linked list."
},
{
"code": null,
"e": 39026,
"s": 39004,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 39073,
"s": 39026,
"text": "Space is used to store the nodes in the stack."
},
{
"code": null,
"e": 39086,
"s": 39073,
"text": "Using array:"
},
{
"code": null,
"e": 39100,
"s": 39086,
"text": "Algorithm :- "
},
{
"code": null,
"e": 39125,
"s": 39100,
"text": "1. Create a linked list."
},
{
"code": null,
"e": 39181,
"s": 39125,
"text": "2. Count the number of nodes present in the Linked List"
},
{
"code": null,
"e": 39232,
"s": 39181,
"text": "3. Initialize an array with the size of the count."
},
{
"code": null,
"e": 39283,
"s": 39232,
"text": "4. Store the elements of the Linked list in array "
},
{
"code": null,
"e": 39336,
"s": 39283,
"text": "5. Print the array from the last index to the first."
},
{
"code": null,
"e": 39340,
"s": 39336,
"text": "C++"
},
{
"code": null,
"e": 39342,
"s": 39340,
"text": "C"
},
{
"code": null,
"e": 39347,
"s": 39342,
"text": "Java"
},
{
"code": null,
"e": 39350,
"s": 39347,
"text": "C#"
},
{
"code": null,
"e": 39361,
"s": 39350,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; typedef struct node { int val; struct node* next;} node; node* head = NULL; // Function to return the No of nodes present in the linked listint count(node* head){ node* p = head; int k = 1; while (p != NULL) { p = p->next; k++; } return k;} node* ll_reverse(node* head) // to reverse the linked list{ node* p = head; long int i = count(head), j = 1; long int arr[i]; while (i && p != NULL) { arr[j++] = p->val; p = p->next; i--; } j--; while (j) // loop will break as soon as j=0 cout << arr[j--] << \" \"; return head;} // Function to insert node at the end of linked listnode* insert_end(node* head, int data){ node *q = head, *p = (node*)malloc(sizeof(node)); p->val = data; while (q->next != NULL) q = q->next; q->next = p; p->next = NULL; return head;} node* create_ll(node* head, int data) // create ll{ node* p = (node*)malloc(sizeof(node)); p->val = data; if (head == NULL) { head = p; p->next = NULL; return head; } else { head = insert_end(head, data); return head; }} // Driver code int main(){ int i = 5, j = 1; while (i--) head = create_ll(head, j++); head = ll_reverse(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 40750,
"s": 39361,
"text": null
},
{
"code": "#include<stdio.h>#include<stdlib.h> typedef struct node { int val; struct node* next;} node; node* head = NULL; // Function to return the No of nodes present in the linked listint count(node* head){ node* p = head; int k = 1; while (p != NULL) { p = p->next; k++; } return k;} node* ll_reverse(node* head) // to reverse the linked list{ node* p = head; long int i = count(head), j = 1; int arr[i]; while (i && p != NULL) { arr[j++] = p->val; p = p->next; i--; } j--; while (j) // loop will break as soon as j=0 printf(\"%d \",arr[j--]); return head;} // Function to insert node at the end of linked listnode* insert_end(node* head, int data){ node *q = head, *p = (node*)malloc(sizeof(node)); p->val = data; while (q->next != NULL) q = q->next; q->next = p; p->next = NULL; return head;} node* create_ll(node* head, int data) // create ll{ node* p = (node*)malloc(sizeof(node)); p->val = data; if (head == NULL) { head = p; p->next = NULL; return head; } else { head = insert_end(head, data); return head; }} // Driver code int main(){ int i = 5, j = 1; while (i--) head = create_ll(head, j++); head = ll_reverse(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 42124,
"s": 40750,
"text": null
},
{
"code": "// Java program of the above approachclass GFG { // Create a class Node to enter values and address in the list static class node { int val; node next; }; static node head = null; // code to count the no. of nodes static int count(node head) { node p = head; int k = 1; while (p != null) { p = p.next; k++; } return k; } // to reverse the linked list static node ll_reverse(node head) { node p = head; int i = count(head), j = 1; int[] arr = new int[i]; while (i != 0 && p != null) { arr[j++] = p.val; p = p.next; i--; } j--; while (j != 0) // loop will break as soon as j=0 System.out.print(arr[j--] + \" \"); return head; } // code to insert at end of ll static node insert_end(node head, int data) { node q = head; node p = new node(); p.val = data; p.next = null; while (q.next != null) q = q.next; q.next = p; p.next = null; return head; } // create ll static node create_ll(node head, int data) { node p = new node(); p.next = null; p.val = data; if (head == null) { head = p; p.next = null; return head; } else { head = insert_end(head, data); return head; } } public static void main(String[] args) { int i = 5, j = 1; while (i != 0) { head = create_ll(head, j++); i--; } head = ll_reverse(head); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 43857,
"s": 42124,
"text": null
},
{
"code": "// C# program of the above approachusing System; public class GFG { // Create a class Node to enter // values and address in the list public class node { public int val; public node next; }; static node head = null; // code to count the no. of nodes static int count(node head) { node p = head; int k = 1; while (p != null) { p = p.next; k++; } return k; } // to reverse the linked list static node ll_reverse(node head) { node p = head; int i = count(head), j = 1; int[] arr = new int[i]; while (i != 0 && p != null) { arr[j++] = p.val; p = p.next; i--; } j--; while (j != 0) // loop will break as soon as j=0 { Console.Write(arr[j--] + \" \"); } return head; } // code to insert at end of ll static node insert_end(node head, int data) { node q = head; node p = new node(); p.val = data; p.next = null; while (q.next != null) { q = q.next; } q.next = p; p.next = null; return head; } // create ll static node create_ll(node head, int data) { node p = new node(); p.next = null; p.val = data; if (head == null) { head = p; p.next = null; return head; } else { head = insert_end(head, data); return head; } } public static void Main(String[] args) { int i = 5, j = 1; while (i != 0) { head = create_ll(head, j++); i--; } head = ll_reverse(head); }} // This code is contributed by umadevi9616",
"e": 45644,
"s": 43857,
"text": null
},
{
"code": "<script>// Javascript program of the above approach // Create a class Node to enter values and address in the listclass node { constructor() { this.val = null; this.next = null; }}; let head = null;// code to count the no. of nodesfunction count(head) { let p = head; let k = 1; while (p != null) { p = p.next; k++; } return k;} // to reverse the linked listfunction ll_reverse(head) { let p = head; let i = count(head), j = 1; let arr = new Array(i); while (i != 0 && p != null) { arr[j++] = p.val; p = p.next; i--; } j--; while (j != 0) // loop will break as soon as j=0 document.write(arr[j--] + \" \"); return head;}// code to insert at end of llfunction insert_end(head, data) { let q = head; let p = new node(); p.val = data; p.next = null; while (q.next != null) q = q.next; q.next = p; p.next = null; return head;} // create llfunction create_ll(head, data) { let p = new node(); p.next = null; p.val = data; if (head == null) { head = p; p.next = null; return head; } else { head = insert_end(head, data); return head; }} let i = 5, j = 1;while (i != 0) { head = create_ll(head, j++); i--;}head = ll_reverse(head); // This code is contributed by gfgking</script>",
"e": 46888,
"s": 45644,
"text": null
},
{
"code": null,
"e": 46933,
"s": 46888,
"text": "Input : 1->2->3->4->5\nOutput: 5->4->3->2->1"
},
{
"code": null,
"e": 46984,
"s": 46933,
"text": "Time complexity: O(N) as we visit every node once."
},
{
"code": null,
"e": 47066,
"s": 46984,
"text": "Auxiliary Space: O(N) as extra space is used to store all the nodes in the array."
},
{
"code": null,
"e": 47208,
"s": 47066,
"text": "Recursively Reversing a linked list (A simple implementation) Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)"
},
{
"code": null,
"e": 48072,
"s": 47208,
"text": "Reversing a linked list | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersReversing a linked list | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=D7y_hoT_YZI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 48141,
"s": 48072,
"text": "References: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf"
},
{
"code": null,
"e": 48155,
"s": 48141,
"text": "AshishKumar22"
},
{
"code": null,
"e": 48166,
"s": 48155,
"text": "andrew1234"
},
{
"code": null,
"e": 48183,
"s": 48166,
"text": "Mayank Sharma 25"
},
{
"code": null,
"e": 48193,
"s": 48183,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 48202,
"s": 48193,
"text": "prakhar7"
},
{
"code": null,
"e": 48218,
"s": 48202,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 48234,
"s": 48218,
"text": "manavgoswami001"
},
{
"code": null,
"e": 48248,
"s": 48234,
"text": "GauravRajput1"
},
{
"code": null,
"e": 48261,
"s": 48248,
"text": "SumitSingh41"
},
{
"code": null,
"e": 48274,
"s": 48261,
"text": "avishekarora"
},
{
"code": null,
"e": 48287,
"s": 48274,
"text": "madhav_mohan"
},
{
"code": null,
"e": 48301,
"s": 48287,
"text": "mdusmanansari"
},
{
"code": null,
"e": 48314,
"s": 48301,
"text": "todaysgaurav"
},
{
"code": null,
"e": 48327,
"s": 48314,
"text": "rajsanghavi9"
},
{
"code": null,
"e": 48339,
"s": 48327,
"text": "umadevi9616"
},
{
"code": null,
"e": 48356,
"s": 48339,
"text": "arorakashish0911"
},
{
"code": null,
"e": 48366,
"s": 48356,
"text": "nnr223442"
},
{
"code": null,
"e": 48379,
"s": 48366,
"text": "lokeshmajeti"
},
{
"code": null,
"e": 48395,
"s": 48379,
"text": "nishantchandhok"
},
{
"code": null,
"e": 48410,
"s": 48395,
"text": "adityakumar129"
},
{
"code": null,
"e": 48418,
"s": 48410,
"text": "gfgking"
},
{
"code": null,
"e": 48432,
"s": 48418,
"text": "abhijeet19403"
},
{
"code": null,
"e": 48444,
"s": 48432,
"text": "anishawagh2"
},
{
"code": null,
"e": 48458,
"s": 48444,
"text": "mitalibhola94"
},
{
"code": null,
"e": 48467,
"s": 48458,
"text": "Accolite"
},
{
"code": null,
"e": 48473,
"s": 48467,
"text": "Adobe"
},
{
"code": null,
"e": 48480,
"s": 48473,
"text": "Amazon"
},
{
"code": null,
"e": 48491,
"s": 48480,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 48501,
"s": 48491,
"text": "Microsoft"
},
{
"code": null,
"e": 48510,
"s": 48501,
"text": "Qualcomm"
},
{
"code": null,
"e": 48518,
"s": 48510,
"text": "Reverse"
},
{
"code": null,
"e": 48526,
"s": 48518,
"text": "Samsung"
},
{
"code": null,
"e": 48535,
"s": 48526,
"text": "SAP Labs"
},
{
"code": null,
"e": 48544,
"s": 48535,
"text": "Snapdeal"
},
{
"code": null,
"e": 48549,
"s": 48544,
"text": "Zoho"
},
{
"code": null,
"e": 48561,
"s": 48549,
"text": "Linked List"
},
{
"code": null,
"e": 48566,
"s": 48561,
"text": "Zoho"
},
{
"code": null,
"e": 48575,
"s": 48566,
"text": "Accolite"
},
{
"code": null,
"e": 48582,
"s": 48575,
"text": "Amazon"
},
{
"code": null,
"e": 48592,
"s": 48582,
"text": "Microsoft"
},
{
"code": null,
"e": 48600,
"s": 48592,
"text": "Samsung"
},
{
"code": null,
"e": 48609,
"s": 48600,
"text": "Snapdeal"
},
{
"code": null,
"e": 48620,
"s": 48609,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 48626,
"s": 48620,
"text": "Adobe"
},
{
"code": null,
"e": 48635,
"s": 48626,
"text": "SAP Labs"
},
{
"code": null,
"e": 48644,
"s": 48635,
"text": "Qualcomm"
},
{
"code": null,
"e": 48656,
"s": 48644,
"text": "Linked List"
},
{
"code": null,
"e": 48664,
"s": 48656,
"text": "Reverse"
},
{
"code": null,
"e": 48762,
"s": 48664,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48810,
"s": 48762,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 48829,
"s": 48810,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 48861,
"s": 48829,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 48925,
"s": 48861,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 48972,
"s": 48925,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 49024,
"s": 48972,
"text": "Add two numbers represented by linked lists | Set 1"
},
{
"code": null,
"e": 49064,
"s": 49024,
"text": "Detect and Remove Loop in a Linked List"
},
{
"code": null,
"e": 49120,
"s": 49064,
"text": "Function to check if a singly linked list is palindrome"
},
{
"code": null,
"e": 49155,
"s": 49120,
"text": "Queue - Linked List Implementation"
}
] |
How to find the MySQL data directory from command line in Windows? | To find the MySQL data directory, we can simply use the variable datadir. Let us see how to use the variable with select statement.
The query is as follows −
mysql> select @@datadir;
Here is the output
+---------------------------------------------+
| @@datadir |
+---------------------------------------------+
| C:\ProgramData\MySQL\MySQL Server 8.0\Data\ |
+---------------------------------------------+
1 row in set (0.00 sec)
Now we can reach the directory from the above sample output.
Here is the snapshot that displays the MySQL data directory. | [
{
"code": null,
"e": 1319,
"s": 1187,
"text": "To find the MySQL data directory, we can simply use the variable datadir. Let us see how to use the variable with select statement."
},
{
"code": null,
"e": 1345,
"s": 1319,
"text": "The query is as follows −"
},
{
"code": null,
"e": 1370,
"s": 1345,
"text": "mysql> select @@datadir;"
},
{
"code": null,
"e": 1389,
"s": 1370,
"text": "Here is the output"
},
{
"code": null,
"e": 1653,
"s": 1389,
"text": "+---------------------------------------------+\n| @@datadir |\n+---------------------------------------------+\n| C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Data\\ |\n+---------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1714,
"s": 1653,
"text": "Now we can reach the directory from the above sample output."
},
{
"code": null,
"e": 1775,
"s": 1714,
"text": "Here is the snapshot that displays the MySQL data directory."
}
] |
Strings in Octave GNU | 06 Jun, 2022
In Octave GNU, A string is basically the collection of characters enclosed between double quotes (“) or single quotes (‘).
Example of strings
“This is a string”
‘This is also a string’
In Octave, there is no limit for the length of the string. i.e. It can be of any size. Character array is used to represent a string in Octave
Escape Sequence : Some double-quoted(“) string containing backslash(‘\’), change the meaning of that string constant, these types of strings are special and are used for special purposes. The backslash (‘\’) character is known as Escape Character.
Below is the list of some Escape Sequences
Escape Sequence
Meaning
\\
\”
\’
\0
\a
\b
\f
\n
\r
\t
\v
\nnn
Represents the octal value nnn, where nnn are one to three digits between 0
and 7
\xhh...
Represents the hexadecimal value hh, where hh are hexadecimal digits (‘0’
through ‘9’ and either ‘A’ through ‘F’ or ‘a’ through ‘f’).
String creation in Octave
In the octave, a string can be generated by using the double quotes, single quotes, and blanks()
Using Double Quotes : varA = “String”;
Using Single Quotes : varB = ‘String’;
Using blanks() : varC = blanks(10), create a 10 size string of blank equivalent to ” “
String concatenation in Octave
In the octave, there are two ways to concatenate strings
Using Square Brackett ‘[]’ : newStr = [oldStr1 oldStr2]; or newStr = [oldStr1, oldStr2];
Using strcat() : newStr = strcat(oldStr1, oldStr2);
String comparison in Octave
In the octave, strcmp() is used to compare two strings
There are various versions of strcmp():
strcmp(s1, s2, n) : compares the first n characters of s1 with s2
strcmpi(s1, s2) : case insensitive strcmp()
Below is the octave code to demonstrate the above-mentioned functions and concepts
MATLAB
% String creation in Octavestr1 = "This is a string";str2 = 'This is also a string';str3 = blanks(10);printf("String created using \" is : %s .\n", str1);printf("String created using \' is : %s .\n", str2);printf("String created using blanks() is : %s .\n\n", str3); % String Concatenation in Octavedisplay("String Concatenation")oldStr1 = "first";oldStr2 = "last";newStr1 = [oldStr1 oldStr2];newStr2 = [oldStr1, oldStr2];newStr3 = strcat(oldStr1, oldStr2);printf("String Concatenation using [ ] is : %s .\n", newStr1);printf("String Concatenation using [, ] is : %s .\n", newStr2);printf("String Concatenation using strcat() is : %s .\n\n", newStr3); % String comparison in Octavedisplay("String Comparison")printf("Comparison using strcmp() : ");disp(strcmp(str1, str2));
Output:
String created using " is : This is a string .
String created using ' is : This is also a string .
String created using blanks() is : .
String Concatenation
String Concatenation using [ ] is : firstlast .
String Concatenation using [, ] is : firstlast .
String Concatenation using strcat() is : firstlast .
String Comparison
Comparison using strcmp() : 0
simranarora5sos
Octave-GNU
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "In Octave GNU, A string is basically the collection of characters enclosed between double quotes (“) or single quotes (‘)."
},
{
"code": null,
"e": 170,
"s": 151,
"text": "Example of strings"
},
{
"code": null,
"e": 189,
"s": 170,
"text": "“This is a string”"
},
{
"code": null,
"e": 213,
"s": 189,
"text": "‘This is also a string’"
},
{
"code": null,
"e": 356,
"s": 213,
"text": "In Octave, there is no limit for the length of the string. i.e. It can be of any size. Character array is used to represent a string in Octave"
},
{
"code": null,
"e": 604,
"s": 356,
"text": "Escape Sequence : Some double-quoted(“) string containing backslash(‘\\’), change the meaning of that string constant, these types of strings are special and are used for special purposes. The backslash (‘\\’) character is known as Escape Character."
},
{
"code": null,
"e": 647,
"s": 604,
"text": "Below is the list of some Escape Sequences"
},
{
"code": null,
"e": 663,
"s": 647,
"text": "Escape Sequence"
},
{
"code": null,
"e": 671,
"s": 663,
"text": "Meaning"
},
{
"code": null,
"e": 674,
"s": 671,
"text": "\\\\"
},
{
"code": null,
"e": 677,
"s": 674,
"text": "\\”"
},
{
"code": null,
"e": 680,
"s": 677,
"text": "\\’"
},
{
"code": null,
"e": 683,
"s": 680,
"text": "\\0"
},
{
"code": null,
"e": 686,
"s": 683,
"text": "\\a"
},
{
"code": null,
"e": 689,
"s": 686,
"text": "\\b"
},
{
"code": null,
"e": 692,
"s": 689,
"text": "\\f"
},
{
"code": null,
"e": 695,
"s": 692,
"text": "\\n"
},
{
"code": null,
"e": 698,
"s": 695,
"text": "\\r"
},
{
"code": null,
"e": 701,
"s": 698,
"text": "\\t"
},
{
"code": null,
"e": 704,
"s": 701,
"text": "\\v"
},
{
"code": null,
"e": 709,
"s": 704,
"text": "\\nnn"
},
{
"code": null,
"e": 785,
"s": 709,
"text": "Represents the octal value nnn, where nnn are one to three digits between 0"
},
{
"code": null,
"e": 791,
"s": 785,
"text": "and 7"
},
{
"code": null,
"e": 799,
"s": 791,
"text": "\\xhh..."
},
{
"code": null,
"e": 873,
"s": 799,
"text": "Represents the hexadecimal value hh, where hh are hexadecimal digits (‘0’"
},
{
"code": null,
"e": 933,
"s": 873,
"text": "through ‘9’ and either ‘A’ through ‘F’ or ‘a’ through ‘f’)."
},
{
"code": null,
"e": 959,
"s": 933,
"text": "String creation in Octave"
},
{
"code": null,
"e": 1056,
"s": 959,
"text": "In the octave, a string can be generated by using the double quotes, single quotes, and blanks()"
},
{
"code": null,
"e": 1095,
"s": 1056,
"text": "Using Double Quotes : varA = “String”;"
},
{
"code": null,
"e": 1134,
"s": 1095,
"text": "Using Single Quotes : varB = ‘String’;"
},
{
"code": null,
"e": 1230,
"s": 1134,
"text": "Using blanks() : varC = blanks(10), create a 10 size string of blank equivalent to ” “"
},
{
"code": null,
"e": 1261,
"s": 1230,
"text": "String concatenation in Octave"
},
{
"code": null,
"e": 1318,
"s": 1261,
"text": "In the octave, there are two ways to concatenate strings"
},
{
"code": null,
"e": 1409,
"s": 1318,
"text": "Using Square Brackett ‘[]’ : newStr = [oldStr1 oldStr2]; or newStr = [oldStr1, oldStr2];"
},
{
"code": null,
"e": 1461,
"s": 1409,
"text": "Using strcat() : newStr = strcat(oldStr1, oldStr2);"
},
{
"code": null,
"e": 1489,
"s": 1461,
"text": "String comparison in Octave"
},
{
"code": null,
"e": 1544,
"s": 1489,
"text": "In the octave, strcmp() is used to compare two strings"
},
{
"code": null,
"e": 1584,
"s": 1544,
"text": "There are various versions of strcmp():"
},
{
"code": null,
"e": 1650,
"s": 1584,
"text": "strcmp(s1, s2, n) : compares the first n characters of s1 with s2"
},
{
"code": null,
"e": 1694,
"s": 1650,
"text": "strcmpi(s1, s2) : case insensitive strcmp()"
},
{
"code": null,
"e": 1777,
"s": 1694,
"text": "Below is the octave code to demonstrate the above-mentioned functions and concepts"
},
{
"code": null,
"e": 1784,
"s": 1777,
"text": "MATLAB"
},
{
"code": "% String creation in Octavestr1 = \"This is a string\";str2 = 'This is also a string';str3 = blanks(10);printf(\"String created using \\\" is : %s .\\n\", str1);printf(\"String created using \\' is : %s .\\n\", str2);printf(\"String created using blanks() is : %s .\\n\\n\", str3); % String Concatenation in Octavedisplay(\"String Concatenation\")oldStr1 = \"first\";oldStr2 = \"last\";newStr1 = [oldStr1 oldStr2];newStr2 = [oldStr1, oldStr2];newStr3 = strcat(oldStr1, oldStr2);printf(\"String Concatenation using [ ] is : %s .\\n\", newStr1);printf(\"String Concatenation using [, ] is : %s .\\n\", newStr2);printf(\"String Concatenation using strcat() is : %s .\\n\\n\", newStr3); % String comparison in Octavedisplay(\"String Comparison\")printf(\"Comparison using strcmp() : \");disp(strcmp(str1, str2));",
"e": 2560,
"s": 1784,
"text": null
},
{
"code": null,
"e": 2568,
"s": 2560,
"text": "Output:"
},
{
"code": null,
"e": 2936,
"s": 2568,
"text": "String created using \" is : This is a string .\nString created using ' is : This is also a string .\nString created using blanks() is : .\n\nString Concatenation\nString Concatenation using [ ] is : firstlast .\nString Concatenation using [, ] is : firstlast .\nString Concatenation using strcat() is : firstlast .\n\nString Comparison\nComparison using strcmp() : 0"
},
{
"code": null,
"e": 2952,
"s": 2936,
"text": "simranarora5sos"
},
{
"code": null,
"e": 2963,
"s": 2952,
"text": "Octave-GNU"
},
{
"code": null,
"e": 2984,
"s": 2963,
"text": "Programming Language"
}
] |
SQL | ENCRYPT Function | 31 Oct, 2019
The SQL Encrypt function is used to encrypt a string using UNIX crypt(). The function is based on Unix crypt() system call, hence it returns NULL on Windows systems. The Encrypt function accepts two parameters which are the string and the salt to be encrypted.The Encrypt function returns a binary string.
Syntax:
ENCRYPT(string, salt)
Parameters Used:
string – It is used to specify the plain text string that is to be encrypted using UNIX crypt().
salt – It is used to specify a string that is at least 2 characters long and cab be used in the encryption process. If salt is not provided, the ENCRYPT function uses a random value.
Return Value:The Encrypt function in SQL returns a binary string.
The Encrypt function returns null in the following cases:
If salt is less than 2 characters in length, then the Encrypt function returns NULL.
If the string is NULL, then the Encrypt function returns NULL.
If UNIX crypt() is not available on the system, then the Encrypt function returns NULL.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing Encrypt function on a string.
SELECT
ENCRYPT('xyz');
Output:
sf3Le/pz2ApNY
Example-2: Implementing Encrypt function on a bigger string.
SELECT
ENCRYPT('geeksforgeeks');
Output:
.mblNS3yOZxb2
Example-3: Implementing Encrypt function on a string by passing both the arguments.
SELECT
ENCRYPT('geeksforgeeks', '123');
Output:
12SrVMQf0pwFU
Example-4: Implementing Encrypt function on a string by passing less than 2 characters in the salt argument.
SELECT
ENCRYPT('geeksforgeeks', '2');
Output:
NULL
Since the salt argument is less than 2 characters in length, the Encrypt function returns NULL.
Example-5: Implementing Encrypt function on a NULL string.
SELECT
ENCRYPT(NULL);
Output:
NULL
SQL-Functions
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 334,
"s": 28,
"text": "The SQL Encrypt function is used to encrypt a string using UNIX crypt(). The function is based on Unix crypt() system call, hence it returns NULL on Windows systems. The Encrypt function accepts two parameters which are the string and the salt to be encrypted.The Encrypt function returns a binary string."
},
{
"code": null,
"e": 342,
"s": 334,
"text": "Syntax:"
},
{
"code": null,
"e": 364,
"s": 342,
"text": "ENCRYPT(string, salt)"
},
{
"code": null,
"e": 381,
"s": 364,
"text": "Parameters Used:"
},
{
"code": null,
"e": 478,
"s": 381,
"text": "string – It is used to specify the plain text string that is to be encrypted using UNIX crypt()."
},
{
"code": null,
"e": 661,
"s": 478,
"text": "salt – It is used to specify a string that is at least 2 characters long and cab be used in the encryption process. If salt is not provided, the ENCRYPT function uses a random value."
},
{
"code": null,
"e": 727,
"s": 661,
"text": "Return Value:The Encrypt function in SQL returns a binary string."
},
{
"code": null,
"e": 785,
"s": 727,
"text": "The Encrypt function returns null in the following cases:"
},
{
"code": null,
"e": 870,
"s": 785,
"text": "If salt is less than 2 characters in length, then the Encrypt function returns NULL."
},
{
"code": null,
"e": 933,
"s": 870,
"text": "If the string is NULL, then the Encrypt function returns NULL."
},
{
"code": null,
"e": 1021,
"s": 933,
"text": "If UNIX crypt() is not available on the system, then the Encrypt function returns NULL."
},
{
"code": null,
"e": 1050,
"s": 1021,
"text": "Supported Versions of MySQL:"
},
{
"code": null,
"e": 1060,
"s": 1050,
"text": "MySQL 5.7"
},
{
"code": null,
"e": 1070,
"s": 1060,
"text": "MySQL 5.6"
},
{
"code": null,
"e": 1080,
"s": 1070,
"text": "MySQL 5.5"
},
{
"code": null,
"e": 1090,
"s": 1080,
"text": "MySQL 5.1"
},
{
"code": null,
"e": 1100,
"s": 1090,
"text": "MySQL 5.0"
},
{
"code": null,
"e": 1110,
"s": 1100,
"text": "MySQL 4.1"
},
{
"code": null,
"e": 1164,
"s": 1110,
"text": "Example-1: Implementing Encrypt function on a string."
},
{
"code": null,
"e": 1189,
"s": 1164,
"text": "SELECT \nENCRYPT('xyz'); "
},
{
"code": null,
"e": 1197,
"s": 1189,
"text": "Output:"
},
{
"code": null,
"e": 1212,
"s": 1197,
"text": "sf3Le/pz2ApNY "
},
{
"code": null,
"e": 1273,
"s": 1212,
"text": "Example-2: Implementing Encrypt function on a bigger string."
},
{
"code": null,
"e": 1308,
"s": 1273,
"text": "SELECT \nENCRYPT('geeksforgeeks'); "
},
{
"code": null,
"e": 1316,
"s": 1308,
"text": "Output:"
},
{
"code": null,
"e": 1331,
"s": 1316,
"text": ".mblNS3yOZxb2 "
},
{
"code": null,
"e": 1415,
"s": 1331,
"text": "Example-3: Implementing Encrypt function on a string by passing both the arguments."
},
{
"code": null,
"e": 1457,
"s": 1415,
"text": "SELECT \nENCRYPT('geeksforgeeks', '123'); "
},
{
"code": null,
"e": 1465,
"s": 1457,
"text": "Output:"
},
{
"code": null,
"e": 1480,
"s": 1465,
"text": "12SrVMQf0pwFU "
},
{
"code": null,
"e": 1589,
"s": 1480,
"text": "Example-4: Implementing Encrypt function on a string by passing less than 2 characters in the salt argument."
},
{
"code": null,
"e": 1629,
"s": 1589,
"text": "SELECT \nENCRYPT('geeksforgeeks', '2'); "
},
{
"code": null,
"e": 1637,
"s": 1629,
"text": "Output:"
},
{
"code": null,
"e": 1643,
"s": 1637,
"text": "NULL "
},
{
"code": null,
"e": 1739,
"s": 1643,
"text": "Since the salt argument is less than 2 characters in length, the Encrypt function returns NULL."
},
{
"code": null,
"e": 1798,
"s": 1739,
"text": "Example-5: Implementing Encrypt function on a NULL string."
},
{
"code": null,
"e": 1822,
"s": 1798,
"text": "SELECT \nENCRYPT(NULL); "
},
{
"code": null,
"e": 1830,
"s": 1822,
"text": "Output:"
},
{
"code": null,
"e": 1836,
"s": 1830,
"text": "NULL "
},
{
"code": null,
"e": 1850,
"s": 1836,
"text": "SQL-Functions"
},
{
"code": null,
"e": 1859,
"s": 1850,
"text": "SQLmysql"
},
{
"code": null,
"e": 1863,
"s": 1859,
"text": "SQL"
},
{
"code": null,
"e": 1867,
"s": 1863,
"text": "SQL"
},
{
"code": null,
"e": 1965,
"s": 1867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2031,
"s": 1965,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2055,
"s": 2031,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2088,
"s": 2055,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2120,
"s": 2088,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2137,
"s": 2120,
"text": "SQL using Python"
},
{
"code": null,
"e": 2215,
"s": 2137,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2251,
"s": 2215,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2281,
"s": 2251,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2312,
"s": 2281,
"text": "SQL Query to Compare Two Dates"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.